<template>
  <el-card shadow="never" class="steps-card">
    <div slot="header" class="section-header">
      <div class="header-left">
        <span>{{ title }}</span>
        <el-tag size="mini" type="info">
          总计 {{ steps.length }}
        </el-tag>
        <el-tag size="mini" type="warning" v-if="stepStats.pending">
          待执行 {{ stepStats.pending }}
        </el-tag>
        <el-tag size="mini" type="success" v-if="stepStats.completed">
          已完成 {{ stepStats.completed }}
        </el-tag>
      </div>
      <div class="header-actions">
        <el-tooltip content="刷新行动项" placement="top">
          <el-button
            icon="el-icon-refresh"
            size="mini"
            type="text"
            :loading="loading"
            @click="$emit('refresh')"
          />
        </el-tooltip>
      </div>
    </div>
    <div v-loading="loading">
      <template v-if="steps && steps.length">
        <el-table
          :data="steps"
          border
          size="small"
          :height="tableHeight"
          :header-cell-style="tableHeaderStyle"
        >
          <el-table-column
            prop="order"
            label="#"
            width="50"
            align="center"
            v-if="showOrderColumn"
          />
          <el-table-column prop="name" label="行动项" min-width="160" show-overflow-tooltip />
          <el-table-column prop="executor" label="执行人" min-width="120" show-overflow-tooltip />
          <el-table-column label="状态" min-width="120">
            <template slot-scope="scope">
              <el-tag :type="getStatusTag(scope.row.status)" size="mini">
                {{ getStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.description || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="$emit('view-step', scope.row)">
                详情
              </el-button>
              <el-dropdown trigger="click" @command="cmd => handleAction(cmd, scope.row)">
                <span class="el-dropdown-link action-more">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="start" v-if="isPending(scope.row)">开始执行</el-dropdown-item>
                  <el-dropdown-item command="complete" v-if="isExecutable(scope.row)">标记完成</el-dropdown-item>
                  <el-dropdown-item command="fail" v-if="isExecutable(scope.row)">标记失败</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-empty v-else description="暂无行动项" />
    </div>
  </el-card>
</template>

<script>
import { startDispatchStep, completeDispatchStep, failDispatchStep, markDispatchTaskInProgress } from '@/api/emergency/dispatchTask'

const STATUS_LABELS = {
  pending: '待执行',
  published: '待执行',
  in_progress: '执行中',
  completed: '已完成',
  done: '已完成',
  failed: '已失败',
  cancelled: '已取消'
}

const STATUS_TAGS = {
  pending: 'info',
  published: 'info',
  in_progress: 'primary',
  completed: 'success',
  done: 'success',
  failed: 'danger',
  cancelled: 'warning'
}

export default {
  name: 'TaskStepsCard',
  props: {
    steps: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    },
    showOrderColumn: {
      type: Boolean,
      default: false
    },
    tableHeight: {
      type: [Number, String],
      default: 240
    },
    title: {
      type: String,
      default: '行动项'
    },
    taskId: {
      type: [Number, String],
      required: true
    },
    task: {
      type: Object,
      default: null
    }
  },
  computed: {
    stepStats() {
      const stats = { pending: 0, completed: 0 }
      this.steps.forEach(step => {
        const status = step.status
        if (status === 'completed' || status === 'done') {
          stats.completed += 1
        } else if (status === 'pending' || status === 'published') {
          stats.pending += 1
        }
      })
      return stats
    },
    tableHeaderStyle() {
      return {
        background: '#f8f8f8',
        color: '#606266',
        fontWeight: 500
      }
    }
  },
  methods: {
    getStatusLabel(status) {
      return STATUS_LABELS[status] || status || '未知'
    },
    getStatusTag(status) {
      return STATUS_TAGS[status] || 'info'
    },
    async handleAction(command, step) {
      try {
        switch (command) {
          case 'start':
            await this.handleStartStep(step)
            break
          case 'complete':
            await this.handleCompleteStep(step)
            break
          case 'fail':
            await this.handleFailStep(step)
            break
          default:
            this.$emit('step-action', { command, step })
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('操作失败:', error)
        }
      }
    },
    async handleStartStep(step) {
      try {
        const res = await startDispatchStep(this.taskId, step.id)
        if (res && res.code === 200) {
          this.$message.success('行动项已开始执行')
          
          // 如果任务状态是published，自动将任务状态变为执行中
          if (this.task && this.task.status === 'published') {
            try {
              await markDispatchTaskInProgress(this.taskId)
              // 触发刷新事件，让父组件更新任务状态
              this.$emit('task-status-changed')
            } catch (error) {
              console.warn('自动更新任务状态失败:', error)
              // 不显示错误，因为行动项已经开始执行了
            }
          }
          
          this.$emit('refresh')
        } else {
          this.$message.error(res.msg || '操作失败')
        }
      } catch (error) {
        console.error('开始执行行动项失败:', error)
        this.$message.error('开始执行行动项失败，请稍后重试')
      }
    },
    async handleCompleteStep(step) {
      try {
        const { value: remark } = await this.$prompt('请输入完成备注（可选）', '标记完成', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'textarea',
          inputPlaceholder: '请输入完成备注...'
        }).catch(() => ({ value: null }))
        
        if (remark === null) return // 用户取消
        
        const res = await completeDispatchStep(this.taskId, step.id, remark)
        if (res && res.code === 200) {
          this.$message.success('行动项已标记为完成')
          this.$emit('refresh')
        } else {
          this.$message.error(res.msg || '操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('完成行动项失败:', error)
          this.$message.error('完成行动项失败，请稍后重试')
        }
      }
    },
    async handleFailStep(step) {
      try {
        const { value: reason } = await this.$prompt('请输入失败原因（可选）', '标记失败', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'textarea',
          inputPlaceholder: '请输入失败原因...'
        }).catch(() => ({ value: null }))
        
        if (reason === null) return // 用户取消
        
        const res = await failDispatchStep(this.taskId, step.id, reason)
        if (res && res.code === 200) {
          this.$message.success('行动项已标记为失败')
          this.$emit('refresh')
        } else {
          this.$message.error(res.msg || '操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('标记失败失败:', error)
          this.$message.error('标记失败失败，请稍后重试')
        }
      }
    },
    isPending(step) {
      return ['pending', 'published'].includes(step.status)
    },
    isExecutable(step) {
      return ['in_progress', 'pending', 'published'].includes(step.status)
    }
  }
}
</script>

<style lang="scss" scoped>
.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 4px;
}

.action-more {
  font-size: 12px;
  color: #409EFF;
  cursor: pointer;
}
</style>