<template>
  <div>
    <el-card>
      <el-form :ref="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
          :ref="mesProductPlan"
          :data="mesProductPlanList"
          :row-class-name="rowMesProductPlanIndex"
          @selection-change="handleMesProductPlanSelectionChange"
          :tree-props="{children: 'children'}"
          style="width: 100%;margin-bottom: 20px;"
          row-key="id"
          border
          default-expand-all
        >
          <el-table-column label="序号" type="index" align="center"></el-table-column>
          <el-table-column
            width="80"
            label="删除"
            type=""
          >
            <template #default="scope">
              <el-button type="danger" icon="el-icon-delete" @click="handleDeleteMesProductPlan(scope)"
                         v-if="scope.row.firstFlag != null && scope.row.firstFlag === '1'
                         && formData.orderStatus!==ORDER_STATUS.FINISHED && formData.orderStatus!==ORDER_STATUS.RECALLED && formData.orderStatus!==ORDER_STATUS.DELETED">
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            width="50"
          ></el-table-column>
          <el-table-column
            align="center"
            label="派工单号"
            prop="dispatchCode"
            width="230"
          >
            <template #default="scope">
              <template v-if="!scope.row.children && !scope.row.firstFlag">
                <!-- 子行不显示任何内容 -->
              </template>
              <template v-else>
                <el-input v-model="scope.row.dispatchCode" disabled></el-input>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="工序"
            prop="processName"
            width="140"
          >
            <template #default="scope">
              <template v-if="!scope.row.children && !scope.row.firstFlag">
                <!-- 子行不显示任何内容 -->
              </template>
              <template v-else>
                <el-input v-model="scope.row.processName" disabled></el-input>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="步骤"
            prop="processOrder"
          >
            <template #default="scope">
              <template v-if="!scope.row.children && !scope.row.firstFlag">
                <!-- 子行不显示任何内容 -->
              </template>
              <template v-else>
                <el-input v-model="scope.row.processOrder" disabled></el-input>
              </template>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            label="派工数量"
            prop="dispatchAmount"
            width="140"
          >
            <template #default="scope">
              <template v-if="!scope.row.children && !scope.row.firstFlag">
                <!-- 子行不显示任何内容 -->
              </template>
              <template v-else>
                <!-- 只有第一个新增行显示输入框 -->
                <template v-if="scope.row.firstFlag === '1' && scope.row.newFlag === '1' && scope.row.addFlag === '1'">
                  <el-input-number
                    v-model="scope.row.dispatchAmount"
                    :min="0"
                    :controls="true"
                    :precision="0"
                    style="width: 120px"
                    @change="handleDispatchAmountChange(scope.row)"
                  />
                </template>
                <!-- 其他新增行不显示 -->
                <template v-else-if="scope.row.newFlag === '1'">
                  <!-- 不显示任何内容 -->
                </template>
                <!-- 非新增行显示数值 -->
                <template v-else>
                  <span>{{ scope.row.dispatchAmount || scope.row.releaseAmount || 0 }}</span>
                </template>
              </template>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            label="工位"
            prop="releaseId"
            width="140"
          >
            <template #default="scope">
              <el-select
                v-model="scope.row.releaseId"
                placeholder="请选择"
                v-if="scope.row.children == null || scope.row.children === undefined"
                :disabled="scope.row.planId != null && scope.row.planId !== undefined && scope.row.planId !== ''"
              >
                <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.processType === PROCESS_TYPE.MANUAL &&
                           scope.row.children != null &&
                           scope.row.children !== undefined ||
                           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="230"
          >
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.planBeginTime"
                style="width:200px;"
                :disabled="scope.row.processType === PROCESS_TYPE.MANUAL &&
                           scope.row.children != null &&
                           scope.row.children !== undefined ||
                           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="230"
          >
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.planEndTime"
                style="width:200px;"
                :disabled="scope.row.processType === PROCESS_TYPE.MANUAL &&
                           scope.row.children != null &&
                           scope.row.children !== undefined ||
                           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">
              {{scope.row.planStatus}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            class-name="small-padding fixed-width"
            label="操作"
            width="100"
          >
            <template #default="scope">
              <el-button
                icon="el-icon-delete"
                size="small"
                type="danger"
                @click="handleDeleteDispatchUser(scope.row)"
                v-if="scope.row.children == null"
                :disabled="scope.row.planStatus !== PLAN_STATUS.TO_DISPATCH &&
                           scope.row.planStatus !== PLAN_STATUS.DISPATCHED ||
                           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, selectProductPlans, orderAddProductPlanList } from '@/api/mes/planInfo'
