<template>
  <div v-if="visible">
    <div class="create-task-dialog" @click.stop>
      <div class="create-task-dialog-header">
        <span class="create-task-dialog-title">创建调度任务</span>
        <el-button 
          type="text" 
          icon="el-icon-close" 
          size="mini"
          @click="handleClose"
          class="create-task-dialog-close"
        ></el-button>
      </div>
      
      <div class="create-task-dialog-body">
        <!-- Event Context (Read-only) -->
        <div v-if="eventData" class="event-context">
          <div class="context-item">
            <span class="context-label">关联事件：</span>
            <span class="context-value">{{ eventData.eventNo || `事件-${eventData.id}` }}</span>
          </div>
          <div class="context-item">
            <span class="context-label">事件标题：</span>
            <span class="context-value">{{ eventData.title || '未命名事件' }}</span>
          </div>
        </div>
        
        <el-form 
          ref="taskForm" 
          :model="formData" 
          :rules="rules" 
          label-width="100px"
        >
          <el-form-item label="任务名称" prop="name">
            <el-input 
              v-model="formData.name" 
              placeholder="请输入任务名称"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
          
          <el-form-item label="任务描述" prop="description">
            <el-input 
              v-model="formData.description" 
              type="textarea"
              :rows="4"
              placeholder="请输入任务描述（可选）"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
          
          <el-form-item label="预案模板" prop="planId">
            <el-select 
              v-model="formData.planId" 
              placeholder="请选择预案模板（可选）"
              clearable
              filterable
              :loading="loadingPlans"
              @change="handlePlanChange"
            >
              <el-option
                v-for="plan in publishedPlans"
                :key="plan.id"
                :label="plan.planName"
                :value="plan.id"
              >
                <span>{{ plan.planName }}</span>
                <span style="color: #8492a6; font-size: 12px; margin-left: 8px;">{{ plan.planNo }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="create-task-dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          :loading="submitting"
          @click="handleSubmit"
        >
          创建
        </el-button>
      </div>
    </div>
    
    <div class="create-task-dialog-backdrop" @click="handleClose"></div>
  </div>
</template>

<script>
import { 
  addDispatchTask, 
  addDispatchParticipants, 
  upsertDispatchSteps, 
  allocateMaterialToStep, 
  allocateEquipmentToStep, 
  allocateVehicleToStep,
  listDispatchSteps,
  listDispatchTasks
} from '@/api/emergency/dispatchTask'
import { 
  listPlans, 
  getPlan, 
  listPlanParticipants, 
  listPlanSteps, 
  listStepResources,
  addPlanUsage,
  updatePlan
} from '@/api/emergency/plan'
import { getTeamMember } from '@/api/resource/team'
import { getExpert } from '@/api/resource/expert'
import { getMaterial } from '@/api/resource/material'
import { getEquipment } from '@/api/resource/equipment'
import { getVehicle } from '@/api/resource/vehicle'
import { listMaterialInventory } from '@/api/resource/material/inventory'

export default {
  name: 'CreateTaskDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    eventId: {
      type: [Number, String],
      default: null
    },
    eventData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      formData: {
        name: '',
        description: '',
        planId: null
      },
      rules: {
        name: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          { max: 200, message: '任务名称不能超过200个字符', trigger: 'blur' }
        ]
      },
      submitting: false,
      loadingPlans: false,
      publishedPlans: [],
      selectedPlanData: null
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.resetForm()
        this.setDefaultName()
        this.loadPublishedPlans()
      }
    },
    eventData: {
      immediate: true,
      handler() {
        if (this.visible) {
          this.setDefaultName()
        }
      }
    }
  },
  methods: {
    resetForm() {
      this.formData = {
        name: '',
        description: '',
        planId: null
      }
      this.selectedPlanData = null
      this.$nextTick(() => {
        if (this.$refs.taskForm) {
          this.$refs.taskForm.resetFields()
        }
      })
    },
    async loadPublishedPlans() {
      this.loadingPlans = true
      try {
        const res = await listPlans({ 
          // status: 'published', // 调试先不限制状态
          pageNum: 1,
          pageSize: 1000
        })
        const rows = res.rows || res.data || []
        this.publishedPlans = Array.isArray(rows) ? rows : []
      } catch (error) {
        console.error('加载预案列表失败:', error)
        this.$message.error('加载预案列表失败')
        this.publishedPlans = []
      } finally {
        this.loadingPlans = false
      }
    },
    async handlePlanChange(planId) {
      if (!planId) {
        this.selectedPlanData = null
        return
      }
      
      try {
        // 加载预案详情
        const [planRes, participantsRes, stepsRes] = await Promise.all([
          getPlan(planId),
          listPlanParticipants(planId),
          listPlanSteps(planId)
        ])
        
        const plan = planRes.data || planRes
        const participants = (participantsRes && participantsRes.code === 200 ? (participantsRes.data || participantsRes) : (participantsRes.data || participantsRes || [])) || []
        const steps = (stepsRes && stepsRes.code === 200 ? (stepsRes.data || stepsRes) : (stepsRes.data || stepsRes || [])) || []
        
        // 加载每个行动项的资源
        const stepsWithResources = await Promise.all(
          steps.map(async (step) => {
            if (!step || !step.id) return step
            try {
              const resourcesRes = await listStepResources(planId, step.id)
              const resources = (resourcesRes && resourcesRes.code === 200 ? (resourcesRes.data || resourcesRes) : (resourcesRes.data || resourcesRes || [])) || []
              return { ...step, resources: Array.isArray(resources) ? resources : [] }
            } catch (error) {
              console.error(`加载行动项 ${step.id} 的资源失败:`, error)
              return { ...step, resources: [] }
            }
          })
        )
        
        this.selectedPlanData = {
          plan,
          participants: Array.isArray(participants) ? participants : [],
          steps: stepsWithResources
        }
      } catch (error) {
        console.error('加载预案详情失败:', error)
        this.$message.error('加载预案详情失败')
        this.selectedPlanData = null
      }
    },
    setDefaultName() {
      if (this.eventData && !this.formData.name) {
        const eventTitle = this.eventData.title || this.eventData.eventNo
        this.formData.name = eventTitle ? `${eventTitle}的调度任务` : '调度任务'
      }
    },
    handleClose() {
      if (!this.submitting) {
        this.$emit('update:visible', false)  // For .sync modifier
        this.$emit('close')  // For explicit @close handler
      }
    },
    async handleSubmit() {
      this.$refs.taskForm.validate(async (valid) => {
        if (!valid) return
        
        this.submitting = true
        try {
          // Use entityId from eventData if available, otherwise use eventId (prefer numeric ID)
          const numericEventId = this.eventData?.entityId || this.eventId
          const taskName = this.formData.name.trim()
          const taskData = {
            eventId: numericEventId,
            name: taskName,
            description: this.formData.description.trim() || ''
          }
          
          // 创建任务
          const taskRes = await addDispatchTask(taskData)
          if (!taskRes || taskRes.code !== 200) {
            this.$message.error(taskRes?.msg || '创建任务失败，请稍后重试')
            return
          }
          
          // 如果选择了预案，需要通过刷新列表来获取任务ID
          if (this.formData.planId && this.selectedPlanData) {
            // 通过事件ID和任务名称查找刚创建的任务（带重试机制）
            const taskId = await this.findTaskIdByEventAndNameWithRetry(numericEventId, taskName)
            if (taskId) {
              // 导入预案数据
              await this.importPlanDataToTask(taskId, this.formData.planId, this.selectedPlanData)
            } else {
              this.$message.warning('任务已创建，但未能找到任务ID，预案数据可能未导入')
            }
          }
          
          this.$message.success('调度任务创建成功')
          // 触发父组件刷新任务列表
          this.$emit('success', { eventId: numericEventId, taskName })
          this.$emit('update:visible', false)  // For .sync modifier
          this.$emit('close')  // For explicit @close handler
        } catch (error) {
          console.error('创建任务失败:', error)
          this.$message.error(error.msg || error.message || '创建任务失败，请稍后重试')
        } finally {
          this.submitting = false
        }
      })
    },
    async findTaskIdByEventAndNameWithRetry(eventId, taskName, maxRetries = 5, delay = 500) {
      for (let i = 0; i < maxRetries; i++) {
        const taskId = await this.findTaskIdByEventAndName(eventId, taskName)
        if (taskId) {
          return taskId
        }
        // 如果不是最后一次重试，等待后重试
        if (i < maxRetries - 1) {
          await new Promise(resolve => setTimeout(resolve, delay))
        }
      }
      return null
    },
    async findTaskIdByEventAndName(eventId, taskName) {
      try {
        // 查询该事件下的所有任务
        const res = await listDispatchTasks({
          eventId: eventId,
          pageNum: 1,
          pageSize: 100
        })
        
        const tasks = res.rows || res.data || []
        if (!Array.isArray(tasks) || tasks.length === 0) {
          return null
        }
        
        // 筛选出名称相同的任务
        const matchingTasks = tasks.filter(task => 
          task.name && task.name.trim() === taskName
        )
        
        if (matchingTasks.length === 0) {
          return null
        }
        
        // 按创建时间排序，获取最新的任务
        matchingTasks.sort((a, b) => {
          const timeA = new Date(a.createTime || 0).getTime()
          const timeB = new Date(b.createTime || 0).getTime()
          return timeB - timeA
        })
        
        return matchingTasks[0].id || null
      } catch (error) {
        console.error('查找任务ID失败:', error)
        return null
      }
    },
    async importPlanDataToTask(taskId, planId, planData) {
      try {
        // 1. 导入执行对象（转换为参与方）
        if (planData.participants && planData.participants.length > 0) {
          const participants = []
          
          // 逐个查询详情并构建参与方数据
          for (const p of planData.participants) {
            if (!p.referenceMemberId && !p.referenceExpertId) {
              continue
            }
            
            let personDetails = null
            let participantType = p.participantType
            
            // 查询人员详情
            if (p.participantType === 'TEAM_MEMBER' && p.referenceMemberId && p.referenceTeamId) {
              try {
                const res = await getTeamMember(p.referenceTeamId, p.referenceMemberId)
                if (res && res.code === 200) {
                  personDetails = res.data || res
                }
              } catch (error) {
                console.warn('获取成员详情失败:', error)
              }
            } else if (p.participantType === 'EXPERT' && p.referenceExpertId) {
              try {
                const res = await getExpert(p.referenceExpertId)
                if (res && res.code === 200) {
                  personDetails = res.data || res
                }
              } catch (error) {
                console.warn('获取专家详情失败:', error)
              }
            }
            
            // 构建快照信息
            let snapshot = {}
            if (personDetails) {
              if (participantType === 'TEAM_MEMBER') {
                snapshot = {
                  name: personDetails.memberName || personDetails.name || p.displayName || '-',
                  phone: personDetails.phone || personDetails.telephone || personDetails.contact || '-',
                  unit: personDetails.teamName || '-',
                  role: personDetails.position || personDetails.role || p.role || '-',
                  position: personDetails.position || personDetails.role || p.role || '-',
                  specialty: personDetails.specialty || []
                }
              } else {
                snapshot = {
                  name: personDetails.expertName || personDetails.name || personDetails.personName || p.displayName || '-',
                  phone: personDetails.phone || personDetails.telephone || personDetails.contact || '-',
                  unit: personDetails.unit || personDetails.organization || '-',
                  role: '专家',
                  position: '专家',
                  specialty: personDetails.specialty || []
                }
              }
            } else {
              // 如果没有查询到详情，使用预案中的信息
              snapshot = {
                name: p.displayName || '-',
                phone: '-',
                unit: '-',
                role: p.role || '-',
                position: p.role || '-',
                specialty: []
              }
            }
            
            participants.push({
              personId: p.referenceMemberId || p.referenceExpertId,
              teamId: p.referenceTeamId || null,
              personSnapshot: JSON.stringify(snapshot)
            })
          }
        
          if (participants.length > 0) {
            await addDispatchParticipants(taskId, participants)
          }
        }
        
        // 2. 导入行动项
        if (planData.steps && planData.steps.length > 0) {
          const steps = planData.steps.map(step => ({
            stepOrder: step.stepOrder || 0,
            title: step.stepName || '',
            description: step.description || '',
            status: 'pending'
          }))
          
          await upsertDispatchSteps(taskId, steps)
          
          // 获取创建后的行动项列表（需要获取ID以关联资源）
          const stepsRes = await listDispatchSteps(taskId)
          const createdSteps = (stepsRes && stepsRes.code === 200 ? (stepsRes.data || stepsRes) : (stepsRes.data || stepsRes || [])) || []
          
          // 3. 导入行动项的资源
          if (createdSteps.length > 0 && planData.steps.length > 0) {
            // 按照 stepOrder 匹配行动项（创建时保持顺序，所以按索引匹配应该可以）
            // 但为了更安全，我们按照 stepOrder 来匹配
            const stepMap = new Map()
            
            // 创建 stepOrder -> taskStepId 的映射
            createdSteps.forEach(taskStep => {
              if (taskStep.stepOrder != null) {
                stepMap.set(taskStep.stepOrder, taskStep.id)
              }
            })
            
            // 为每个计划行动项导入资源
            for (const planStep of planData.steps) {
              const taskStepId = stepMap.get(planStep.stepOrder)
              if (!taskStepId || !planStep.resources || planStep.resources.length === 0) {
                continue
              }
              
              for (const resource of planStep.resources) {
                if (!resource.resourceRefId || !resource.resourceType) {
                  continue
                }
                
                try {
                  // 先查询资源详情
                  let resourceDetails = null
                  
                  if (resource.resourceType === 'material') {
                    try {
                      const res = await getMaterial(resource.resourceRefId)
                      if (res && res.code === 200) {
                        resourceDetails = res.data || res
                      }
                    } catch (error) {
                      console.warn('获取物资详情失败:', error)
                    }
                    
                    if (!resourceDetails) {
                      console.warn(`物资 ${resource.resourceRefId} 不存在，跳过`)
                      continue
                    }
                    
                    // 查找仓库ID：优先使用预案中的，如果没有则查找物资库存
                    let warehouseId = resource.warehouseId || null
                    if (!warehouseId) {
                      try {
                        const inventoryRes = await listMaterialInventory(resource.resourceRefId, { pageNum: 1, pageSize: 10 })
                        const inventories = inventoryRes.rows || inventoryRes.data || []
                        // 查找第一个有可用库存的仓库
                        const availableInventory = inventories.find(inv => 
                          inv.availableQty && parseFloat(inv.availableQty) > 0
                        )
                        if (availableInventory) {
                          warehouseId = availableInventory.warehouseId
                        } else if (inventories.length > 0) {
                          // 如果没有可用库存，使用第一个有库存的仓库
                          warehouseId = inventories[0].warehouseId
                        }
                      } catch (error) {
                        console.warn('查找物资库存失败:', error)
                      }
                    }
                    
                    // 如果还是没有仓库ID，跳过该资源
                    if (!warehouseId) {
                      console.warn(`物资 ${resource.resourceRefId} 没有可用的仓库，跳过`)
                      continue
                    }
                    
                    const materialData = {
                      materialId: resource.resourceRefId,
                      quantity: resource.suggestedQuantity || 1,
                      unit: resourceDetails.unit || '个',
                      warehouseId: warehouseId,
                      expectedAt: null,
                      usageContext: resource.usageNote || '',
                      usageMode: 'occupy'
                    }
                    await allocateMaterialToStep(taskId, taskStepId, materialData)
                    
                  } else if (resource.resourceType === 'equipment') {
                    try {
                      const res = await getEquipment(resource.resourceRefId)
                      if (res && res.code === 200) {
                        resourceDetails = res.data || res
                      }
                    } catch (error) {
                      console.warn('获取装备详情失败:', error)
                    }
                    
                    if (!resourceDetails) {
                      console.warn(`装备 ${resource.resourceRefId} 不存在，跳过`)
                      continue
                    }
                    
                    const equipmentData = {
                      equipmentId: resource.resourceRefId,
                      warehouseId: resource.warehouseId || null,
                      expectedFrom: null,
                      expectedUntil: null,
                      notes: resource.usageNote || ''
                    }
                    await allocateEquipmentToStep(taskId, taskStepId, equipmentData)
                    
                  } else if (resource.resourceType === 'vehicle') {
                    try {
                      const res = await getVehicle(resource.resourceRefId)
                      if (res && res.code === 200) {
                        resourceDetails = res.data || res
                      }
                    } catch (error) {
                      console.warn('获取车辆详情失败:', error)
                    }
                    
                    if (!resourceDetails) {
                      console.warn(`车辆 ${resource.resourceRefId} 不存在，跳过`)
                      continue
                    }
                    
                    const vehicleData = {
                      vehicleId: resource.resourceRefId,
                      route: '',
                      dispatchTime: null,
                      durationMinutes: null,
                      notes: resource.usageNote || ''
                    }
                    await allocateVehicleToStep(taskId, taskStepId, vehicleData)
                  }
                } catch (error) {
                  console.error(`导入资源失败 (${resource.resourceType}):`, error)
                  // 继续导入其他资源，不中断流程
                }
              }
            }
          }
        }
        
        // 4. 记录预案使用并更新引用次数
        try {
          await addPlanUsage(planId, {
            dispatchTaskId: taskId,
            source: 'dispatch',
            remark: `任务：${this.formData.name}`
          })
          
          // 更新预案的引用次数（usageCount + 1）
          // 获取当前预案信息以获取当前的 usageCount
          try {
            const currentPlanRes = await getPlan(planId)
            const currentPlan = currentPlanRes.data || currentPlanRes
            const currentUsageCount = currentPlan.usageCount || 0
            
            // 更新预案的 usageCount
            await updatePlan(planId, {
              usageCount: currentUsageCount + 1
            })
          } catch (updateError) {
            console.error('更新预案引用次数失败:', updateError)
            // 不影响任务创建，只记录错误
          }
        } catch (error) {
          console.error('记录预案使用失败:', error)
          // 不影响任务创建，只记录错误
        }
      } catch (error) {
        console.error('导入预案数据失败:', error)
        this.$message.warning('任务已创建，但导入预案数据时出现错误：' + (error.msg || error.message || '未知错误'))
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.create-task-dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 500px;
  max-height: 80vh;
  background: white;
  border-radius: 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
  z-index: 2001;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.create-task-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  background: #f5f7fa;
  flex-shrink: 0;
}

.create-task-dialog-title {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.create-task-dialog-close {
  padding: 0;
  color: #909399;
}

.create-task-dialog-body {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.event-context {
  background: #f5f7fa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 20px;
}

.context-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.context-label {
  font-size: 13px;
  color: #606266;
  min-width: 80px;
}

.context-value {
  font-size: 13px;
  color: #303133;
  font-weight: 500;
}

.create-task-dialog-footer {
  padding: 12px 16px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  flex-shrink: 0;
}

.create-task-dialog-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2000;
  background: rgba(0, 0, 0, 0.3);
}
</style>