<template>
  <div>
    <el-card>
      <el-form :model="formData" :rules="rules" label-width="120px" :key="formData.productOrderId">
        <el-divider content-position="left"><span style="font-weight: bold; font-size: larger;">订单信息</span></el-divider>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="任务编号：">
              {{ formData.orderCode }}
            </el-form-item>
            <el-form-item label="成品编码：">
              {{ formData.materialCode }}
            </el-form-item>
            <el-form-item label="计划开始时间：">
              {{ formData.planBeginTime }}
            </el-form-item>
            <el-form-item label="计划数量/已派工数量/完成数量：" label-width="220px">
              {{ formData.planAmount }}/{{ formData.dispatchAmount }}/{{ formData.completeAmount }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工艺路线：">
              {{ formData.dispatchName }}
            </el-form-item>
            <el-form-item label="成品名称：">
              {{ formData.materialName }}
            </el-form-item>
            <el-form-item label="计划结束时间：">
              {{ formData.planEndTime }}
            </el-form-item>
            <el-form-item label="任务状态：">
              {{ getOrderStatusText(formData.orderStatus) }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left"><span style="font-weight: bold; font-size: larger;">派工信息</span></el-divider>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="handleAddMesProductPlan"
              v-if="formData.orderStatus!==ORDER_STATUS.FINISHED && formData.orderStatus!=ORDER_STATUS.RECALLED && formData.orderStatus!=ORDER_STATUS.DELETED"
            >
              新增
            </el-button>
          </el-col>
        </el-row>

        <el-table
          :data="mesProductPlanList"
          :row-class-name="rowMesProductPlanIndex"
          @selection-change="handleMesProductPlanSelectionChange"
          style="width: 100%;margin-bottom: 20px;"
          row-key="id"
          border
        >
          <el-table-column label="序号" type="index" align="center" width="60"></el-table-column>
          <el-table-column
            align="center"
            label="派工单号"
            prop="dispatchCode"
            width="180"
          >
            <template #default="scope">
              <el-input v-model="scope.row.dispatchCode" disabled size="small"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="工单编号"
            prop="planCode"
            width="180"
          >
            <template #default="scope">
              <el-input v-model="scope.row.planCode" disabled size="small"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="工序"
            prop="processName"
            width="140"
          >
            <template #default="scope">
              <el-input v-model="scope.row.processName" disabled size="small"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="步骤"
            prop="processOrder"
            width="80"
          >
            <template #default="scope">
              <el-input v-model="scope.row.processOrder" disabled size="small"></el-input>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            label="派工数量"
            prop="dispatchAmount"
            width="160"
          >
            <template #default="scope">
              <template v-if="scope.row.newFlag === '1'">
                <el-input-number
                  v-model="scope.row.dispatchAmount"
                  :min="0"
                  :max="getMaxDispatchAmount(scope.row.dispatchCode)"
                  :controls="true"
                  :precision="0"
                  style="width: 120px"
                  :disabled="formData.orderStatus === ORDER_STATUS.FINISHED ||
                           formData.orderStatus === ORDER_STATUS.RECALLED ||
                           formData.orderStatus === ORDER_STATUS.DELETED"
                  @change="handleDispatchAmountChange(scope.row)"
                />
              </template>
              <template v-else>
                <span>{{ scope.row.dispatchAmount || scope.row.releaseAmount || 0 }}</span>
              </template>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            label="工位"
            prop="releaseId"
            width="180"
          >
            <template #default="scope">
              <el-select
                v-model="scope.row.releaseId"
                placeholder="请选择工位"
                size="small"
                style="width: 100%"
                :disabled="(scope.row.planId != null && scope.row.planId !== undefined && scope.row.planId !== '') ||
                         scope.row.planStatus === PLAN_STATUS.FINISHED ||
                         formData.orderStatus === ORDER_STATUS.FINISHED ||
                         formData.orderStatus === ORDER_STATUS.RECALLED ||
                         formData.orderStatus === ORDER_STATUS.DELETED"
                clearable
              >
                <el-option
                  v-for="item in (processStations[scope.row.processId] || [])"
                  :key="item.stationId"
                  :label="item.stationName"
                  :value="item.stationId"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
<!--          <el-table-column-->
<!--            align="center"-->
<!--            label="派工标准工时(小时)"-->
<!--            prop="productionTime"-->
<!--            width="180"-->
<!--          >-->
<!--            <template #default="scope">-->
<!--              <el-input-number-->
<!--                style="width:150px;"-->
<!--                :min="0"-->
<!--                v-model="scope.row.productionTime"-->
<!--                :disabled="scope.row.planStatus === PLAN_STATUS.FINISHED ||-->
<!--                           formData.orderStatus === ORDER_STATUS.FINISHED ||-->
<!--                           formData.orderStatus === ORDER_STATUS.RECALLED ||-->
<!--                           formData.orderStatus === ORDER_STATUS.DELETED"-->
<!--                @change="handleProductionTimeChange(scope.row)"-->
<!--              >-->
<!--              </el-input-number>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column
            align="center"
            label="计划开始时间"
            prop="planBeginTime"
            width="200"
          >
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.planBeginTime"
                style="width:100%;"
                size="small"
                :disabled="scope.row.planStatus === PLAN_STATUS.FINISHED ||
                           formData.orderStatus === ORDER_STATUS.FINISHED ||
                           formData.orderStatus === ORDER_STATUS.RECALLED ||
                           formData.orderStatus === ORDER_STATUS.DELETED"
                clearable
                placeholder="请选择计划开始时间"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
              >
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="计划结束时间"
            prop="planEndTime"
            width="200"
          >
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.planEndTime"
                style="width:100%;"
                size="small"
                :disabled="scope.row.planStatus === PLAN_STATUS.FINISHED ||
                           formData.orderStatus === ORDER_STATUS.FINISHED ||
                           formData.orderStatus === ORDER_STATUS.RECALLED ||
                           formData.orderStatus === ORDER_STATUS.DELETED"
                clearable
                placeholder="请选择计划完成时间"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
              >
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="状态"
            prop="planStatus"
            width="150"
          >
            <template #default="scope">
              {{ getPlanStatusText(scope.row.planStatus) }}
            </template>
          </el-table-column>
          <el-table-column
            width="80"
            label="操作"
            align="center"
          >
            <template #default="scope">
              <el-button
                type="danger"
                size="small"
                @click="handleDeleteMesProductPlan(scope)"
                v-if="scope.row.newFlag === '1' &&
                      formData.orderStatus!==ORDER_STATUS.FINISHED &&
                      formData.orderStatus!==ORDER_STATUS.RECALLED &&
                      formData.orderStatus!==ORDER_STATUS.DELETED">删除
              </el-button>
            </template>
          </el-table-column>

        </el-table>
      </el-form>

      <el-form label-width="100px">
        <el-form-item style="text-align: center;margin-left:-100px;margin-top:10px;">
          <el-button
            type="primary"
            :loading="loading"
            @click="submitForm()"
            v-if="formData.orderStatus!==ORDER_STATUS.FINISHED && formData.orderStatus!==ORDER_STATUS.RECALLED && formData.orderStatus!==ORDER_STATUS.DELETED"
          >
            提交
          </el-button>
          <el-button @click="close()">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderInfo } from '@/api/mes/orderInfo'
import {
  getBaseRouteProcesses,
  getDispatchCode,
  getPlanCode,
  selectProductPlans,
  orderAddProductPlanList,
  orderAddProductPlanJJList
} from '@/api/mes/planInfo';
import { getStationInfoList } from '@/api/mes/baseStationInfo'


const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter()
const route = useRoute();


const ORDER_STATUS = {
  FINISHED: '2',   // 已完成
  RECALLED: '8',   // 已撤回
  DELETED: '9'     // 已删除
}

const PROCESS_TYPE = {
  AUTO: '3',       // 自动化工序
  MANUAL: '1'      // 手动工序
}

const PLAN_STATUS = {
  TO_DISPATCH: '0',   // 待派工
  DISPATCHED: '1',    // 已派工
  STARTED: '2',       // 已开始
  FINISHED: '3'       // 已完成
}

const planStatusTextMap = {
  '0': '待派工',
  '1': '已派工',
  '2': '已开始',
  '3': '已完成'
}

const orderStatusTextMap = {
  '0': '待生产',
  '1': '生产中',
  '2': '已完成',
  '3': '已暂停',
  '4': '已取消',
  '8': '已撤回',
  '9': '已删除'
}


const formData = ref({
  orderStatus: '',
  dispatchId: '',
  planBeginTime: '',
  planEndTime: '',
  saleType: '',
  produceMaterialId: '',
  materialId: '',
  materialBomId: '',
  productOrderId: '',
  saleOrderId: '',
  saleorderCode: '',
  productionTime: '',
  orderCode: '',
  materialCode: '',
  materialName: '',
  dispatchName: '',
  planAmount: 0,
  dispatchAmount: 0,
  completeAmount: 0,
  routeId: '',
} as any)

const mesProductPlanList = ref([])
const processStations = ref([])
const toDeletedPlanIds = ref([])

const rules = ref({
  orderCode: [
    { required: true, message: '请输入任务编号', trigger: 'blur' }
  ],
  materialCode: [
    { required: true, message: '请输入成品编码', trigger: 'blur' }
  ],
  planAmount: [
    { required: true, message: '请输入计划数量', trigger: 'blur' },
    { type: 'number' as const, message: '计划数量必须为数字' }
  ]
} as any)

const getOrderStatusText = (status) => {
  return orderStatusTextMap[status] || `未知状态(${status})`
}

const getPlanStatusText = (status) => {
  return planStatusTextMap[status] || `未知状态(${status})`
}

const fetchOrderInfo = async (productOrderId) => {
  // console.log('Fetching order info for ID', productOrderId)
  try {
    const response = await getOrderInfo(productOrderId)
    // console.log('Order info response', response)

    if (response.code === 200 && response.data) {
      const data = response.data as any
      Object.assign(formData.value, {
        orderCode: data.orderCode,
        materialCode: data.materialCode || '',
        planBeginTime: data.planBeginTime,
        planEndTime: data.planEndTime,
        planAmount: Number(data.planAmount || 0),
        dispatchAmount: Number(data.dispatchAmount || 0),
        completeAmount: Number(data.completeAmount || 0),
        dispatchName: data.dispatchName || '',
        materialName: data.materialName || '',
        orderStatus: data.orderStatus,
        productOrderId: data.productOrderId,
        materialId: data.materialId,
        materialBomId: data.materialBomId,
        saleOrderId: data.saleOrderId || '',
        saleorderCode: data.saleorderCode || '',
        dispatchId: data.dispatchId || data.routeId || '',
        productionTime: data.productionTime || '',
      })
      await getProcessJoin(productOrderId)
    } else {
      ElMessage.error('获取工单信息失败：数据为空')
    }
  } catch (error: any) {
    console.error('Failed to fetch order info', error)
    ElMessage.error('获取工单信息失败：' + (error?.message || '未知错误'))
  }
}

const getProcessJoin = async (productOrderId) => {
  try {
    const stationResponse = await getStationInfoList(null)
    if (!stationResponse.data) {
      throw new Error('获取工位信息失败')
    }

     processStations.value = {} as any

    stationResponse.data.forEach(station => {
      if (!processStations.value[station.processId]) {
        processStations.value[station.processId] = []
      }
      processStations.value[station.processId].push(station)
    })

    const productPlansResponse = await selectProductPlans({ productOrderId })
    if (!productPlansResponse.data) {
      throw new Error('获取生产计划失败')
    }

    mesProductPlanList.value = []

    await groupProductPlans(productPlansResponse.data)

  } catch (error: any) {
    console.error('Failed to fetch process info', error)
    ElMessage.error('获取工序信息失败：' + (error?.message || '未知错误'))
  }
}

const groupProductPlans = async (productPlans) => {
  mesProductPlanList.value = []

  productPlans.forEach(productPlan => {
    // 确保派工数量有值
    productPlan.dispatchAmount = productPlan.dispatchAmount || productPlan.releaseAmount || 0

    // 如果后端返回的是秒，需要转换为小时显示
    if (productPlan.productionTime) {
      productPlan.productionTime = parseFloat((productPlan.productionTime / 3600).toFixed(1));
      productPlan.processProductionTime = productPlan.productionTime * 3600;
    }

    const planRow: any = {
      id: productPlan.planId || `temp_${Date.now()}_${Math.random()}`,
      planId: productPlan.planId,
      dispatchCode: productPlan.dispatchCode,
      planCode: productPlan.planCode,
      dispatchAmount: productPlan.dispatchAmount,
      processId: productPlan.processId,
      processName: productPlan.processName,
      processType: productPlan.processType,
      processOrder: productPlan.processOrder,
      lastProcessId: productPlan.lastProcessId,
      finalProcessFlag: productPlan.finalProcessFlag,
      productionTime: productPlan.productionTime || 0,
      processProductionTime: productPlan.processProductionTime || 0,
      planBeginTime: productPlan.planBeginTime || formData.value.planBeginTime || '',
      planEndTime: productPlan.planEndTime || formData.value.planEndTime || '',
      planStatus: productPlan.planStatus,
      materialId: formData.value.materialId,
      materialBomId: productPlan.materialBomId || formData.value.materialBomId,
      productOrderId: productPlan.productOrderId || formData.value.productOrderId,
      saleOrderId: productPlan.saleOrderId || formData.value.saleOrderId || null,
      saleorderCode: productPlan.saleorderCode || formData.value.saleorderCode || '',
      releaseId: productPlan.releaseId || null,
      attachId: productPlan.attachId || null,
      newFlag: '0', // 已保存的数据
      oldRowFlag: true
    }

    mesProductPlanList.value.push(planRow)
  })
}

const loading = ref(false);

const submitForm = async () => {
  if (loading.value) return;

  if (!mesProductPlanList.value || mesProductPlanList.value.length === 0) {
    ElMessage.error('无派工信息提交');
    return;
  }

  try {
    loading.value = true;
    const dataList = mesProductPlanList.value;
    const toUpdatedProductPlans: any[] = [];

    // 只处理新增的数据（newFlag === '1'的数据）
    const newPlans = dataList.filter((plan: any) => plan.newFlag === '1');

    if (newPlans.length === 0) {
      ElMessage.info('无新增派工数据需要提交');
      return;
    }

    // 按dispatchCode分组，校验每个组的派工数量
    const groupMap = new Map<string, any[]>()
    newPlans.forEach((plan: any) => {
      const dispatchCode = plan.dispatchCode
      if (!groupMap.has(dispatchCode)) {
        groupMap.set(dispatchCode, [])
      }
      groupMap.get(dispatchCode)!.push(plan)
    })

    // 校验相同processName的工序派工数量之和不能大于计划数量
    const processNameMap = new Map<string, number>()
    newPlans.forEach((plan: any) => {
      const processName = plan.processName || ''
      const dispatchAmount = Number(plan.dispatchAmount || 0)
      const currentSum = processNameMap.get(processName) || 0
      processNameMap.set(processName, currentSum + dispatchAmount)
    })

    const planAmount = Number(formData.value.planAmount || 0)
    for (const [processName, totalAmount] of processNameMap.entries()) {
      if (totalAmount > planAmount) {
        ElMessage.error(`工序 ${processName} 的派工数量之和 ${totalAmount} 超过计划数量 ${planAmount}`)
        loading.value = false
        return
      }
    }

    // 处理每个工序的数据
    for (const productPlan of newPlans) {
      // 验证工序基本信息
      if (!productPlan.processId) {
        ElMessage.error(`工序信息不完整`)
        loading.value = false
        return
      }

      // 获取该工序的派工数量（单个工序的数量）
      let dispatchAmount = Number(productPlan.dispatchAmount || 0)



      // 验证时间
      if (!productPlan.planBeginTime || !productPlan.planEndTime) {
        ElMessage.error(`工序 ${productPlan.processName || productPlan.processId} 的计划开始时间和结束时间不能为空`)
        loading.value = false
        return
      }

      const planBeginTime = String(productPlan.planBeginTime).trim()
      const planEndTime = String(productPlan.planEndTime).trim()

      if (!planBeginTime || !planEndTime) {
        ElMessage.error(`工序 ${productPlan.processName || productPlan.processId} 的计划时间不能为空`)
        loading.value = false
        return
      }

      if (planBeginTime >= planEndTime) {
        ElMessage.error(`工序 ${productPlan.processName || productPlan.processId} 的计划开始时间必须小于结束时间`)
        loading.value = false
        return
      }

      // 验证工位选择（每个工序都需要选择工位）
      if (!productPlan.releaseId) {
        ElMessage.error(`工序 ${productPlan.processName || productPlan.processId} 必须选择工位`)
        loading.value = false
        return
      }

      // 计算生产时间（秒）
      const productionTimeSeconds = productPlan.processProductionTime
        ? Number(productPlan.processProductionTime)
        : (productPlan.productionTime
            ? Math.round(Number(productPlan.productionTime) * 3600)
            : 0)

      // 构建提交数据（每个工序使用自己的派工数量）
      const planData: any = {
        dispatchCode: String(productPlan.dispatchCode),
        dispatchAmount: dispatchAmount, // 每个工序使用自己的派工数量
        processId: Number(productPlan.processId),
        productionTime: productionTimeSeconds,
        planBeginTime: planBeginTime,
        planEndTime: planEndTime,
        planStatus: PLAN_STATUS.TO_DISPATCH,
        materialId: formData.value.materialId,
        materialBomId: Number(formData.value.materialBomId),
        productOrderId: Number(formData.value.productOrderId),
        saleOrderId: formData.value.saleOrderId ? Number(formData.value.saleOrderId) : null,
        saleorderCode: formData.value.saleorderCode || '',
        releaseId: String(productPlan.releaseId), // 每个工序对应一个工位
        planCode: productPlan.planCode || '',
        processOrder: Number(productPlan.processOrder || 0),
        lastProcessId: productPlan.lastProcessId ? Number(productPlan.lastProcessId) : null,
        finalProcessFlag: productPlan.finalProcessFlag || '0',
        attachId: productPlan.attachId || null,
        releaseType: '3', // 工位类型
        planAmount: Number(dispatchAmount || 0),
      }

      // 移除undefined字段，确保数据干净
      Object.keys(planData).forEach(key => {
        if (planData[key] === undefined) {
          delete planData[key]
        }
      })

      toUpdatedProductPlans.push(planData)
    }

    // 计算所有新增工序的派工数量总和（用于订单级别的dispatchAmount）
    // 总的派工数量 = 每个工序的派工数量之和
    const totalDispatchAmount = toUpdatedProductPlans.reduce((sum, plan: any) => sum + Number(plan.dispatchAmount || 0), 0)

    // 构建提交数据
    const submitData = {
      productOrderId: Number(formData.value.productOrderId),
      dispatchAmount: totalDispatchAmount,
      mesProductPlanList: toUpdatedProductPlans,
      toDeletedPlanIds: toDeletedPlanIds.value && toDeletedPlanIds.value.length > 0 ? toDeletedPlanIds.value : []
    };

    console.log('提交数据:', JSON.stringify(submitData, null, 2))

    const res = await orderAddProductPlanJJList(submitData);

    if (res.code === 200) {
      ElMessage.success('提交成功');
      // await fetchOrderInfo(formData.value.productOrderId);
      close();
    } else {
      throw new Error((res as any).msg || '提交失败');
    }
  } catch (error: any) {
    console.error('提交异常', error);
    const errorMessage = error?.response?.data?.msg || error?.message || '提交失败，请重试';
    ElMessage.error(errorMessage);
  } finally {
    loading.value = false;
  }
}

const rowMesProductPlanIndex = ({row, rowIndex}: any): string => {
  row.index = rowIndex + 1
  return ''
}

const checkedMesProductPlanList = ref([])
const single = ref(true)

const handleMesProductPlanSelectionChange = (selection) => {
  checkedMesProductPlanList.value = selection
  single.value = selection.length !== 1
}

const close = () => {
  mesProductPlanList.value = []
  proxy.$tab.closePage(route);
  router.go(-1);
}

let id = 1

const handleAddMesProductPlan = async () => {
  if (!formData.value?.dispatchId) {
    ElMessage.error('未获取到工艺路线信息')
    return
  }

  if (!formData.value?.materialId || !formData.value?.materialBomId) {
    ElMessage.error('未获取到物料信息，请先完善生产订单信息')
    return
  }

  try {
    // 获取派工单号
    const { msg: dispatchCode } = await getDispatchCode()
    if (!dispatchCode) {
      throw new Error('获取派工单号失败')
    }

    // 获取工艺路线工序
    const { data: processes } = await getBaseRouteProcesses({
      routeId: formData.value.dispatchId
    })

    if (!processes || processes.length === 0) {
      ElMessage.error('工艺路线未维护工序信息')
      return
    }

    // 为每个工序创建一行，每个工序都需要选择工位，每个工序生成不同的工单编号
    for (const process of processes) {
      // 为每个工序生成不同的工单编号
      const planCodeRes = await getPlanCode()
      // 兼容不同的返回格式：data 或 msg
      const planCode = planCodeRes.data || planCodeRes.msg || ''

      if (!planCode) {
        throw new Error('获取工单编号失败')
      }

      const basePlan: any = {
        id: `new_${Date.now()}_${++id}`,
        dispatchCode, // 同一批次使用相同的派工单号
        planCode, // 每个工序使用不同的工单编号
        processId: process.processId,
        processName: process.processName,
        processType: process.processType,
        processOrder: process.processOrder,
        lastProcessId: process.lastProcessId || null,
        finalProcessFlag: process.finalProcessFlag,
        productionTime: 0,
        processProductionTime: 0,
        planBeginTime: formData.value.planBeginTime || '',
        planEndTime: formData.value.planEndTime || '',
        planStatus: PLAN_STATUS.TO_DISPATCH,
        materialId: formData.value.materialId,
        materialBomId: formData.value.materialBomId,
        productOrderId: formData.value.productOrderId,
        saleOrderId: formData.value.saleOrderId || null,
        saleorderCode: formData.value.saleorderCode || '',
        newFlag: '1',
        dispatchAmount: Number(formData.value.planAmount || 0), // 初始派工数量设为计划数量
        oldRowFlag: false,
        releaseId: null, // 每个工序都需要选择工位
        attachId: null,
        planId: null
      }

      mesProductPlanList.value.push(basePlan)
    }

    ElMessage.success('新增派工计划成功，请填写派工数量和时间信息')
  } catch (error: any) {
    console.error('新增派工计划失败:', error)
    ElMessage.error(error?.message || '新增派工计划失败')
  }
}

const updateMaxId = (list) => {
  list.forEach(item => {
    id = Math.max(id, item.id)
    if (item.children && item.children.length > 0) {
      updateMaxId(item.children)
    }
  })
}

const handleDeleteMesProductPlan = (scope) => {
  const dispatchCode = scope.row.dispatchCode

  ElMessageBox.confirm(`是否确认删除生产派工单号为${dispatchCode}的数据项？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (formData.value.orderStatus === ORDER_STATUS.RECALLED) {
      ElMessage.error('此生产任务已经撤回，不能删除')
      return
    }

    if (formData.value.orderStatus === ORDER_STATUS.FINISHED) {
      ElMessage.error('此生产任务已经完成，不能删除')
      return
    }

    if (formData.value.orderStatus === ORDER_STATUS.DELETED) {
      ElMessage.error('此生产任务已经删除，不能删除')
      return
    }

    if (scope.row.newFlag != null && scope.row.newFlag === '1') {
      // 删除同一派工单号的所有新增工序
      mesProductPlanList.value = mesProductPlanList.value.filter((item: any) =>
        scope.row.dispatchCode !== item.dispatchCode
      )
      ElMessage.success('删除成功')
      return
    }

    let dispatchSum = 0

    try {
      const plansToDelete = mesProductPlanList.value.filter((item: any) =>
        scope.row.dispatchCode === item.dispatchCode
      )

      for (const item of plansToDelete) {
        if (item.planStatus !== PLAN_STATUS.DISPATCHED &&
          item.planStatus !== PLAN_STATUS.TO_DISPATCH) {
          throw new Error('只能删除还未开始过状态的生产派工单！')
        }
        dispatchSum = item.dispatchAmount
      }


      } catch (error: any) {
        ElMessage.error(error?.message || '删除失败')
      }
  }).catch(() => {
    // 用户取消删除，不做处理
  })
}


// 处理标准工时变化的函数
const handleProductionTimeChange = (row) => {
  // 保存用户输入的小时数
  row.productionTime = Number(row.productionTime || 0);
  // 转换为秒
  row.processProductionTime = Math.round(row.productionTime * 3600);

  // 找到对应的父行（如果存在）并更新其工时
  const parentRow = mesProductPlanList.value.find(plan =>
    plan.dispatchCode === row.dispatchCode && plan.processId === row.processId
  );

  if (parentRow) {
    parentRow.productionTime = row.productionTime;
    parentRow.processProductionTime = row.processProductionTime;
  }
}

// 获取同一组（相同dispatchCode）的最大派工数量
// 最大数量 = 订单计划数量 - 已派工数量 - 其他新增组的派工数量
const getMaxDispatchAmount = (dispatchCode: string) => {
  const planAmount = Number(formData.value.planAmount || 0)
  const currentDispatchAmount = Number(formData.value.dispatchAmount || 0)

  // 计算其他新增组的派工数量总和
  let otherGroupsAmount = 0
  mesProductPlanList.value.forEach((plan: any) => {
    if (plan.newFlag === '1' && plan.dispatchCode !== dispatchCode) {
      // 获取该组第一个工序的派工数量（因为同一组内数量一致）
      const groupFirstPlan = mesProductPlanList.value.find((p: any) =>
        p.newFlag === '1' && p.dispatchCode === plan.dispatchCode
      )
      if (groupFirstPlan) {
        otherGroupsAmount += Number(groupFirstPlan.dispatchAmount || 0)
      }
    }
  })

  // 最大可派工数量 = 计划数量 - 已派工数量 - 其他新增组的派工数量
  const maxAmount = planAmount - currentDispatchAmount - otherGroupsAmount
  return Math.max(0, maxAmount)
}

// 处理派工数量变化，确保同一组内所有工序的派工数量保持一致
const handleDispatchAmountChange = (changedRow: any) => {
  const dispatchCode = changedRow.dispatchCode
  const newAmount = Number(changedRow.dispatchAmount || 0)

  // 找到同一组内的所有新增工序，同步派工数量
  mesProductPlanList.value.forEach((plan: any) => {
    if (plan.newFlag === '1' && plan.dispatchCode === dispatchCode && plan.id !== changedRow.id) {
      plan.dispatchAmount = newAmount
    }
  })
}


onMounted(async () => {
  // console.log('Component mounted, route', route)
  const productOrderId = route.params.productOrderId || route.query.productOrderId
  // console.log('Product Order ID', productOrderId)

  if (productOrderId) {
    await fetchOrderInfo(productOrderId)
  } else {
    ElMessage.error('未获取到工单ID')
  }

  if (mesProductPlanList.value.length > 0) {
    updateMaxId(mesProductPlanList.value)
  }
})
</script>

<style scoped>
:deep(.el-icon-close) {
  display: none;
}
:deep(.el-upload) {
  display: none;
}
</style>