import { getProdBaseProcessUserList } from '@/api/mes/prodBaseProcessUser'
import { getStationInfoList } from '@/api/mes/baseStationInfo'
import { getProdLineList } from '@/api/mes/baseProdLineInfo'
import { getBaseRouteList } from '@/api/mes/baseRoute'
import { getProcessInfoList } from '@/api/mes/baseProcessInfo'
import { PlanInfoVO, PlanInfoQuery, PlanInfoForm } from '@/api/mes/planInfo/types';

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 orderStatusTextMap = {
  '0': '待生产',
  '1': '生产中',
  '2': '已完成',
  '3': '已暂停',
  '4': '已取消',
  '8': '已撤回',
  '9': '已删除'
}

const deepClone = (obj) => {
  return JSON.parse(JSON.stringify(obj))
}

const formData = ref({
  orderStatus: '', 
  dispatchId: '',
  planBeginTime: '',
  planEndTime: '',
  saleType: '',
  produceMaterialId: '',
  materialId: '',
  materialBomId: '',
  productOrderId: '',
  saleOrderId: '',
  saleorderCode: '',
  productionTime: '',
})

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', message: '计划数量必须为数字' }
  ]
})

const getOrderStatusText = (status) => {
  return orderStatusTextMap[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) {
      Object.assign(formData.value, {
        orderCode: response.data.orderCode,
        materialCode: response.data.materialCode,
        planBeginTime: response.data.planBeginTime,
        planEndTime: response.data.planEndTime,
        planAmount: Number(response.data.planAmount || 0),
        dispatchAmount: Number(response.data.dispatchAmount || 0),
        completeAmount: Number(response.data.completeAmount || 0),
        dispatchName: response.data.dispatchName,
        materialName: response.data.materialName,
        orderStatus: response.data.orderStatus,
        productOrderId: response.data.productOrderId,
        materialId: response.data.materialId,
        materialBomId: response.data.materialBomId,
        saleOrderId: response.data.saleOrderId || '',
        saleorderCode: response.data.saleorderCode || '',
        dispatchId: response.data.dispatchId || response.data.routeId,
        productionTime: response.data.productionTime,
      })
      // console.log('Form after update', JSON.stringify(formData.value, null, 2))
      await getProcessJoin(productOrderId)
    } else {
      ElMessage.error('获取工单信息失败：数据为空')
    }
  } catch (error) {
    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 = {}

    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)

    // console.log('Process stations', processStations.value)
    // console.log('Product plans', mesProductPlanList.value)
  } catch (error) {
    console.error('Failed to fetch process info', error)
    ElMessage.error('获取工序信息失败：' + error.message)
  }
}

