<template>
  <div class="plan-detail-page app-container">
    <el-page-header class="mb16" @back="handleBack" content="预案详情" />

    <el-card shadow="never" class="mb16" v-loading="loadingPlan">
      <el-row :gutter="20">
        <el-col :md="16" :sm="24">
          <h2 class="plan-title">
            {{ planInfo.planName || '-' }}
            <el-tag size="mini" :type="statusTag(planInfo.status)">{{ renderStatus(planInfo.status) }}</el-tag>
          </h2>
          <el-descriptions :column="2" size="small" border>
            <el-descriptions-item label="编号">{{ planInfo.planNo || '-' }}</el-descriptions-item>
            <el-descriptions-item label="版本">{{ planInfo.version || '-' }}</el-descriptions-item>
            <el-descriptions-item label="事件类型">{{ planInfo.eventType || '-' }}</el-descriptions-item>
            <el-descriptions-item label="事件级别">{{ renderEventLevel(planInfo.eventLevel) }}</el-descriptions-item>
            <el-descriptions-item label="引用次数">{{ planInfo.usageCount || 0 }}</el-descriptions-item>
            <el-descriptions-item label="最后使用时间">{{ parseTime(planInfo.lastUsedAt) }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :md="8" :sm="24" class="text-right">
          <el-button
            type="primary"
            icon="el-icon-upload2"
            @click="handlePublish"
            v-hasPermi="['emergency:plan:publish']"
          >
            发布
          </el-button>
        </el-col>
      </el-row>
      <el-divider />
      <p class="plan-desc">{{ planInfo.description || '暂无描述' }}</p>
    </el-card>

    <el-card shadow="never">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="概览" name="overview">
          <el-descriptions :column="3" border size="small">
            <el-descriptions-item label="创建人">{{ planInfo.createBy || '-' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ parseTime(planInfo.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ parseTime(planInfo.updateTime) }}</el-descriptions-item>
            <el-descriptions-item label="审批人">{{ planInfo.approverName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="审批时间">{{ parseTime(planInfo.approvalTime) }}</el-descriptions-item>
            <el-descriptions-item label="发布状态">{{ renderStatus(planInfo.status) }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <el-tab-pane label="执行对象" name="participants">
          <div class="tab-toolbar">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-plus"
              @click="openParticipantDialog()"
              v-hasPermi="['emergency:plan:participant:add']"
            >
              新增执行对象
            </el-button>
          </div>
          <el-table :data="participants" border>
            <el-table-column prop="displayName" label="名称" min-width="150" />
            <el-table-column prop="participantType" label="类型" width="120" />
            <el-table-column prop="role" label="角色职责" min-width="160" show-overflow-tooltip />
            <el-table-column prop="sortOrder" label="顺序" width="80" />
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="openParticipantDialog(scope.row)">编辑</el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="removeParticipant(scope.row)"
                  v-hasPermi="['emergency:plan:participant:remove']"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="行动项" name="steps">
          <div class="tab-toolbar">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-plus"
              @click="openStepDialog()"
              v-hasPermi="['emergency:plan:step:add']"
            >
              新增行动项
            </el-button>
          </div>
          <el-table :data="steps" border>
            <el-table-column prop="stepOrder" label="顺序" width="80" />
            <el-table-column prop="stepName" label="行动项" min-width="180" show-overflow-tooltip />
            <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
            <el-table-column prop="estimatedDuration" label="预计耗时(分钟)" width="140" />
            <el-table-column label="资源" width="160">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="openResourceManager(scope.row)">
                  管理资源 ({{ (resourcesMap[scope.row.id] || []).length }})
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="openStepDialog(scope.row)">编辑</el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="removeStep(scope.row)"
                  v-hasPermi="['emergency:plan:step:remove']"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="版本管理" name="versions">
          <el-table :data="versions" border>
            <el-table-column prop="version" label="版本号" width="120" />
            <el-table-column prop="changeLog" label="变更说明" min-width="220" show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间" width="180">
              <template slot-scope="scope">{{ parseTime(scope.row.createTime) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="160">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="mini"
                  @click="restoreVersion(scope.row)"
                  v-hasPermi="['emergency:plan:version:restore']"
                >
                  恢复
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="审批记录" name="approvals">
          <el-table :data="approvals" border>
            <el-table-column prop="approverName" label="审批人" width="160" />
            <el-table-column prop="approvalStatus" label="状态" width="120" />
            <el-table-column prop="approvalComment" label="意见" min-width="220" show-overflow-tooltip />
            <el-table-column prop="approvalTime" label="审批时间" width="180">
              <template slot-scope="scope">{{ parseTime(scope.row.approvalTime) }}</template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="使用记录" name="usage">
          <el-table :data="usageRecords" border>
            <el-table-column prop="dispatchTaskId" label="调度任务ID" width="140" />
            <el-table-column prop="source" label="来源" width="120" />
            <el-table-column prop="rating" label="评分" width="80" />
            <el-table-column prop="feedback" label="反馈" min-width="220" show-overflow-tooltip />
            <el-table-column prop="createTime" label="记录时间" width="180">
              <template slot-scope="scope">{{ parseTime(scope.row.createTime) }}</template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- Participant dialog -->
    <el-dialog :title="participantDialog.title" :visible.sync="participantDialog.visible" width="520px">
      <el-form ref="participantForm" :model="participantDialog.form" :rules="participantRules" label-width="110px">
        <el-form-item label="显示名称" prop="displayName">
          <el-input v-model="participantDialog.form.displayName" placeholder="请输入显示名称" />
        </el-form-item>
        <el-form-item label="类型" prop="participantType">
          <el-select v-model="participantDialog.form.participantType" placeholder="请选择类型">
            <el-option label="队伍成员" value="TEAM_MEMBER" />
            <el-option label="专家" value="EXPERT" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色/职责">
          <el-input v-model="participantDialog.form.role" placeholder="请输入角色" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="participantDialog.form.sortOrder" :min="1" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitParticipant">确 定</el-button>
        <el-button @click="participantDialog.visible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- Step dialog -->
    <el-dialog :title="stepDialog.title" :visible.sync="stepDialog.visible" width="540px">
      <el-form ref="stepForm" :model="stepDialog.form" :rules="stepRules" label-width="110px">
        <el-form-item label="行动项名称" prop="stepName">
          <el-input v-model="stepDialog.form.stepName" placeholder="请输入行动项名称" />
        </el-form-item>
        <el-form-item label="顺序" prop="stepOrder">
          <el-input-number v-model="stepDialog.form.stepOrder" :min="1" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="stepDialog.form.description" />
        </el-form-item>
        <el-form-item label="预计耗时(分钟)">
          <el-input-number v-model="stepDialog.form.estimatedDuration" :min="0" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitStep">确 定</el-button>
        <el-button @click="stepDialog.visible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- Resource manager -->
    <el-drawer
      title="行动项资源"
      :visible.sync="resourceManager.visible"
      size="40%"
      append-to-body
    >
      <div class="drawer-header">
        <span>{{ resourceManager.step && resourceManager.step.stepName }}</span>
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="openResourceDialog()">
          新增资源
        </el-button>
      </div>
      <el-table :data="resourceManager.list" border>
        <el-table-column prop="resourceType" label="资源类型" width="120" />
        <el-table-column prop="resourceRefId" label="引用ID" width="120" />
        <el-table-column prop="suggestedQuantity" label="建议数量" width="120" />
        <el-table-column prop="required" label="是否必需" width="100">
          <template slot-scope="scope">
            <el-tag size="mini" :type="scope.row.required ? 'danger' : 'info'">
              {{ scope.row.required ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="usageNote" label="说明" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="openResourceDialog(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="removeResource(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <el-dialog :title="resourceDialog.title" :visible.sync="resourceDialog.visible" width="480px">
      <el-form ref="resourceForm" :model="resourceDialog.form" :rules="resourceRules" label-width="110px">
        <el-form-item label="资源类型" prop="resourceType">
          <el-select v-model="resourceDialog.form.resourceType" placeholder="请选择">
            <el-option label="物资" value="material" />
            <el-option label="装备" value="equipment" />
            <el-option label="车辆" value="vehicle" />
          </el-select>
        </el-form-item>
        <el-form-item label="引用资源ID">
          <el-input-number v-model="resourceDialog.form.resourceRefId" :min="1" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="建议数量">
          <el-input-number v-model="resourceDialog.form.suggestedQuantity" :min="1" />
        </el-form-item>
        <el-form-item label="是否必需">
          <el-switch v-model="resourceDialog.form.required" />
        </el-form-item>
        <el-form-item label="使用说明">
          <el-input type="textarea" v-model="resourceDialog.form.usageNote" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitResource">确 定</el-button>
        <el-button @click="resourceDialog.visible = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getPlan,
  publishPlan,
  listPlanParticipants,
  addPlanParticipant,
  updatePlanParticipant,
  deletePlanParticipants,
  listPlanSteps,
  addPlanStep,
  updatePlanStep,
  deletePlanSteps,
  listStepResources,
  addStepResource,
  updateStepResource,
  deleteStepResources,
  listPlanVersions,
  restorePlanVersion,
  listPlanUsage
} from '@/api/emergency/plan'
import { parseTime } from '@/utils/shuyu-utils'

export default {
  name: 'PlanDetail',
  data() {
    return {
      planId: null,
      planInfo: {},
      loadingPlan: false,
      activeTab: 'overview',
      participants: [],
      steps: [],
      resourcesMap: {},
      versions: [],
      approvals: [],
      usageRecords: [],
      participantDialog: {
        visible: false,
        title: '',
        form: {}
      },
      stepDialog: {
        visible: false,
        title: '',
        form: {}
      },
      resourceManager: {
        visible: false,
        step: null,
        list: []
      },
      resourceDialog: {
        visible: false,
        title: '',
        form: {}
      },
      participantRules: {
        displayName: [{ required: true, message: '请输入显示名称', trigger: 'blur' }],
        participantType: [{ required: true, message: '请选择类型', trigger: 'change' }]
      },
      stepRules: {
        stepName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        stepOrder: [{ required: true, message: '请输入顺序', trigger: 'change' }]
      },
      resourceRules: {
        resourceType: [{ required: true, message: '请选择资源类型', trigger: 'change' }]
      }
    }
  },
  created() {
    this.planId = this.$route.query.id
    if (!this.planId) {
      this.$message.error('缺少预案ID参数')
      this.$router.back()
      return
    }
    this.loadPlanDetail()
  },
  methods: {
    parseTime,
    handleBack() {
      this.$router.back()
    },
    renderEventLevel(value) {
      const map = { I: 'Ⅰ级', II: 'Ⅱ级', III: 'Ⅲ级', IV: 'Ⅳ级' }
      return map[value] || value || '-'
    },
    renderStatus(value) {
      const map = {
        draft: '草稿',
        approving: '审批中',
        approved: '已批准',
        published: '已发布',
        archived: '已归档',
        rejected: '已驳回'
      }
      return map[value] || value || '-'
    },
    statusTag(value) {
      const map = {
        draft: 'info',
        approving: 'warning',
        approved: 'success',
        published: 'success',
        archived: 'default',
        rejected: 'danger'
      }
      return map[value] || 'default'
    },
    async loadPlanDetail() {
      this.loadingPlan = true
      try {
        const [planRes] = await Promise.all([getPlan(this.planId)])
        this.planInfo = planRes.data || planRes
        await Promise.all([
          this.fetchParticipants(),
          this.fetchSteps(),
          this.fetchVersions(),
          this.fetchUsage()
        ])
      } finally {
        this.loadingPlan = false
      }
    },
    async fetchParticipants() {
      const res = await listPlanParticipants(this.planId)
      this.participants = res.data || res || []
    },
    async fetchSteps() {
      const res = await listPlanSteps(this.planId)
      this.steps = res.data || res || []
      await this.loadStepResources()
    },
    async loadStepResources() {
      const map = {}
      await Promise.all(
        this.steps.map(async step => {
          const res = await listStepResources(this.planId, step.id)
          map[step.id] = res.data || res || []
        })
      )
      this.resourcesMap = map
    },
    async fetchVersions() {
      const res = await listPlanVersions(this.planId)
      this.versions = res.data || res || []
    },
    async fetchUsage() {
      const res = await listPlanUsage(this.planId)
      this.usageRecords = res.data || res || []
    },
    handlePublish() {
      this.$modal
        .confirm('确认发布该预案吗？')
        .then(() => publishPlan(this.planId))
        .then(() => {
          this.$modal.msgSuccess('发布成功')
          this.loadPlanDetail()
        })
        .catch(() => {})
    },
    openParticipantDialog(row) {
      this.participantDialog.visible = true
      this.participantDialog.title = row ? '编辑执行对象' : '新增执行对象'
      this.participantDialog.form = row
        ? Object.assign({}, row)
        : {
            displayName: '',
            participantType: '',
            role: '',
            sortOrder: this.participants.length + 1
          }
    },
    submitParticipant() {
      this.$refs.participantForm.validate(valid => {
        if (!valid) return
        const form = this.participantDialog.form
        const req = form.id
          ? updatePlanParticipant(this.planId, form.id, form)
          : addPlanParticipant(this.planId, form)
        req.then(() => {
          this.$modal.msgSuccess(form.id ? '更新成功' : '新增成功')
          this.participantDialog.visible = false
          this.fetchParticipants()
        })
      })
    },
    removeParticipant(row) {
      this.$modal
        .confirm('确认删除该执行对象吗？')
        .then(() => deletePlanParticipants(this.planId, row.id))
        .then(() => {
          this.$modal.msgSuccess('删除成功')
          this.fetchParticipants()
        })
        .catch(() => {})
    },
    openStepDialog(row) {
      this.stepDialog.visible = true
      this.stepDialog.title = row ? '编辑行动项' : '新增行动项'
      this.stepDialog.form = row
        ? Object.assign({}, row)
        : {
            stepName: '',
            stepOrder: this.steps.length + 1,
            description: '',
            estimatedDuration: 0
          }
    },
    submitStep() {
      this.$refs.stepForm.validate(valid => {
        if (!valid) return
        const form = this.stepDialog.form
        const req = form.id ? updatePlanStep(this.planId, form.id, form) : addPlanStep(this.planId, form)
        req.then(() => {
          this.$modal.msgSuccess(form.id ? '更新成功' : '新增成功')
          this.stepDialog.visible = false
          this.fetchSteps()
        })
      })
    },
    removeStep(row) {
      this.$modal
        .confirm('确认删除该行动项吗？')
        .then(() => deletePlanSteps(this.planId, row.id))
        .then(() => {
          this.$modal.msgSuccess('删除成功')
          this.fetchSteps()
        })
        .catch(() => {})
    },
    openResourceManager(step) {
      this.resourceManager.visible = true
      this.resourceManager.step = step
      this.resourceManager.list = this.resourcesMap[step.id] || []
    },
    openResourceDialog(row) {
      this.resourceDialog.visible = true
      this.resourceDialog.title = row ? '编辑资源' : '新增资源'
      this.resourceDialog.form = row
        ? Object.assign({}, row)
        : {
            resourceType: '',
            resourceRefId: null,
            suggestedQuantity: 1,
            required: false,
            usageNote: ''
          }
    },
    submitResource() {
      this.$refs.resourceForm.validate(valid => {
        if (!valid) return
        const stepId = this.resourceManager.step && this.resourceManager.step.id
        if (!stepId) return
        const form = this.resourceDialog.form
        const req = form.id
          ? updateStepResource(this.planId, stepId, form.id, form)
          : addStepResource(this.planId, stepId, form)
        req.then(() => {
          this.$modal.msgSuccess(form.id ? '更新成功' : '新增成功')
          this.resourceDialog.visible = false
          this.fetchSteps().then(() => {
            this.resourceManager.list = this.resourcesMap[stepId] || []
          })
        })
      })
    },
    removeResource(row) {
      const stepId = this.resourceManager.step && this.resourceManager.step.id
      if (!stepId) return
      this.$modal
        .confirm('确认删除该资源吗？')
        .then(() => deleteStepResources(this.planId, stepId, row.id))
        .then(() => {
          this.$modal.msgSuccess('删除成功')
          this.fetchSteps().then(() => {
            this.resourceManager.list = this.resourcesMap[stepId] || []
          })
        })
        .catch(() => {})
    },
    restoreVersion(row) {
      this.$modal
        .confirm(`确定恢复到版本 ${row.version} 吗？`)
        .then(() => restorePlanVersion(this.planId, row.id))
        .then(() => {
          this.$modal.msgSuccess('恢复成功')
          this.loadPlanDetail()
        })
        .catch(() => {})
    }
  }
}
</script>

<style scoped>
.mb16 {
  margin-bottom: 16px;
}
.plan-title {
  margin: 0 0 12px;
}
.plan-desc {
  margin: 0;
  color: #666;
}
.tab-toolbar {
  margin-bottom: 12px;
  text-align: right;
}
.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
</style>

