<template>
  <el-dialog
    title="管理资源"
    :visible.sync="dialogVisible"
    width="900px"
    :close-on-click-modal="false"
    append-to-body
    modal-append-to-body
    @close="handleClose"
  >
    <div class="step-resource-allocation-dialog">
      <!-- Tabs for different resource types -->
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <!-- Materials Tab -->
        <el-tab-pane label="物资" name="materials">
          <div class="tab-content">
            <!-- Allocated Materials -->
            <div class="allocated-resources-section">
              <div class="section-title">已分配物资</div>
              <div v-if="allocatedMaterials.length === 0" class="empty-state">
                <el-empty description="暂无已分配物资" :image-size="60" />
              </div>
              <el-table
                v-else
                :data="allocatedMaterials"
                border
                size="small"
                max-height="200px"
              >
                <el-table-column prop="resourceName" label="物资名称" min-width="150" />
                <el-table-column prop="quantity" label="数量" width="100">
                  <template slot-scope="scope">
                    {{ getMaterialQuantity(scope.row) }}
                  </template>
                </el-table-column>
                <el-table-column prop="unit" label="单位" width="80">
                  <template slot-scope="scope">
                    <dict-tag 
                      v-if="getMaterialUnit(scope.row)"
                      :options="dict.type.material_unit || []" 
                      :value="getMaterialUnit(scope.row)" 
                    />
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column prop="warehouse" label="仓库" min-width="120">
                  <template slot-scope="scope">
                    {{ getWarehouseName(scope.row) }}
                  </template>
                </el-table-column>
                <el-table-column prop="warehouseDistance" label="仓库距离" width="100" v-if="eventLocation">
                  <template slot-scope="scope">
                    {{ getWarehouseDistanceForResource(scope.row) }}
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template slot-scope="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)" size="mini">
                      {{ getStatusLabel(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="mini"
                      icon="el-icon-delete"
                      style="color: #f56c6c;"
                      @click="handleRemoveResource(scope.row)"
                      :loading="removingResourceId === scope.row.id"
                      v-if="scope.row.status === 'locked'"
                    >
                      移除
                    </el-button>
                    <span v-else>/</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- Add Material Form -->
            <div class="add-resource-section">
              <div class="section-title">添加物资</div>
              <el-form
                ref="materialForm"
                :model="materialForm"
                :rules="materialRules"
                label-width="100px"
                size="small"
              >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="仓库" prop="warehouseId">
                      <el-select
                        v-model="materialForm.warehouseId"
                        placeholder="请选择仓库（可选）"
                        clearable
                        filterable
                        style="width: 100%"
                      >
                        <el-option
                          v-for="warehouse in warehouses"
                          :key="warehouse.id"
                          :label="warehouse.warehouseName + getWarehouseDistance(warehouse)"
                          :value="warehouse.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="物资" prop="materialId">
                      <el-select
                        v-model="materialForm.materialId"
                        placeholder="请选择物资"
                        filterable
                        style="width: 100%"
                        @change="handleMaterialSelect"
                      >
                        <el-option
                          v-for="material in availableMaterials"
                          :key="material.id"
                          :label="material.materialName"
                          :value="material.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="数量" prop="quantity">
                      <el-input-number
                        v-model="materialForm.quantity"
                        :min="0.01"
                        :precision="2"
                        style="width: 100%"
                        placeholder="数量"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="单位" prop="unit">
                      <dict-tag 
                        v-if="materialForm.unit"
                        :options="dict.type.material_unit || []" 
                        :value="materialForm.unit" 
                      />
                      <span v-else style="line-height: 32px; color: #909399;">
                        选择物资自动获取
                      </span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="使用模式" prop="usageMode">
                      <el-select
                        v-model="materialForm.usageMode"
                        placeholder="请先选择物资"
                        style="width: 100%"
                        disabled
                      >
                        <el-option label="占用后归还" value="occupy" />
                        <el-option label="占用后消耗" value="consume" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="使用说明" prop="usageContext">
                  <el-input
                    v-model="materialForm.usageContext"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入使用说明（可选）"
                    maxlength="200"
                    show-word-limit
                  />
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    size="small"
                    :loading="addingMaterial"
                    @click="handleAddMaterial"
                  >
                    添加物资
                  </el-button>
                  <el-button size="small" @click="resetMaterialForm">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-tab-pane>

        <!-- Equipment Tab -->
        <el-tab-pane label="装备" name="equipment">
          <div class="tab-content">
            <!-- Allocated Equipment -->
            <div class="allocated-resources-section">
              <div class="section-title">已分配装备</div>
              <div v-if="allocatedEquipment.length === 0" class="empty-state">
                <el-empty description="暂无已分配装备" :image-size="60" />
              </div>
              <el-table
                v-else
                :data="allocatedEquipment"
                border
                size="small"
                max-height="200px"
              >
                <el-table-column prop="resourceName" label="装备名称" min-width="150" />
                <el-table-column prop="warehouse" label="仓库" min-width="120">
                  <template slot-scope="scope">
                    {{ getEquipmentWarehouseName(scope.row) }}
                  </template>
                </el-table-column>
                <el-table-column prop="warehouseDistance" label="仓库距离" width="100" v-if="eventLocation">
                  <template slot-scope="scope">
                    {{ getEquipmentWarehouseDistance(scope.row) }}
                  </template>
                </el-table-column>
                <el-table-column prop="expectedFrom" label="预计开始时间" width="160">
                  <template slot-scope="scope">
                    {{ formatDateTime(scope.row.expectedFrom) }}
                  </template>
                </el-table-column>
                <el-table-column prop="expectedUntil" label="预计结束时间" width="160">
                  <template slot-scope="scope">
                    {{ formatDateTime(scope.row.expectedUntil) }}
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template slot-scope="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)" size="mini">
                      {{ getStatusLabel(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="mini"
                      icon="el-icon-delete"
                      style="color: #f56c6c;"
                      @click="handleRemoveResource(scope.row)"
                      :loading="removingResourceId === scope.row.id"
                    >
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- Add Equipment Form -->
            <div class="add-resource-section">
              <div class="section-title">添加装备</div>
              <el-form
                ref="equipmentForm"
                :model="equipmentForm"
                :rules="equipmentRules"
                label-width="100px"
                size="small"
              >
                <el-form-item label="仓库" prop="warehouseId">
                  <el-select
                    v-model="equipmentForm.warehouseId"
                    placeholder="请选择仓库（可选）"
                    clearable
                    filterable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="warehouse in warehouses"
                      :key="warehouse.id"
                      :label="warehouse.warehouseName + getWarehouseDistance(warehouse)"
                      :value="warehouse.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="装备" prop="equipmentId">
                  <el-select
                    v-model="equipmentForm.equipmentId"
                    placeholder="请选择装备"
                    filterable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="equipment in availableEquipment"
                      :key="equipment.id"
                      :label="equipment.equipmentName"
                      :value="equipment.id"
                    />
                  </el-select>
                </el-form-item>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="预计开始时间" prop="expectedFrom">
                      <el-date-picker
                        v-model="equipmentForm.expectedFrom"
                        type="datetime"
                        placeholder="选择开始时间"
                        style="width: 100%"
                        value-format="yyyy-MM-dd HH:mm:ss"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="预计结束时间" prop="expectedUntil">
                      <el-date-picker
                        v-model="equipmentForm.expectedUntil"
                        type="datetime"
                        placeholder="选择结束时间"
                        style="width: 100%"
                        value-format="yyyy-MM-dd HH:mm:ss"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="备注" prop="notes">
                  <el-input
                    v-model="equipmentForm.notes"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入备注（可选）"
                    maxlength="200"
                    show-word-limit
                  />
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    size="small"
                    :loading="addingEquipment"
                    @click="handleAddEquipment"
                  >
                    添加装备
                  </el-button>
                  <el-button size="small" @click="resetEquipmentForm">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-tab-pane>

        <!-- Vehicles Tab -->
        <el-tab-pane label="车辆" name="vehicles">
          <div class="tab-content">
            <!-- Allocated Vehicles -->
            <div class="allocated-resources-section">
              <div class="section-title">已分配车辆</div>
              <div v-if="allocatedVehicles.length === 0" class="empty-state">
                <el-empty description="暂无已分配车辆" :image-size="60" />
              </div>
              <el-table
                v-else
                :data="allocatedVehicles"
                border
                size="small"
                max-height="200px"
              >
                <el-table-column prop="resourceName" label="车辆名称" min-width="150" />
                <el-table-column prop="route" label="路线/目的地" min-width="150">
                  <template slot-scope="scope">
                    {{ scope.row.route || '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="dispatchTime" label="调度时间" width="160">
                  <template slot-scope="scope">
                    {{ formatDateTime(scope.row.dispatchTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="durationMinutes" label="预计时长" width="100">
                  <template slot-scope="scope">
                    {{ scope.row.durationMinutes ? scope.row.durationMinutes + '分钟' : '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="notes" label="备注" min-width="150" :show-overflow-tooltip="true" />
                <el-table-column prop="status" label="状态" width="100">
                  <template slot-scope="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)" size="mini">
                      {{ getStatusLabel(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="mini"
                      icon="el-icon-delete"
                      style="color: #f56c6c;"
                      @click="handleRemoveResource(scope.row)"
                      :loading="removingResourceId === scope.row.id"
                    >
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- Add Vehicle Form -->
            <div class="add-resource-section">
              <div class="section-title">添加车辆</div>
              <el-form
                ref="vehicleForm"
                :model="vehicleForm"
                :rules="vehicleRules"
                label-width="100px"
                size="small"
              >
                <el-form-item label="车辆" prop="vehicleId">
                  <el-select
                    v-model="vehicleForm.vehicleId"
                    placeholder="请选择车辆"
                    filterable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="vehicle in availableVehicles"
                      :key="vehicle.id"
                      :label="(vehicle.vehicleName || vehicle.plateNo) + getVehicleDistance(vehicle)"
                      :value="vehicle.id"
                    />
                  </el-select>
                </el-form-item>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="调度时间" prop="dispatchTime">
                      <el-date-picker
                        v-model="vehicleForm.dispatchTime"
                        type="datetime"
                        placeholder="选择调度时间"
                        style="width: 100%"
                        value-format="yyyy-MM-dd HH:mm:ss"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="时长" prop="durationMinutes">
                      <el-input-number
                        v-model="vehicleForm.durationMinutes"
                        :min="1"
                        style="width: 100%"
                        placeholder="预计使用时长"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="路线/目的地" prop="route">
                  <div style="display: flex; align-items: center; gap: 10px;">
                    <el-input
                      v-model="vehicleForm.route"
                      placeholder="请点击选择位置按钮选择目的地"
                      readonly
                      style="flex: 1"
                    />
                    <el-button
                      size="small"
                      type="primary"
                      plain
                      icon="el-icon-location"
                      @click="openLocationPicker"
                    >
                      选择位置
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item label="备注" prop="notes">
                  <el-input
                    v-model="vehicleForm.notes"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入备注（可选）"
                    maxlength="200"
                    show-word-limit
                  />
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    size="small"
                    :loading="addingVehicle"
                    @click="handleAddVehicle"
                  >
                    添加车辆
                  </el-button>
                  <el-button size="small" @click="resetVehicleForm">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">关闭</el-button>
    </div>

    <!-- Location Picker Dialog -->
    <LocationPickerDialog
      :visible.sync="locationPickerVisible"
      :initial-location="{
        longitude: locationPickerTarget ? locationPickerTarget.longitude : undefined,
        latitude: locationPickerTarget ? locationPickerTarget.latitude : undefined,
        locationName: locationPickerTarget ? locationPickerTarget.route : ''
      }"
      @confirm="handleLocationConfirm"
    />
  </el-dialog>
</template>

<script>
import { listMaterial } from '@/api/resource/material'
import { listEquipment } from '@/api/resource/equipment'
import { listVehicle } from '@/api/resource/vehicle'
import { listWarehouse } from '@/api/resource/warehouse'
import { getEvent } from '@/api/emergency/event'
import { getDispatchTask } from '@/api/emergency/dispatchTask'
import { formatDateTime as formatDateTimeUtil } from '@/views/duty/alert/utils/dateHelpers'
import LocationPickerDialog from '@/components/location/LocationPickerDialog.vue'
import {
  listDispatchStepResources,
  allocateMaterialToStep,
  allocateEquipmentToStep,
  allocateVehicleToStep,
  removeStepResource
} from '@/api/emergency/dispatchTask'

export default {
  name: 'StepResourceAllocationDialog',
  components: {
    LocationPickerDialog
  },
  dicts: ['material_unit'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    taskId: {
      type: [Number, String],
      required: true
    },
    stepId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      activeTab: 'materials',
      // Allocated resources
      allocatedResources: [],
      // Available resources
      availableMaterials: [],
      availableEquipment: [],
      availableVehicles: [],
      warehouses: [],
      // Forms
      materialForm: {
        materialId: null,
        quantity: null,
        unit: '',
        warehouseId: null,
        expectedAt: null,
        usageContext: '',
        usageMode: 'occupy'
      },
      equipmentForm: {
        equipmentId: null,
        warehouseId: null,
        expectedFrom: null,
        expectedUntil: null,
        notes: ''
      },
      vehicleForm: {
        vehicleId: null,
        route: '',
        dispatchTime: null,
        durationMinutes: null,
        notes: ''
      },
      locationPickerVisible: false,
      locationPickerTarget: null,
      // Rules
      materialRules: {
        materialId: [{ required: true, message: '请选择物资', trigger: 'change' }],
        quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }]
        // unit 字段非必填，与物资台账保持一致
      },
      equipmentRules: {
        equipmentId: [{ required: true, message: '请选择装备', trigger: 'change' }]
      },
      vehicleRules: {
        vehicleId: [{ required: true, message: '请选择车辆', trigger: 'change' }]
      },
      // Loading states
      loadingResources: false,
      loadingMaterials: false,
      loadingEquipment: false,
      loadingVehicles: false,
      loadingWarehouses: false,
      addingMaterial: false,
      addingEquipment: false,
      addingVehicle: false,
      removingResourceId: null,
      // Event location for distance calculation
      eventLocation: null
    }
  },
  computed: {
    allocatedMaterials() {
      return this.allocatedResources.filter(r => r.resourceType === 'material')
    },
    allocatedEquipment() {
      return this.allocatedResources.filter(r => r.resourceType === 'equipment')
    },
    allocatedVehicles() {
      return this.allocatedResources.filter(r => r.resourceType === 'vehicle')
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.loadData()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    async loadData() {
      // Load materials, warehouses, equipment, and vehicles first so they're available when processing allocated resources
      await Promise.all([
        this.loadMaterials(),
        this.loadWarehouses(),
        this.loadEquipment(),
        this.loadVehicles()
      ])
      await Promise.all([
        this.loadAllocatedResources(),
        this.loadEventLocation()
      ])
    },
    async loadAllocatedResources() {
      this.loadingResources = true
      try {
        // Materials should already be loaded by loadData
        const res = await listDispatchStepResources(this.taskId, this.stepId)
        this.allocatedResources = (res.data || []).map(link => {
          // Parse resource snapshot to get resource name
          let resourceName = `资源 #${link.resourceId}`
          if (link.note) {
            try {
              const snapshot = typeof link.note === 'string' ? JSON.parse(link.note) : link.note
              resourceName = snapshot.name || snapshot.materialName || snapshot.equipmentName || snapshot.vehicleName || resourceName
            } catch (e) {
              // If note is not JSON, use it as resourceName
              resourceName = link.note
            }
          }
          // If materialName not in snapshot, look it up from availableMaterials
          if ((!resourceName || resourceName.startsWith('资源 #')) && link.resourceType === 'material') {
            const material = this.availableMaterials.find(m => 
              m.id === link.resourceId || 
              String(m.id) === String(link.resourceId) ||
              Number(m.id) === Number(link.resourceId)
            )
            if (material) {
              resourceName = material.materialName || resourceName
            }
          }
          // If equipmentName not in snapshot, look it up from availableEquipment
          if ((!resourceName || resourceName.startsWith('资源 #')) && link.resourceType === 'equipment') {
            const equipment = this.availableEquipment.find(e => 
              e.id === link.resourceId || 
              String(e.id) === String(link.resourceId) ||
              Number(e.id) === Number(link.resourceId)
            )
            if (equipment) {
              resourceName = equipment.equipmentName || resourceName
            }
          }
          // If vehicleName not in snapshot, look it up from availableVehicles
          if ((!resourceName || resourceName.startsWith('资源 #')) && link.resourceType === 'vehicle') {
            const vehicle = this.availableVehicles.find(v => 
              v.id === link.resourceId || 
              String(v.id) === String(link.resourceId) ||
              Number(v.id) === Number(link.resourceId)
            )
            if (vehicle) {
              resourceName = vehicle.vehicleName || vehicle.plateNo || resourceName
            }
          }
          const extractedInfo = this.extractResourceInfo(link)
          // If resourceName is still default, use extracted name from extractResourceInfo
          if (resourceName.startsWith('资源 #') || !resourceName) {
            if (link.resourceType === 'material' && extractedInfo.materialName) {
              resourceName = extractedInfo.materialName
            } else if (link.resourceType === 'equipment' && extractedInfo.equipmentName) {
              resourceName = extractedInfo.equipmentName
            } else if (link.resourceType === 'vehicle' && extractedInfo.vehicleName) {
              resourceName = extractedInfo.vehicleName
            }
          }
          return {
            ...link,
            resourceName,
            // Extract additional info from note/snapshot
            ...extractedInfo
          }
        })
      } catch (error) {
        console.error('Failed to load allocated resources:', error)
        this.$message.error('加载已分配资源失败')
      } finally {
        this.loadingResources = false
      }
    },
    extractResourceInfo(link) {
      const info = {}
      if (link.note) {
        try {
          const snapshot = typeof link.note === 'string' ? JSON.parse(link.note) : link.note
          if (link.resourceType === 'material') {
            // InventoryAction uses 'qty' not 'quantity'
            info.quantity = snapshot.qty || snapshot.quantity
            // Extract warehouseId from InventoryAction
            info.warehouseId = snapshot.warehouseId
            // Unit and name are not in snapshot, need to get from material (handle ID type mismatch)
            const material = this.availableMaterials.find(m => 
              m.id === link.resourceId || 
              String(m.id) === String(link.resourceId) ||
              Number(m.id) === Number(link.resourceId)
            )
            if (material) {
              info.materialName = material.materialName
              if (material.unit) {
                info.unit = material.unit
              }
            }
          } else if (link.resourceType === 'equipment') {
            // Extract warehouseId from snapshot (stored at allocation time)
            info.warehouseId = snapshot.warehouseId
            // Extract expected times from snapshot
            info.expectedFrom = snapshot.expectedFrom
            info.expectedUntil = snapshot.expectedUntil
            // Look up equipment name if not in snapshot
            const equipment = this.availableEquipment.find(e => 
              e.id === link.resourceId || 
              String(e.id) === String(link.resourceId) ||
              Number(e.id) === Number(link.resourceId)
            )
            if (equipment) {
              info.equipmentName = equipment.equipmentName
            }
          } else if (link.resourceType === 'vehicle') {
            // Look up vehicle name if not in snapshot
            const vehicle = this.availableVehicles.find(v => 
              v.id === link.resourceId || 
              String(v.id) === String(link.resourceId) ||
              Number(v.id) === Number(link.resourceId)
            )
            if (vehicle) {
              info.vehicleName = vehicle.vehicleName || vehicle.plateNo
            }
            // Handle both old format (plain string) and new format (JSON snapshot)
            // Check if snapshot has vehicleId to determine if it's new format
            if (snapshot.vehicleId !== undefined || (snapshot.route !== undefined && snapshot.route !== null)) {
              // New format: JSON snapshot
              info.route = snapshot.route || ''
              info.dispatchTime = snapshot.dispatchTime
              info.durationMinutes = snapshot.durationMinutes
              info.notes = snapshot.notes || ''
            } else {
              // Old format: plain string (was stored as notes)
              info.route = link.note || ''
              info.notes = link.note || ''
            }
          }
        } catch (e) {
          // Not JSON, might be plain text (old format)
          if (link.resourceType === 'vehicle') {
            info.route = link.note || ''
            info.notes = link.note || ''
          }
        }
      }
      return info
    },
    getMaterialQuantity(resource) {
      // Check if quantity was already extracted
      if (resource.quantity !== undefined && resource.quantity !== null) {
        return resource.quantity
      }
      // Try to extract from note (InventoryAction uses 'qty')
      if (resource.note) {
        try {
          const snapshot = typeof resource.note === 'string' ? JSON.parse(resource.note) : resource.note
          return snapshot.qty || snapshot.quantity || '-'
        } catch (e) {
          return '-'
        }
      }
      return '-'
    },
    getMaterialUnit(resource) {
      // Check if unit was already extracted
      if (resource.unit) {
        return resource.unit
      }
      // Try to get from available materials (handle ID type mismatch)
      if (resource.resourceId) {
        const material = this.availableMaterials.find(m => 
          m.id === resource.resourceId || 
          String(m.id) === String(resource.resourceId) ||
          Number(m.id) === Number(resource.resourceId)
        )
        if (material && material.unit) {
          return material.unit
        }
      }
      return null
    },
    getWarehouseName(resource) {
      if (!resource.warehouseId) return '-'
      const warehouse = this.warehouses.find(w => 
        w.id === resource.warehouseId || 
        String(w.id) === String(resource.warehouseId) ||
        Number(w.id) === Number(resource.warehouseId)
      )
      return warehouse ? warehouse.warehouseName : '-'
    },
    getWarehouseDistanceForResource(resource) {
      if (!resource.warehouseId || !this.eventLocation) return '-'
      const warehouse = this.warehouses.find(w => 
        w.id === resource.warehouseId || 
        String(w.id) === String(resource.warehouseId) ||
        Number(w.id) === Number(resource.warehouseId)
      )
      if (!warehouse || !warehouse.latitude || !warehouse.longitude) return '-'
      
      const distance = this.calculateDistance(
        parseFloat(warehouse.latitude),
        parseFloat(warehouse.longitude),
        this.eventLocation.lat,
        this.eventLocation.lng
      )
      if (distance === null) return '-'
      
      if (distance < 1) {
        return `${(distance * 1000).toFixed(0)}m`
      } else {
        return `${distance.toFixed(1)}km`
      }
    },
    getEquipmentWarehouseName(resource) {
      if (!resource.warehouseId) return '-'
      const warehouse = this.warehouses.find(w => 
        w.id === resource.warehouseId || 
        String(w.id) === String(resource.warehouseId) ||
        Number(w.id) === Number(resource.warehouseId)
      )
      return warehouse ? warehouse.warehouseName : '-'
    },
    getEquipmentWarehouseDistance(resource) {
      if (!resource.warehouseId || !this.eventLocation) return '-'
      const warehouse = this.warehouses.find(w => 
        w.id === resource.warehouseId || 
        String(w.id) === String(resource.warehouseId) ||
        Number(w.id) === Number(resource.warehouseId)
      )
      if (!warehouse || !warehouse.latitude || !warehouse.longitude) return '-'
      
      const distance = this.calculateDistance(
        parseFloat(warehouse.latitude),
        parseFloat(warehouse.longitude),
        this.eventLocation.lat,
        this.eventLocation.lng
      )
      if (distance === null) return '-'
      
      if (distance < 1) {
        return `${(distance * 1000).toFixed(0)}m`
      } else {
        return `${distance.toFixed(1)}km`
      }
    },
    async loadAvailableResources() {
      await Promise.all([
        this.loadMaterials(),
        this.loadEquipment(),
        this.loadVehicles()
      ])
    },
    async loadMaterials() {
      this.loadingMaterials = true
      try {
        const res = await listMaterial({ pageNum: 1, pageSize: 1000 })
        this.availableMaterials = res.rows || res.data || []
      } catch (error) {
        console.error('Failed to load materials:', error)
        this.$message.error('加载物资列表失败')
      } finally {
        this.loadingMaterials = false
      }
    },
    async loadEquipment() {
      this.loadingEquipment = true
      try {
        const res = await listEquipment({ pageNum: 1, pageSize: 1000 })
        this.availableEquipment = res.rows || res.data || []
      } catch (error) {
        console.error('Failed to load equipment:', error)
        this.$message.error('加载装备列表失败')
      } finally {
        this.loadingEquipment = false
      }
    },
    async loadVehicles() {
      this.loadingVehicles = true
      try {
        const res = await listVehicle({ pageNum: 1, pageSize: 1000 })
        this.availableVehicles = res.rows || res.data || []
      } catch (error) {
        console.error('Failed to load vehicles:', error)
        this.$message.error('加载车辆列表失败')
      } finally {
        this.loadingVehicles = false
      }
    },
    async loadWarehouses() {
      this.loadingWarehouses = true
      try {
        const res = await listWarehouse({ pageNum: 1, pageSize: 1000 })
        this.warehouses = res.rows || res.data || []
      } catch (error) {
        console.error('Failed to load warehouses:', error)
        // Don't show error, warehouses are optional
      } finally {
        this.loadingWarehouses = false
      }
    },
    handleMaterialSelect(materialId) {
      if (materialId) {
        const material = this.availableMaterials.find(m => m.id === materialId)
        if (material) {
          this.materialForm.unit = material.unit || ''
          // Auto-set usage mode based on reusable property
          if (material.reusable !== undefined) {
            this.materialForm.usageMode = material.reusable === 1 ? 'occupy' : 'consume'
          }
        }
      }
    },
    async handleAddMaterial() {
      this.$refs.materialForm.validate(async (valid) => {
        if (!valid) return
        this.addingMaterial = true
        try {
          const request = {
            materialId: this.materialForm.materialId,
            quantity: this.materialForm.quantity,
            unit: this.materialForm.unit,
            warehouseId: this.materialForm.warehouseId || null,
            expectedAt: this.materialForm.expectedAt || null,
            usageContext: this.materialForm.usageContext || null,
            usageMode: this.materialForm.usageMode || 'occupy'
          }
          await allocateMaterialToStep(this.taskId, this.stepId, request)
          this.$message.success('添加物资成功')
          this.resetMaterialForm()
          await this.loadAllocatedResources()
        } catch (error) {
          console.error('Failed to add material:', error)
          this.$message.error(error.msg || '添加物资失败')
        } finally {
          this.addingMaterial = false
        }
      })
    },
    async handleAddEquipment() {
      this.$refs.equipmentForm.validate(async (valid) => {
        if (!valid) return
        this.addingEquipment = true
        try {
          const request = {
            equipmentId: this.equipmentForm.equipmentId,
            warehouseId: this.equipmentForm.warehouseId || null,
            expectedFrom: this.equipmentForm.expectedFrom || null,
            expectedUntil: this.equipmentForm.expectedUntil || null,
            notes: this.equipmentForm.notes || null
          }
          await allocateEquipmentToStep(this.taskId, this.stepId, request)
          this.$message.success('添加装备成功')
          this.resetEquipmentForm()
          await this.loadAllocatedResources()
        } catch (error) {
          console.error('Failed to add equipment:', error)
          this.$message.error(error.msg || '添加装备失败')
        } finally {
          this.addingEquipment = false
        }
      })
    },
    async handleAddVehicle() {
      this.$refs.vehicleForm.validate(async (valid) => {
        if (!valid) return
        this.addingVehicle = true
        try {
          const request = {
            vehicleId: this.vehicleForm.vehicleId,
            route: this.vehicleForm.route || null,
            dispatchTime: this.vehicleForm.dispatchTime || null,
            durationMinutes: this.vehicleForm.durationMinutes || null,
            notes: this.vehicleForm.notes || null
          }
          await allocateVehicleToStep(this.taskId, this.stepId, request)
          this.$message.success('添加车辆成功')
          this.resetVehicleForm()
          await this.loadAllocatedResources()
        } catch (error) {
          console.error('Failed to add vehicle:', error)
          this.$message.error(error.msg || '添加车辆失败')
        } finally {
          this.addingVehicle = false
        }
      })
    },
    async handleRemoveResource(resource) {
      this.$confirm('确定要移除该资源吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.removingResourceId = resource.id
        try {
          await removeStepResource(this.taskId, this.stepId, resource.id)
          this.$message.success('移除资源成功')
          await this.loadAllocatedResources()
          this.$emit('resource-removed')
        } catch (error) {
          console.error('Failed to remove resource:', error)
          this.$message.error(error.msg || '移除资源失败')
        } finally {
          this.removingResourceId = null
        }
      }).catch(() => {
        // User cancelled
      })
    },
    resetMaterialForm() {
      this.$refs.materialForm?.resetFields()
      this.materialForm = {
        materialId: null,
        quantity: null,
        unit: '',
        warehouseId: null,
        expectedAt: null,
        usageContext: '',
        usageMode: 'occupy'
      }
    },
    resetEquipmentForm() {
      this.$refs.equipmentForm?.resetFields()
      this.equipmentForm = {
        equipmentId: null,
        warehouseId: null,
        expectedFrom: null,
        expectedUntil: null,
        notes: ''
      }
    },
    resetVehicleForm() {
      this.$refs.vehicleForm?.resetFields()
      this.vehicleForm = {
        vehicleId: null,
        route: '',
        dispatchTime: null,
        durationMinutes: null,
        notes: ''
      }
    },
    handleTabChange(tab) {
      // Optionally reload data when switching tabs
    },
    handleClose() {
      this.dialogVisible = false
      this.$emit('close')
      this.$emit('resource-updated')
    },
    getStatusTagType(status) {
      const statusMap = {
        'locked': 'warning',
        'assigned': 'info',
        'busy': 'danger',
        'released': 'success',
        'consumed': 'danger',
        'returned': 'success',
        'unlocked': 'info'
      }
      return statusMap[status] || 'info'
    },
    getStatusLabel(status) {
      const labelMap = {
        'locked': '已锁定',
        'assigned': '已分配',
        'busy': '使用中',
        'released': '已释放',
        'consumed': '已消耗',
        'returned': '已归还',
        'unlocked': '已解锁'
      }
      return labelMap[status] || status || '-'
    },
    formatDateTime(value) {
      if (!value) return '-'
      // If it's already a string, return it; otherwise format it
      if (typeof value === 'string') {
        return value
      }
      return formatDateTimeUtil(value)
    },
    openLocationPicker() {
      this.locationPickerTarget = {
        longitude: undefined,
        latitude: undefined,
        route: this.vehicleForm.route
      }
      this.locationPickerVisible = true
    },
    handleLocationConfirm({ lng, lat, address }) {
      // Store the address in the route field
      this.vehicleForm.route = address || ''
      this.locationPickerVisible = false
      this.locationPickerTarget = null
    },
    async loadEventLocation() {
      if (!this.taskId) return
      try {
        const taskRes = await getDispatchTask(this.taskId)
        if (taskRes && taskRes.code === 200 && taskRes.data && taskRes.data.eventId) {
          const eventRes = await getEvent(taskRes.data.eventId)
          if (eventRes && eventRes.code === 200 && eventRes.data) {
            const event = eventRes.data
            if (event.latitude && event.longitude) {
              this.eventLocation = {
                lat: parseFloat(event.latitude),
                lng: parseFloat(event.longitude)
              }
            }
          }
        }
      } catch (error) {
        console.warn('加载事件位置失败，无法计算距离:', error)
      }
    },
    calculateDistance(lat1, lon1, lat2, lon2) {
      if (!lat1 || !lon1 || !lat2 || !lon2) return null
      
      const R = 6371 // Earth's radius in km
      const dLat = (lat2 - lat1) * Math.PI / 180
      const dLon = (lon2 - lon1) * Math.PI / 180
      const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                Math.sin(dLon / 2) * Math.sin(dLon / 2)
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
      return R * c
    },
    getWarehouseDistance(warehouse) {
      if (!this.eventLocation || !warehouse.latitude || !warehouse.longitude) {
        return ''
      }
      const distance = this.calculateDistance(
        parseFloat(warehouse.latitude),
        parseFloat(warehouse.longitude),
        this.eventLocation.lat,
        this.eventLocation.lng
      )
      if (distance === null) return ''
      
      if (distance < 1) {
        return ` (${(distance * 1000).toFixed(0)}m)`
      } else {
        return ` (${distance.toFixed(1)}km)`
      }
    },
    getVehicleDistance(vehicle) {
      if (!this.eventLocation || !vehicle.gpsLat || !vehicle.gpsLng) {
        return ''
      }
      const distance = this.calculateDistance(
        parseFloat(vehicle.gpsLat),
        parseFloat(vehicle.gpsLng),
        this.eventLocation.lat,
        this.eventLocation.lng
      )
      if (distance === null) return ''
      
      if (distance < 1) {
        return ` (${(distance * 1000).toFixed(0)}m)`
      } else {
        return ` (${distance.toFixed(1)}km)`
      }
    }
  }
}
</script>

<style scoped lang="scss">
.step-resource-allocation-dialog {
  .tab-content {
    padding: 10px 0;
  }

  .section-title {
    font-weight: 600;
    margin-bottom: 12px;
    color: #303133;
    font-size: 14px;
  }

  .allocated-resources-section {
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #ebeef5;
  }

  .add-resource-section {
    margin-top: 16px;
  }

  .empty-state {
    padding: 20px;
    text-align: center;
  }
}

.dialog-footer {
  text-align: right;
}
</style>