const groupProductPlans = async (productPlans) => {
  const groupedProductPlans = {}
  let id = 1
  let firstDispatch = {}

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

    const key = `${productPlan.dispatchCode}-${productPlan.processId}`
    if (!groupedProductPlans[key]) {
      groupedProductPlans[key] = []
    }
    groupedProductPlans[key].push(productPlan)
  })

  for (let dispatchCodeProcessId in groupedProductPlans) {
    let productPlansByDispatch = groupedProductPlans[dispatchCodeProcessId]

    let obj = {}

    let dispatchCode = dispatchCodeProcessId.split('-')[0]
    if (!firstDispatch[dispatchCode]) {
      firstDispatch[dispatchCode] = 1
      obj.firstFlag = 1
    }

    obj.id = id++
    obj.addFlag = 0
    let i = 0
    let processType
    productPlansByDispatch.forEach(groupedProductPlan => {
      if (groupedProductPlan.planStatus !== PLAN_STATUS.FINISHED) {
        obj.addFlag = 1
      }

      processType = groupedProductPlan.processType
      groupedProductPlan.id = id++

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

      obj.attachId = groupedProductPlan.attachId
      obj.productionTime = groupedProductPlan.productionTime
      obj.processProductionTime = groupedProductPlan.processProductionTime

      if (i === 0) {
        obj.dispatchCode = groupedProductPlan.dispatchCode
        obj.planCode = groupedProductPlan.planCode
        obj.dispatchAmount = groupedProductPlan.dispatchAmount
        obj.processId = groupedProductPlan.processId
        obj.processName = groupedProductPlan.processName
        obj.lastProcessId = groupedProductPlan.lastProcessId
        obj.processType = groupedProductPlan.processType
        obj.processOrder = groupedProductPlan.processOrder
        obj.finalProcessFlag = groupedProductPlan.finalProcessFlag
        obj.attachId = groupedProductPlan.attachId
        obj.planBeginTime = formData.value.planBeginTime
        obj.planEndTime = formData.value.planEndTime
        obj.planStatus = groupedProductPlan.planStatus
        obj.materialId = formData.value.materialId
        obj.materialBomId = formData.value.materialBomId
        obj.productOrderId = formData.value.productOrderId
        obj.saleOrderId = formData.value.saleOrderId
        obj.saleorderCode = formData.value.saleorderCode
        obj.productionTime = formData.value.productionTime
        obj.oldRowFlag = true
        i++
      }
    })

    if (processType === PROCESS_TYPE.MANUAL) {
      obj.children = productPlansByDispatch
      mesProductPlanList.value.push(obj)
    } else {
      mesProductPlanList.value.push(obj)
    }
  }

  // console.log('Grouped plans:', mesProductPlanList.value)
}

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: PlanInfoForm[] = [];
    let currentDispatchAmount = 0;

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

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

    for (let productPlan of newPlans) {
      // 如果是手动工序且有子行，则从子行获取数据
      if (productPlan.processType === PROCESS_TYPE.MANUAL && productPlan.children?.length > 0) {
        // 获取第一个子行的数据
        const childPlan = productPlan.children[0];



        if (childPlan.planBeginTime > childPlan.planEndTime) {
          ElMessage.error(`工序 ${productPlan.processName} 的计划开始时间不能大于结束时间`);
          return;
        }

        currentDispatchAmount += Number(productPlan.dispatchAmount || 0);

        const stationData = productPlan.children.map(child => ({
          releaseId: Number(child.releaseId),
          processId: child.processId || productPlan.processId
        })).filter(item => item.releaseId);

        if (productPlan.children.length !== stationData.length) {
          ElMessage.error('请为所有工序选择工位');
          return;
        }

        // 构建提交数据前再次确认时间值
        const planBeginTime = childPlan.planBeginTime?.trim() || '';
        const planEndTime = childPlan.planEndTime?.trim() || '';


        const planData: PlanInfoForm = {
          dispatchCode: productPlan.dispatchCode,
          dispatchAmount: Number(productPlan.dispatchAmount),
          processId: Number(productPlan.processId),
          productionTime: productPlan.processProductionTime ||
            Math.round(Number(productPlan.productionTime || 0) * 3600),
          // 使用子行的时间数据
          planBeginTime: planBeginTime || null,
          planEndTime: planEndTime || null,
          planStatus: PLAN_STATUS.TO_DISPATCH,
          materialId: Number(formData.value.materialId),
          materialBomId: Number(formData.value.materialBomId),
          productOrderId: Number(formData.value.productOrderId),
          saleOrderId: formData.value.saleOrderId ? Number(formData.value.saleOrderId) : undefined,
          saleorderCode: formData.value.saleorderCode,
          releaseId: stationData.map(item => item.releaseId).join(','),
          planCode: productPlan.planCode,
          processOrder: Number(productPlan.processOrder),
          lastProcessId: Number(productPlan.lastProcessId),
          finalProcessFlag: productPlan.finalProcessFlag,
          attachId: productPlan.attachId,
          releaseType: '3',
          planAmount: Number(formData.value.planAmount),
        };

        toUpdatedProductPlans.push(planData);
      } else {
        // 自动工序直接使用当前行的时间数据
        if (!productPlan.planBeginTime || !productPlan.planEndTime) {
          ElMessage.error(`工序 ${productPlan.processName} 的计划开始时间和结束时间不能为空`);
          return;
        }

        // ... 处理自动工序的其他逻辑 ...
      }
    }

    if (currentDispatchAmount === 0) {
      ElMessage.error('派工数量必须大于0');
      return;
    }

    const totalDispatchAmount = Number(formData.value.dispatchAmount || 0) + currentDispatchAmount;
    if (totalDispatchAmount > formData.value.planAmount) {
      ElMessage.error('派工数量之和需小于等于该生产任务计划数量！');
      return;
    }

    const submitData = {
      productOrderId: Number(formData.value.productOrderId),
      dispatchAmount: currentDispatchAmount,
      mesProductPlanList: toUpdatedProductPlans,
      toDeletedPlanIds: toDeletedPlanIds.value || []
    };

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

const rowMesProductPlanIndex = ({row, rowIndex}) => {
  row.index = rowIndex + 1
}

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

const close = () => {
  mesProductPlanList.value = []
  router.back()
}

let id = 1

const handleAddMesProductPlan = async () => {
  if (!formData.value?.dispatchId) {
    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
    }

    processes.forEach((process, index) => {
      const isFirstProcess = index === 0
      const basePlan = {
        id: ++id,
        dispatchCode,
        processId: process.processId,
        processName: process.processName,
        processType: process.processType,
        processOrder: process.processOrder,
        finalProcessFlag: process.finalProcessFlag,
        productionTime: 0,
        processProductionTime: 0,
        planBeginTime: '',
        planEndTime: '',
        planStatus: '1',
        materialId: formData.saleType === '2' ? formData.produceMaterialId : formData.materialId,
        materialBomId: formData.materialBomId,
        productOrderId: formData.productOrderId,
        saleOrderId: formData.saleOrderId,
        saleorderCode: formData.saleorderCode,
        newFlag: '1',
        dispatchAmount: 0,
        firstFlag: isFirstProcess ? '1' : '0',
        oldRowFlag: false,
        addFlag: isFirstProcess ? '1' : '0'
      }

      // 添加工位选择行
      if (process.processType !== '3') { // 不是自动工序时添加工位选择行
        basePlan.children = [{
          id: ++id,
          dispatchCode,
          processId: process.processId,
          materialBomId: formData.materialBomId,
          planStatus: '1',
          productionTime: 0,
          processProductionTime: 0,
          userId: null,
          dispatchAmount: 0,
          oldRowFlag: false,
          newFlag: '1'
        }]
      } else {
        basePlan.children = []
      }

      mesProductPlanList.value.push(basePlan)
    })

  } catch (error) {
    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 isPositiveInteger = (value) => {
  return /^[0-9]d$/.test(value)
}

const handleDeleteDispatchUser = (row) => {
  mesProductPlanList.value.forEach(mesProductPlan => {
    mesProductPlan.children = mesProductPlan.children.filter(item => item.id !== row.id)
  })
  if (row.planId != null && row.planId !== '') {
    toDeletedPlanIds.value.push(row.planId)
  }
}

// const isOptionDisabled = (attachId) => {
//   return materialBomAttachIdList.value.includes(attachId)
// }

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 =>
        scope.row.dispatchCode !== item.dispatchCode
      )
      ElMessage.success('删除成功')
      return
    }

    let dispatchSum = 0

    try {
      const plansToDelete = mesProductPlanList.value.filter(item =>
        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
      }

/*      deleteProductPlansByDispatchCode({
        productOrderId: formData.value.productOrderId,
        dispatchCode: dispatchCode,
        dispatchAmount: dispatchSum
      }).then(() => {
        mesProductPlanList.value = mesProductPlanList.value.filter(item =>
          dispatchCode !== item.dispatchCode
        )
        formData.value.dispatchAmount = formData.value.dispatchAmount - dispatchSum
        ElMessage.success('删除成功')
      })*/
    } catch (error) {
      ElMessage.error(error.message)
    }
  }).catch(() => {
    // 用户取消删除，不做处理
  })
}

const handleStationChange = (value, scope) => {
  const parentPlan = mesProductPlanList.value.find(
    plan => plan.dispatchCode === scope.row.dispatchCode
  );
  if (parentPlan) {
    parentPlan.releaseId = value;
  }
}

// 处理标准工时变化的函数
const handleProductionTimeChange = (row) => {
  // console.log('工时变化前:', row.productionTime);

  // 保存用户输入的小时数
  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;
  }

  // console.log('工时变化后:', {
  //   小时: row.productionTime,
  //   秒: row.processProductionTime,
  //   行数据: row
  // });
}

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>

