<template>
  <div class='p-2'>
    <transition :enter-active-class='proxy?.animate.searchAnimate.enter'
                :leave-active-class='proxy?.animate.searchAnimate.leave'>
      <div v-show='showSearch' class='mb-[10px]'>
        <el-card shadow='hover'>
          <el-form ref='queryFormRef' :model='queryParams' :inline='true'>
            <!--            <el-form-item label="生产订单ID" prop="productOrderId">-->
            <!--              <el-input v-model="queryParams.productOrderId" placeholder="请输入生产订单ID" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label='计划编号' prop='planCode'>
              <el-input v-model='queryParams.planCode' placeholder='请输入计划编号' clearable
                        @keyup.enter='handleQuery' />
            </el-form-item>
            <el-form-item label='物料名称' prop='materialName'>
              <el-input v-model='queryParams.materialName' placeholder='请输入物料名称' clearable
                        @keyup.enter='handleQuery' />
            </el-form-item>
            <!--            <el-form-item label="物料BOM" prop="materialBomId">-->
            <!--              <el-input v-model="queryParams.materialBomId" placeholder="请输入物料BOM" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="工序ID" prop="processId">-->
            <!--              <el-input v-model="queryParams.processId" placeholder="请输入工序ID" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label='机台名称' prop='releaseId'>
              <el-select v-model='queryParams.releaseId' placeholder='请选择机台名称'clearable
                         @keyup.enter='handleQuery'>
                <el-option
                  v-for='item in releaseList'
                  :key='item.machineId'
                  :label='item.machineName'
                  :value='item.machineId'
                />
              </el-select>
            </el-form-item>
            <el-form-item label='计划时间' prop='planRangeTime'>
              <el-date-picker clearable
                              v-model='queryParams.planRangeTime'
                              type='datetimerange'
                              range-separator='至'
                              start-placeholder='开始日期'
                              end-placeholder='结束日期'
                              value-format='YYYY-MM-DD HH:mm:ss'
              />
            </el-form-item>
            <el-form-item label='计划状态' prop='planStatus'>
              <el-select v-model='queryParams.planStatus' placeholder='请选择计划状态' clearable
                         @keyup.enter='handleQuery'>
                <el-option v-for='dict in mes_plan_status' :key='dict.value' :label='dict.label' :value='dict.value' />
              </el-select>
            </el-form-item>
            <!--            <el-form-item label="班次" prop="shiftId">-->
            <!--              <el-input v-model="queryParams.shiftId" placeholder="请输入班次" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="班组" prop="classTeamId">-->
            <!--              <el-input v-model="queryParams.classTeamId" placeholder="请输入班组" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
<!--            <el-form-item label='模号' prop='modelCode'>-->
<!--              <el-select v-model='queryParams.modelCode' placeholder='请选择模号' clearable-->
<!--                         @keyup.enter='handleQuery'>-->
<!--                <el-option v-for='dict in mes_model_code' :key='dict.value' :label='dict.label' :value='dict.value' />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
            <el-form-item>
              <el-button type='primary' icon='Search' @click='handleQuery'>搜索</el-button>
              <el-button icon='Refresh' @click='resetQuery'>重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow='never'>
      <template #header>
        <el-row :gutter='10' class='mb8'>
          <!--          <el-col :span='1.5'>-->
          <!--            <el-button type='primary' plain icon='Plus' @click='handleAdd' v-hasPermi="['mes:planInfo:add']">新增-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <el-col :span='1.5'>
            <el-button type='primary' plain icon='Plus' @click='handleSfpBatchAdd' v-hasPermi="['mes:planInfo:add']"
                       v-if="workshopId === '2'">半制品新增
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='primary' plain icon='Plus' @click='handleFormingBatchAdd' v-hasPermi="['mes:planInfo:add']"
                       v-if="workshopId === '3'">成型新增
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='primary' plain icon='Plus' @click='handleVulBatchAdd' v-hasPermi="['mes:planInfo:add']"
                       v-if="workshopId === '4'">硫化新增
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='danger' plain icon='Bottom' :disabled='multiple' @click='handleIssuePlanInfo()'
                       v-hasPermi="['mes:planInfo:add']">下发选中计划
            </el-button>
          </el-col>
          <!--          <el-col :span='1.5'>-->
          <!--            <el-button type='success' plain icon='Edit' :disabled='single' @click='handleUpdate()'-->
          <!--                       v-hasPermi="['mes:planInfo:edit']">修改-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span='1.5'>-->
          <!--            <el-button type='danger' plain icon='Delete' :disabled='multiple' @click='handleDelete()'-->
          <!--                       v-hasPermi="['mes:planInfo:remove']">删除-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span='1.5'>-->
          <!--            <el-button type='warning' plain icon='Download' @click='handleExport' v-hasPermi="['mes:planInfo:export']">-->
          <!--              导出-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch='showSearch' :columns='columns' :search='true'
                         @queryTable='getList'></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading='loading' :data='planInfoList' @selection-change='handleSelectionChange'>
        <el-table-column type='selection' width='55' align='center' />
        <el-table-column label='主键标识' align='center' prop='planId' v-if='columns[0].visible' />
        <el-table-column label='生产订单ID' align='center' prop='productOrderId' v-if='columns[2].visible'
                         width='100' />
        <el-table-column label='销售订单ID' align='center' prop='saleOrderId' v-if='columns[3].visible' />
        <el-table-column label='销售订单编号' align='center' prop='saleorderCode' v-if='columns[4].visible' />
        <el-table-column label='计划编号' align='center' prop='planCode' v-if='columns[5].visible' width='120' />
        <el-table-column label='派工单号' align='center' prop='dispatchCode' v-if='columns[6].visible' />
        <el-table-column label='物料名称' align='center' prop='materialName' v-if='columns[7].visible' width='160' />
        <el-table-column label='BOM版本' align='center' prop='materialBomVersion' v-if='columns[8].visible' width='160' />
        <el-table-column label='工序名称' align='center' prop='processName' v-if='columns[9].visible' />
        <el-table-column label='顺序' align='center' prop='processOrder' v-if='columns[10].visible' />
        <el-table-column label='上一工序ID' align='center' prop='lastProcessId' v-if='columns[11].visible'
                         width='100' />
        <el-table-column label='最后工序标识' align='center' prop='finalProcessFlag' v-if='columns[12].visible'
                         width='110'>
          <template #default='scope'>
            <dict-tag :options='active_flag' :value='scope.row.finalProcessFlag' />
          </template>
        </el-table-column>
        <el-table-column label='下达类型' align='center' prop='releaseType' v-if='columns[13].visible'>
          <template #default='scope'>
            <dict-tag :options='mes_release_type' :value='scope.row.releaseType' />
          </template>
        </el-table-column>
        <el-table-column label='下达机台' align='center' prop='releaseName' v-if='columns[14].visible' />
        <el-table-column label='单位生产时间(秒)' align='center' prop='productionTime' v-if='columns[15].visible' />
        <el-table-column label='计划数量' align='center' prop='planAmount' v-if='columns[16].visible' />
        <el-table-column label='派工数量' align='center' prop='dispatchAmount' v-if='columns[17].visible' />
        <el-table-column label='完成数量' align='center' prop='completeAmount' v-if='columns[18].visible' />
        <el-table-column label='计量单位' align='center' prop='unitName' v-if='columns[37].visible' />
        <el-table-column label='计划时间' align='center' prop='planBeginTime' width='180' v-if='columns[19].visible'>
          <template #default='scope'>
            <span>{{ parseTime(scope.row.planBeginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label='计划结束时间' align='center' prop='planEndTime' width='180' v-if='columns[20].visible'>
          <template #default='scope'>
            <span>{{ parseTime(scope.row.planEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label='实际开始时间' align='center' prop='realBeginTime' width='180'
                         v-if='columns[21].visible'>
          <template #default='scope'>
            <span>{{ parseTime(scope.row.realBeginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label='实际完成时间' align='center' prop='realEndTime' width='180' v-if='columns[22].visible'>
          <template #default='scope'>
            <span>{{ parseTime(scope.row.realEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label='附件信息' align='center' prop='attachId' v-if='columns[23].visible' />
        <el-table-column label='计划状态' align='center' prop='planStatus' v-if='columns[24].visible'>
          <template #default='scope'>
            <dict-tag :options='mes_plan_status' :value='scope.row.planStatus' />
          </template>
        </el-table-column>
        <el-table-column label='导入类型' align='center' prop='importFlag' v-if='columns[25].visible'>
          <template #default='scope'>
            <dict-tag :options='mes_import_flag' :value='scope.row.importFlag' />
          </template>
        </el-table-column>
        <el-table-column label='完成标识' align='center' prop='finishFlag' v-if='columns[26].visible'>
          <template #default='scope'>
            <dict-tag :options='mes_finish_flag' :value="scope.row.finishFlag ? scope.row.finishFlag.split(',') : []" />
          </template>
        </el-table-column>
        <el-table-column label='优先级' align='center' prop='priority' v-if='columns[27].visible' />
        <el-table-column label='班次' align='center' prop='shiftName' v-if='columns[28].visible' />
        <el-table-column label='班组' align='center' prop='teamName' v-if='columns[29].visible' />
        <el-table-column label='模号' align='center' prop='modelCode' v-if='workshopId == "4" '>
          <template #default='scope'>
            <dict-tag :options='mes_model_code' :value='scope.row.modelCode' />
          </template>
        </el-table-column>
        <el-table-column label='备注' align='center' prop='remark' v-if='columns[31].visible' />
        <el-table-column label='操作' align='center' class-name='small-padding fixed-width' fixed='right'>
          <template #default='scope'>
            <el-button link type='primary' @click='handleRecall(scope.row)'
                       v-if='["0", "1"].includes(scope.row.planStatus)'
                       v-hasPermi="['mes:planInfo:edit']">撤回
            </el-button>
            <!--            <el-tooltip content='删除' placement='top'>-->
            <!--              <el-button link type='primary' icon='Delete' @click='handleDelete(scope.row)'-->
            <!--                         v-hasPermi="['mes:planInfo:remove']"></el-button>-->
            <!--            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show='total > 0' :total='total' v-model:page='queryParams.pageNum'
                  v-model:limit='queryParams.pageSize' @pagination='getList' />
    </el-card>
    <!-- 添加或修改生产工单信息对话框 -->
    <el-dialog :title='dialog.title' v-model='dialog.visible' width='500px' append-to-body>
      <el-form ref='planInfoFormRef' :model='form' :rules='rules' label-width='100px'>
        <!--        <el-form-item label="生产订单ID" prop="productOrderId">-->
        <!--          <el-input v-model="form.productOrderId" placeholder="请输入生产订单ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="销售订单ID" prop="saleOrderId">-->
        <!--          <el-input v-model="form.saleOrderId" placeholder="请输入销售订单ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="销售订单编号" prop="saleorderCode">-->
        <!--          <el-input v-model="form.saleorderCode" placeholder="请输入销售订单编号" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="计划编号" prop="planCode">-->
        <!--          <el-input v-model="form.planCode" placeholder="请输入计划编号" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="派工单号" prop="dispatchCode">-->
        <!--          <el-input v-model="form.dispatchCode" placeholder="请输入派工单号" />-->
        <!--        </el-form-item>-->
        <el-form-item label='物料名称' prop='materialId'>
          <el-input v-model='form.materialName' placeholder='请点击检索物料' @click='handleMaterialAdd' readonly>
            <template #append>
              <el-icon class='el-input__icon'>
                <search />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label='BOM版本' prop='materialBomVersion'>
          <el-select v-model='form.materialBomVersion' placeholder='请选择BOM版本'>
            <el-option
              v-for='item in materialBomVersionOptions'
              :key='item.materialBomVersion'
              :label='`${item.materialBomVersion} - ${item.materialBomDesc}`'
              :value='item.materialBomVersion'
            />
          </el-select>
        </el-form-item>
        <el-form-item label='工序名称' prop='processId'>
          <el-select v-model='form.processId' placeholder='请选择工序'>
            <el-option
              v-for='item in processList'
              :key='item.processId'
              :label='item.processName'
              :value='item.processId'
            />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="顺序" prop="processOrder">-->
        <!--          <el-input-number v-model="form.processOrder" placeholder="请输入顺序" style="width: 200px;"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="上一工序ID" prop="lastProcessId">-->
        <!--          <el-input v-model="form.lastProcessId" placeholder="请输入上一工序ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="最后工序标识" prop="finalProcessFlag">-->
        <!--          <el-radio-group v-model="form.finalProcessFlag">-->
        <!--            <el-radio-->
        <!--              v-for="dict in active_flag"-->
        <!--              :key="dict.value"-->
        <!--              :value="dict.value"-->
        <!--            >{{dict.label}}</el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <el-form-item label='下达类型' prop='releaseType'>
          <el-radio-group v-model='form.releaseType' :disabled='true'>
            <el-radio
              v-for='dict in mes_release_type'
              :key='dict.value'
              :value='dict.value'
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='机台' prop='releaseId'>
          <el-select v-model='form.releaseId' placeholder='请选择'>
            <el-option
              v-for='item in releaseList'
              :key='item.machineId'
              :label='item.machineName'
              :value='item.machineId'
            />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="单位生产时间(秒)" prop="productionTime">-->
        <!--          <el-input v-model="form.productionTime" placeholder="请输入单位生产时间(秒)" />-->
        <!--        </el-form-item>-->
        <el-form-item label='计划数量' prop='planAmount'>
          <el-input-number v-model='form.planAmount' placeholder='请输入计划数量' style='width: 200px;' />
        </el-form-item>
        <!--        <el-form-item label="派工数量" prop="dispatchAmount">-->
        <!--          <el-input-number v-model="form.dispatchAmount" placeholder="请输入派工数量" style="width: 200px;" />-->
        <!--        </el-form-item>-->
        <el-form-item label='计划时间' prop='planBeginTime'>
          <el-date-picker clearable
                          v-model='form.planBeginTime'
                          type='datetime'
                          value-format='YYYY-MM-DD HH:mm:ss'
                          placeholder='请选择计划时间'>
          </el-date-picker>
        </el-form-item>
        <!--        <el-form-item label='计划结束时间' prop='planEndTime'>-->
        <!--          <el-date-picker clearable-->
        <!--                          v-model='form.planEndTime'-->
        <!--                          type='datetime'-->
        <!--                          value-format='YYYY-MM-DD HH:mm:ss'-->
        <!--                          placeholder='请选择计划结束时间'>-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="附件信息" prop="attachId">-->
        <!--          <el-input v-model="form.attachId" placeholder="请输入附件信息" />-->
        <!--        </el-form-item>-->
        <el-form-item label='优先级' prop='priority'>
          <el-input-number v-model='form.priority' placeholder='请输入优先级' style='width: 200px;' />
        </el-form-item>
        <el-form-item label='班次' prop='shiftId'>
          <el-radio-group v-model='form.shiftId'>
            <el-radio
              v-for='dict in shiftList'
              :key='dict.shiftId'
              :value='dict.shiftId'
            >{{ dict.shiftName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='班组' prop='classTeamId'>
          <el-select v-model='form.classTeamId' placeholder='请选择班组'>
            <el-option
              v-for='item in classTeamList'
              :key='item.classTeamId'
              :label='item.teamName'
              :value='item.classTeamId'
            />
          </el-select>
        </el-form-item>
        <el-form-item label='模号' prop='modelCode'>
          <el-radio-group v-model='form.modelCode'>
            <el-radio
              v-for='dict in mes_model_code'
              :key='dict.value'
              :value='dict.value'
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='备注' prop='remark'>
          <el-input v-model='form.remark' placeholder='请输入备注' />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class='dialog-footer'>
          <el-button :loading='buttonLoading' type='primary' @click='submitForm'>确 定</el-button>
          <el-button @click='cancel'>取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加物料BOM信息对话框 -->
<!--    <el-dialog title='选择物料BOM信息' v-model='materialBomOpen' append-to-body>-->
<!--      <BomSelect @selection='handleSelection' ref='bomSelectRef' v-if='materialBomOpen'-->
<!--                 :materialIdForm='materialIdForm'></BomSelect>-->
<!--      <div slot='footer' class='dialog-footer'>-->
<!--        <el-button type='primary' @click='submitMaterialBomForm'>确 定</el-button>-->
<!--        <el-button @click='materialBomOpen = false'>取 消</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->

    <!-- 添加物料信息对话框 -->
    <el-dialog title='选择物料信息' v-model='materialOpen' width='1200px' append-to-body>
      <MaterialSelect @selection='handleSelection' ref='materialSelectRef' v-if='materialOpen'></MaterialSelect>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='submitMaterialForm'>确 定</el-button>
        <el-button @click='materialOpen = false'>取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量添加半制品计划信息对话框 -->
    <el-dialog :title='sfpBatchDialog.title' v-model='sfpBatchDialog.visible' width='1000px' append-to-body>
      <template #header='{ close, titleId, titleClass }'>
        <div class='my-header'>
          {{ sfpBatchDialog.title }}
        </div>
      </template>
      <el-container style='height: 500px; border: 1px solid #eee'>
        <div style='width: 400px; height: 100%; overflow: auto'>
          <el-form-item label='工序名称' prop='processId'>
            <el-select v-model='form.processId' placeholder='请先选择工序，再选择机台' @change='getMachine'>
              <el-option
                v-for='item in processList'
                :key='item.processId'
                :label='item.processName'
                :value='item.processId'
              />
            </el-select>
          </el-form-item>
          <el-divider content-position='center'>机台信息</el-divider>
          <div style='margin-bottom: 8px'>
            <span style='font-weight:700; padding: 0 4px'>已勾选机台:</span>
            <el-tag type='primary' v-for='tag in machineNameTags'>{{ tag }}</el-tag>
          </div>
          <el-form ref='querySfpFormRef' :model='machineQueryParams' :inline='true' label-width='68px'>
              <span style='font-weight:700; padding: 0 4px'>
                机台编号
              </span>
            <el-input v-model='machineQueryParams.machineCode' placeholder='请输入机台编号' clearable
                      style='width: 120px;' />
            <span style='font-weight:700; padding: 0 4px'>
                机台名称
              </span>
            <el-input v-model='machineQueryParams.machineName' placeholder='请输入机台名称' clearable
                      style='width: 120px;' />
            <el-form-item>
              <el-button type='primary' icon='Search' @click='handleMachineQuery'>搜索</el-button>
            </el-form-item>
          </el-form>
          <el-table v-loading='loading' :data='prodBaseMachineInfoList'
                    @selection-change='handleSelectionMachineChange'>
            <el-table-column type='selection' width='55' align='center' />
            <el-table-column label='主键标识' align='center' prop='machineId' v-if='false' />
            <el-table-column label='机台编号' align='center' prop='machineCode' />
            <el-table-column label='机台名称' align='center' prop='machineName' />
          </el-table>
        </div>
        <el-container>
          <el-header style='text-align: right; font-size: 12px'>
            <el-form ref='planInfoFormRef' :model='form' :rules='rules' label-width='100px'>
              <el-form-item label='物料名称' prop='materialId'>
                <el-input v-model='form.materialName' placeholder='请点击检索物料' @click='handleMaterialAdd' readonly>
                  <template #append>
                    <el-icon class='el-input__icon'>
                      <search />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label='BOM版本' prop='materialBomVersion'>
                <el-select v-model='form.materialBomVersion' placeholder='请选择BOM版本'>
                  <el-option
                    v-for='item in materialBomVersionOptions'
                    :key='item.materialBomVersion'
                    :label='`${item.materialBomVersion} - ${item.materialBomDesc}`'
                    :value='item.materialBomVersion'
                  />
                </el-select>
              </el-form-item>

              <el-form-item label='计划时间' prop='planBeginTime'>
                <el-date-picker clearable
                                v-model='form.planBeginTime'
                                type='date'
                                value-format='YYYY-MM-DD HH:mm:ss'
                                placeholder='请选择计划时间'>
                </el-date-picker>
              </el-form-item>
              <!--              <el-form-item label='计划结束时间' prop='planEndTime'>-->
              <!--                <el-date-picker clearable-->
              <!--                                v-model='form.planEndTime'-->
              <!--                                type='date'-->
              <!--                                value-format='YYYY-MM-DD HH:mm:ss'-->
              <!--                                placeholder='请选择计划结束时间'>-->
              <!--                </el-date-picker>-->
              <!--              </el-form-item>-->
              <el-form-item label='班组' prop='classTeamId'>
                <el-select v-model='form.classTeamId' placeholder='请选择班组'>
                  <el-option
                    v-for='item in classTeamList'
                    :key='item.classTeamId'
                    :label='item.teamName'
                    :value='item.classTeamId'
                  />
                </el-select>
              </el-form-item>
              <el-form-item label='早班数量' prop='planAmount1'>
                <el-input-number v-model='form.planAmount1' placeholder='请输入计划数量' style='width: 200px;' />
              </el-form-item>
              <el-form-item label='中班数量' prop='planAmount2'>
                <el-input-number v-model='form.planAmount2' placeholder='请输入计划数量' style='width: 200px;' />
              </el-form-item>
              <el-form-item label='晚班数量' prop='planAmount3'>
                <el-input-number v-model='form.planAmount3' placeholder='请输入计划数量' style='width: 200px;' />
              </el-form-item>

            </el-form>
          </el-header>
        </el-container>
      </el-container>

      <template #footer>
        <div class='dialog-footer'>
          <el-button :loading='buttonLoading' type='primary' @click='submitForm'>确 定</el-button>
          <el-button @click='cancel'>取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量添加成型计划信息对话框 -->
    <el-dialog v-model='formingBatchDialog.visible' width='1000px' append-to-body>
      <template #header='{ close, titleId, titleClass }'>
        <div class='my-header'>
          {{ formingBatchDialog.title }}
        </div>
      </template>
      <el-container style='height: 500px; border: 1px solid #eee'>
        <div style='width: 400px; height: 100%; overflow: auto'>
          <el-divider content-position='center'>机台信息</el-divider>
          <div style='margin-bottom: 8px'>
            <span style='font-weight:700; padding: 0 4px'>已勾选机台:</span>
            <el-tag type='primary' v-for='tag in machineNameTags'>{{ tag }}</el-tag>
          </div>
          <el-form ref='queryFormingFormRef' :model='machineQueryParams' :inline='true' label-width='68px'>
              <span style='font-weight:700; padding: 0 4px'>
                机台编号
              </span>
            <el-input v-model='machineQueryParams.machineCode' placeholder='请输入机台编号' clearable
                      style='width: 120px;' />
            <span style='font-weight:700; padding: 0 4px'>
                机台名称
              </span>
            <el-input v-model='machineQueryParams.machineName' placeholder='请输入机台名称' clearable
                      style='width: 120px;' />
            <el-form-item>
              <el-button type='primary' icon='Search' @click='handleMachineQuery'>搜索</el-button>
            </el-form-item>
          </el-form>
          <el-table v-loading='loading' :data='prodBaseMachineInfoList'
                    @selection-change='handleSelectionMachineChange'>
            <el-table-column type='selection' width='55' align='center' />
            <el-table-column label='主键标识' align='center' prop='machineId' v-if='false' />
            <el-table-column label='机台编号' align='center' prop='machineCode' />
            <el-table-column label='机台名称' align='center' prop='machineName' />
          </el-table>
        </div>
        <el-container>
          <el-header style='text-align: right; font-size: 12px'>
            <el-form ref='planInfoFormRef' :model='form' :rules='rules' label-width='100px'>
              <el-form-item label='物料名称' prop='materialId'>
                <el-input v-model='form.materialName' placeholder='请点击检索物料' @click='handleMaterialAdd' readonly>
                  <template #append>
                    <el-icon class='el-input__icon'>
                      <search />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label='BOM版本' prop='materialBomVersion'>
                <el-select v-model='form.materialBomVersion' placeholder='请选择BOM版本'>
                  <el-option
                    v-for='item in materialBomVersionOptions'
                    :key='item.materialBomVersion'
                    :label='`${item.materialBomVersion} - ${item.materialBomDesc}`'
                    :value='item.materialBomVersion'
                  />
                </el-select>
              </el-form-item>
              <el-form-item label='计划时间' prop='planBeginTime'>
                <el-date-picker clearable
                                v-model='form.planBeginTime'
                                type='date'
                                value-format='YYYY-MM-DD HH:mm:ss'
                                placeholder='请选择计划时间'>
                </el-date-picker>
              </el-form-item>
              <!--              <el-form-item label='计划结束时间' prop='planEndTime'>-->
              <!--                <el-date-picker clearable-->
              <!--                                v-model='form.planEndTime'-->
              <!--                                type='date'-->
              <!--                                value-format='YYYY-MM-DD HH:mm:ss'-->
              <!--                                placeholder='请选择计划结束时间'>-->
              <!--                </el-date-picker>-->
              <!--              </el-form-item>-->
              <el-form-item label='班组' prop='classTeamId'>
                <el-select v-model='form.classTeamId' placeholder='请选择班组'>
                  <el-option
                    v-for='item in classTeamList'
                    :key='item.classTeamId'
                    :label='item.teamName'
                    :value='item.classTeamId'
                  />
                </el-select>
              </el-form-item>
              <el-form-item label='早班数量' prop='planAmount1'>
                <el-input-number v-model='form.planAmount1' placeholder='请输入计划数量' style='width: 200px;' />
              </el-form-item>
              <el-form-item label='中班数量' prop='planAmount2'>
                <el-input-number v-model='form.planAmount2' placeholder='请输入计划数量' style='width: 200px;' />
              </el-form-item>
              <el-form-item label='晚班数量' prop='planAmount3'>
                <el-input-number v-model='form.planAmount3' placeholder='请输入计划数量' style='width: 200px;' />
              </el-form-item>

            </el-form>
          </el-header>
        </el-container>
      </el-container>

      <template #footer>
        <div class='dialog-footer'>
          <el-button :loading='buttonLoading' type='primary' @click='submitForm'>确 定</el-button>
          <el-button @click='cancel'>取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量添加硫化计划信息对话框 -->
    <el-dialog v-model='vulBatchDialog.visible' width='1300px' append-to-body>
      <template #header='{ close, titleId, titleClass }'>
        <div class='my-header'>
          {{ vulBatchDialog.title }}
        </div>
      </template>
      <el-container style='height: 500px; border: 1px solid #eee'>
        <div style='width: 400px; height: 100%; overflow: auto'>
          <el-divider content-position='center'>机台信息</el-divider>
          <div style='margin-bottom: 8px'>
            <span style='font-weight:700; padding: 0 4px'>已勾选机台:</span>
            <el-tag type='primary' v-for='tag in machineNameTags'>{{ tag }}</el-tag>
          </div>
          <el-form ref='queryVulFormRef' :model='machineQueryParams' :inline='true' label-width='68px'>
              <span style='font-weight:700; padding: 0 4px'>
                机台编号
              </span>
            <el-input v-model='machineQueryParams.machineCode' placeholder='请输入机台编号' clearable
                      style='width: 120px;' />
            <span style='font-weight:700; padding: 0 4px'>
                机台名称
              </span>
            <el-input v-model='machineQueryParams.machineName' placeholder='请输入机台名称' clearable
                      style='width: 120px;' />
            <el-form-item>
              <el-button type='primary' icon='Search' @click='handleMachineQuery'>搜索</el-button>
            </el-form-item>
          </el-form>
          <el-table v-loading='loading' :data='prodBaseMachineInfoList'
                    @selection-change='handleSelectionMachineChange'>
            <el-table-column type='selection' width='55' align='center' />
            <el-table-column label='主键标识' align='center' prop='machineId' v-if='false' />
            <el-table-column label='机台编号' align='center' prop='machineCode' />
            <el-table-column label='机台名称' align='center' prop='machineName' />
          </el-table>
        </div>
        <el-container>
          <el-header style='text-align: right; font-size: 12px;margin-top: 12px'>
            <el-form ref='planInfoFormRef' :model='form' :rules='rules' label-width='100px'>
              <el-row :gutter='10' class='mb8'>
                <el-col :span='12'>
                  <el-form-item label='计划时间' prop='planBeginTime'>
                    <el-date-picker clearable
                                    v-model='form.planBeginTime'
                                    type='date'
                                    value-format='YYYY-MM-DD HH:mm:ss'
                                    placeholder='请选择计划时间'>
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span='12'>
                  <el-form-item label='班组' prop='classTeamId'>
                    <el-select v-model='form.classTeamId' placeholder='请选择班组'>
                      <el-option
                        v-for='item in classTeamList'
                        :key='item.classTeamId'
                        :label='item.teamName'
                        :value='item.classTeamId'
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter='10' class='mb8'>
                <el-col :span='12'>
                  <el-form-item label='左模物料' prop='materialNameL'>
                    <el-input v-model='form.materialNameL' placeholder='请点击检索物料' @click='handleMaterialAdd("L")'
                              readonly>
                      <template #append>
                        <el-icon class='el-input__icon'>
                          <search />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span='12'>
                  <el-form-item label='右模物料' prop='materialNameR'>
                    <el-input v-model='form.materialNameR' placeholder='请点击检索物料' @click='handleMaterialAdd("R")'
                              readonly>
                      <template #append>
                        <el-icon class='el-input__icon'>
                          <search />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter='10' class='mb8'>
                <el-col :span='12'>
                  <el-form-item label='BOM版本' prop='materialBomVersionL'>
                    <el-select v-model='form.materialBomVersionL' placeholder='请选择BOM版本'>
                      <el-option
                        v-for='item in materialBomVersionLOptions'
                        :key='item.materialBomVersion'
                        :label='`${item.materialBomVersion} - ${item.materialBomDesc}`'
                        :value='item.materialBomVersion'
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span='12'>
                  <el-form-item label='BOM版本' prop='materialBomVersionR'>
                    <el-select v-model='form.materialBomVersionR' placeholder='请选择BOM版本'>
                      <el-option
                        v-for='item in materialBomVersionROptions'
                        :key='item.materialBomVersion'
                        :label='`${item.materialBomVersion} - ${item.materialBomDesc}`'
                        :value='item.materialBomVersion'
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter='10' class='mb8'>
                <el-col :span='12'>
                  <el-form-item label='左模早班数量' prop='planAmount1'>
                    <el-input-number v-model='form.planAmount1' placeholder='请输入计划数量' style='width: 200px;' />
                  </el-form-item>
                  <el-form-item label='左模中班数量' prop='planAmount2'>
                    <el-input-number v-model='form.planAmount2' placeholder='请输入计划数量' style='width: 200px;' />
                  </el-form-item>
                  <el-form-item label='左模晚班数量' prop='planAmount3'>
                    <el-input-number v-model='form.planAmount3' placeholder='请输入计划数量' style='width: 200px;' />
                  </el-form-item>
                </el-col>
                <el-col :span='12'>
                  <el-form-item label='右模早班数量' prop='planAmount4'>
                    <el-input-number v-model='form.planAmount4' placeholder='请输入计划数量' style='width: 200px;' />
                  </el-form-item>
                  <el-form-item label='右模中班数量' prop='planAmount5'>
                    <el-input-number v-model='form.planAmount5' placeholder='请输入计划数量' style='width: 200px;' />
                  </el-form-item>
                  <el-form-item label='右模晚班数量' prop='planAmount6'>
                    <el-input-number v-model='form.planAmount6' placeholder='请输入计划数量' style='width: 200px;' />
                  </el-form-item>
                </el-col>
              </el-row>
              <!--        <el-form-item label="附件信息" prop="attachId">-->
              <!--          <el-input v-model="form.attachId" placeholder="请输入附件信息" />-->
              <!--        </el-form-item>-->
              <!--        <el-form-item label='优先级' prop='priority'>-->
              <!--          <el-input-number v-model='form.priority' placeholder='请输入优先级' style='width: 200px;' />-->
              <!--        </el-form-item>-->
              <!--        <el-form-item label='班次' prop='shiftId'>-->
              <!--          <el-radio-group v-model='form.shiftId'>-->
              <!--            <el-radio-->
              <!--              v-for='dict in shiftList'-->
              <!--              :key='dict.shiftId'-->
              <!--              :value='dict.shiftId'-->
              <!--            >{{ dict.shiftName }}-->
              <!--            </el-radio>-->
              <!--          </el-radio-group>-->
              <!--        </el-form-item>-->
              <!--        <el-form-item label='模号' prop='modelCode'>-->
              <!--          <el-radio-group v-model='form.modelCode'>-->
              <!--            <el-radio-->
              <!--              v-for='dict in mes_model_code'-->
              <!--              :key='dict.value'-->
              <!--              :value='dict.value'-->
              <!--            >{{ dict.label }}-->
              <!--            </el-radio>-->
              <!--          </el-radio-group>-->
              <!--        </el-form-item>-->
              <!--        <el-form-item label='备注' prop='remark'>-->
              <!--          <el-input v-model='form.remark' placeholder='请输入备注' />-->
              <!--        </el-form-item>-->
            </el-form>
          </el-header>
        </el-container>
      </el-container>

      <template #footer>
        <div class='dialog-footer'>
          <el-button :loading='buttonLoading' type='primary' @click='submitForm'>确 定</el-button>
          <el-button @click='cancel'>取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name='PlanInfo' lang='ts'>
import {
  listPlanInfo,
  getPlanInfo,
  delPlanInfo,
  addPlanInfo,
  updatePlanInfo,
  orderAddProductPlanList, issuePlanInfo,
  materialBomTreeSelect,
  materialBomVersionSelect
} from '@/api/mes/planInfo';
import { PlanInfoVO, PlanInfoQuery, PlanInfoForm } from '@/api/mes/planInfo/types';
import { getBaseShiftInfoList } from '@/api/mes/baseShiftInfo';
import { getBaseClassTeamInfoList } from '@/api/mes/baseClassTeamInfo';
import BomSelect from '@/views/mes/materialBom/addBom.vue';
import MaterialSelect from '@/views/mes/baseMaterialInfo/addMaterial.vue';
import { getProcessInfoList } from '@/api/mes/baseProcessInfo';
import { getStationInfoList } from '@/api/mes/baseStationInfo';
import { getProdBaseMachineInfoList } from '@/api/mes/prodBaseMachineInfo';
import { ProdBaseMachineInfoVO } from '@/api/mes/prodBaseMachineInfo/types';
import { MaterialBomVO } from '@/api/mes/materialBom/types';
import { optionselect } from '@/api/system/post';
import { cloneDeep } from 'lodash-es';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  mes_import_flag,
  active_flag,
  mes_plan_status,
  mes_release_type,
  mes_finish_flag,
  mes_model_code
} = toRefs<any>(proxy?.useDict('mes_import_flag', 'active_flag', 'mes_plan_status', 'mes_release_type', 'mes_finish_flag', 'mes_model_code'));

const planInfoList = ref<PlanInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const planInfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const sfpBatchDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const formingBatchDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const vulBatchDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const shiftList = ref([]);
const classTeamList = ref([]);
const processList = ref([]);
let releaseList = ref([]);
const materialBomOpen = ref(false);
const bomSelectRef = ref();
const materialOpen = ref(false);
const materialSelectRef = ref();
const materialIdForm = ref();

const materialBomVersionOptions = ref<MaterialBomVO[]>([]);

const materialBomVersionLOptions = ref<MaterialBomVO[]>([]);
const materialBomVersionROptions = ref<MaterialBomVO[]>([]);


const workshopId = ref();

const prodBaseMachineInfoList = ref<ProdBaseMachineInfoVO[]>([]);

const machineIds = ref<Array<string | number>>([]);

const machineQueryParams = ref({});

const modelCodeRef = ref();

/*获取班次下拉框*/
const getShiftSelect = async () => {
  let res = await getBaseShiftInfoList(null);
  shiftList.value = res.data;
};

/*获取班组下拉框*/
const getClassTeamSelect = async () => {
  let res = await getBaseClassTeamInfoList(null);
  classTeamList.value = res.data;
};

/*获取半制品工序下拉框*/
const getProcessSelect = async () => {
  let res = await getProcessInfoList({ processType: 1 });
  processList.value = res.data.filter(item => item.processId !== 17 && item.processId !== 18);
};

/*获取机台下拉框*/
const getReleaseSelect = async () => {
  machineQueryParams.value.processId = form.value.processId;
  // machineQueryParams.value.workshopId = workshopId.value;
  let res = await getProdBaseMachineInfoList(machineQueryParams.value);
  releaseList.value = res.data;
  prodBaseMachineInfoList.value = res.data;
};

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `主键标识`, visible: false },
  { key: 1, label: `租户编号`, visible: false },
  { key: 2, label: `生产订单ID`, visible: false },
  { key: 3, label: `销售订单ID`, visible: false },
  { key: 4, label: `销售订单编号`, visible: false },
  { key: 5, label: `计划编号`, visible: true },
  { key: 6, label: `派工单号`, visible: false },
  { key: 7, label: `物料名称`, visible: true },
  { key: 8, label: `BOM版本`, visible: true },
  { key: 9, label: `工序名称`, visible: true },
  { key: 10, label: `顺序`, visible: false },
  { key: 11, label: `上一工序ID`, visible: false },
  { key: 12, label: `最后工序标识`, visible: false },
  { key: 13, label: `下达类型`, visible: true },
  { key: 14, label: `下达ID`, visible: true },
  { key: 15, label: `单位生产时间(秒)`, visible: false },
  { key: 16, label: `计划数量`, visible: true },
  { key: 17, label: `派工数量`, visible: false },
  { key: 18, label: `完成数量`, visible: true },
  { key: 19, label: `计划时间`, visible: true },
  { key: 20, label: `计划结束时间`, visible: false },
  { key: 21, label: `实际开始时间`, visible: true },
  { key: 22, label: `实际完成时间`, visible: true },
  { key: 23, label: `附件信息`, visible: false },
  { key: 24, label: `计划状态`, visible: true },
  { key: 25, label: `导入类型`, visible: false },
  { key: 26, label: `完成标识`, visible: true },
  { key: 27, label: `优先级`, visible: false },
  { key: 28, label: `班次`, visible: true },
  { key: 29, label: `班组`, visible: true },
  { key: 30, label: `模号`, visible: true },
  { key: 31, label: `备注`, visible: false },
  { key: 32, label: `创建部门`, visible: false },
  { key: 33, label: `创建人`, visible: false },
  { key: 34, label: `创建时间`, visible: false },
  { key: 35, label: `更新人`, visible: false },
  { key: 36, label: `更新时间`, visible: false },
  { key: 37, label: `计量单位`, visible: true },
]);

const initFormData: PlanInfoForm = {
  planId: undefined,
  productOrderId: undefined,
  saleOrderId: undefined,
  saleorderCode: undefined,
  planCode: undefined,
  dispatchCode: undefined,
  materialId: undefined,
  materialBomId: undefined,
  processId: undefined,
  processOrder: undefined,
  lastProcessId: undefined,
  finalProcessFlag: undefined,
  releaseType: '1',
  releaseId: undefined,
  productionTime: undefined,
  planAmount: 1,
  dispatchAmount: undefined,
  completeAmount: undefined,
  planBeginTime: undefined,
  planEndTime: undefined,
  realBeginTime: undefined,
  realEndTime: undefined,
  attachId: undefined,
  planStatus: undefined,
  importFlag: undefined,
  finishFlag: [],
  priority: 1,
  shiftId: undefined,
  classTeamId: undefined,
  modelCode: undefined,
  remark: undefined,
  materialBoMName: undefined,
  workshopId: undefined,
  // 批量计划相关字段
  planAmount1: undefined,
  planAmount2: undefined,
  planAmount3: undefined,
  planAmount4: undefined,
  planAmount5: undefined,
  planAmount6: undefined,
  materialIdL: undefined,
  materialNameL: undefined,
  materialIdR: undefined,
  materialNameR: undefined,
  materialBomVersion: undefined,
  materialBomVersionL: undefined,
  materialBomVersionR: undefined,
  materialBoMNameL: undefined,
  materialBoMNameR: undefined,
  materialBoMIdL: undefined,
  materialBoMIdR: undefined,
  shiftName: '',
};
const data = reactive<PageData<PlanInfoForm, PlanInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planId: undefined,
    productOrderId: undefined,
    saleOrderId: undefined,
    saleorderCode: undefined,
    planCode: undefined,
    dispatchCode: undefined,
    materialId: undefined,
    materialBomId: undefined,
    processId: undefined,
    processOrder: undefined,
    lastProcessId: undefined,
    finalProcessFlag: undefined,
    releaseType: undefined,
    releaseId: undefined,
    productionTime: undefined,
    planAmount: undefined,
    dispatchAmount: undefined,
    completeAmount: undefined,
    planBeginTime: undefined,
    planEndTime: undefined,
    realBeginTime: undefined,
    realEndTime: undefined,
    attachId: undefined,
    planStatus: undefined,
    importFlag: undefined,
    finishFlag: undefined,
    priority: undefined,
    shiftId: undefined,
    classTeamId: undefined,
    modelCode: undefined,
    workshopId: undefined,
    params: {},
    planRangeTime: undefined,
    materialName: undefined,
    shiftName: '',
    shifitId: undefined,
  },
  rules: {
    materialId: [
      { required: true, message: '物料名称不能为空', trigger: 'blur' }
    ],
    processId: [
      { required: true, message: '工序不能为空', trigger: 'blur' }
    ],
    releaseId: [
      { required: true, message: '机台名称不能为空', trigger: 'blur' }
    ],
    materialName: [
      { required: true, message: '物料BOM不能为空', trigger: 'blur' }
    ],
    planAmount: [
      { required: true, message: '计划数量不能为空', trigger: 'blur' }
    ],
    planBeginTime: [
      { required: true, message: '计划日期不能为空', trigger: 'blur' }
    ],
    // planAmount1: [
    //   { required: true, message: '早班数量不能为空', trigger: 'blur' }
    // ],
    // planAmount2: [
    //   { required: true, message: '中班数量不能为空', trigger: 'blur' }
    // ],
    // planAmount3: [
    //   { required: true, message: '晚班数量不能为空', trigger: 'blur' }
    // ]
  }
});

const { queryParams, form, rules } = toRefs(data);
const machineNameTags = ref([]);

const getWorkshopId = async () => {
  const router = useRouter();
  workshopId.value = router.currentRoute._rawValue.query && router.currentRoute._rawValue.query.workshopId;
  queryParams.value.workshopId = workshopId.value;
};

/** 查询生产计划信息列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = {
      ...queryParams.value,
      planBeginTime: queryParams.value.planRangeTime?.[0],
      planEndTime: queryParams.value.planRangeTime?.[1]
    };
    const res = await listPlanInfo(params);
    planInfoList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  sfpBatchDialog.visible = false;
  formingBatchDialog.visible = false;
  vulBatchDialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  form.value.workshopId = workshopId.value;
  planInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PlanInfoVO[]) => {
  ids.value = selection.map(item => item.planId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 选择机台条数  */
const handleSelectionMachineChange = (selection: ProdBaseMachineInfoVO[]) => {
  machineIds.value = selection.map(item => item.machineId);
  machineNameTags.value = selection.map(item => item.machineName);
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加生产计划信息';
};

/** 新增半制品按钮操作 */
const handleSfpBatchAdd = () => {
  reset();
  machineIds.value = [];
  sfpBatchDialog.visible = true;
  sfpBatchDialog.title = '添加半制品生产计划信息';
  machineQueryParams.value = {};
  /*  if (form.value.processId != null ){
      getReleaseSelect();
    }*/
};

/** 新增成型按钮操作 */
const handleFormingBatchAdd = () => {
  reset();
  machineIds.value = [];
  formingBatchDialog.visible = true;
  formingBatchDialog.title = '添加成型生产计划信息';
  form.value.processId = 17;
  machineQueryParams.value = {};
  getReleaseSelect();
};

/** 新增硫化按钮操作 */
const handleVulBatchAdd = () => {
  reset();
  machineIds.value = [];
  vulBatchDialog.visible = true;
  vulBatchDialog.title = '添加硫化生产计划信息';
  form.value.processId = 18;
  machineQueryParams.value = {};
  getReleaseSelect();
};

/** 修改按钮操作 */
const handleUpdate = async (row?: PlanInfoVO) => {
  reset();
  const _planId = row?.planId || ids.value[0];
  const res = await getPlanInfo(_planId);
  Object.assign(form.value, res.data);
  // finishFlag 类型守卫
  if (Array.isArray(form.value.finishFlag)) {
    // do nothing
  } else if (typeof form.value.finishFlag === 'string') {
    form.value.finishFlag = form.value.finishFlag.split(',').filter(Boolean).join(',');
  } else {
    form.value.finishFlag = [];
  }
  dialog.visible = true;
  dialog.title = '修改生产计划信息';
};

/** 撤回按钮操作 */
const handleRecall = async (row?: PlanInfoVO) => {
  buttonLoading.value = true;
  let rowData = cloneDeep(row);
  rowData.workshopId = workshopId.value;
  rowData.planStatus = '4';
  await proxy?.$modal.confirm('是否确认撤回计划编号为"' + row.planCode + '"的数据项？').finally(() => {
    updatePlanInfo(rowData).finally(() => buttonLoading.value = false);
  });
  proxy?.$modal.msgSuccess('撤回成功');
  await getList();
};

/** 提交按钮 */
const submitForm = () => {
  planInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      // finishFlag 类型守卫
      if (Array.isArray(form.value.finishFlag)) {
        form.value.finishFlag = form.value.finishFlag.join(',');
      } else if (typeof form.value.finishFlag === 'string') {
        // do nothing
      } else {
        form.value.finishFlag = '';
      }
      //半制品、成型、硫化新增
      let assemblyData = batchesAddAssemblyData();
      if (machineIds.value.length == 0) {
        proxy?.$modal.msgWarning('请选择机台！');
        return;
      }
      await orderAddProductPlanList({
        mesProductPlanList: assemblyData,
        productOrderId: 0,
        machineIds: machineIds.value
      }).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      sfpBatchDialog.visible = false;
      formingBatchDialog.visible = false;
      vulBatchDialog.visible = false;
      await getList();
    }
  });
};

/** 批量新增组装数据 */
const batchesAddAssemblyData = () => {
  const formData = form.value;
  // 统一workshopId类型为字符串，保证比较安全
  const workshopIdStr = formData.workshopId != null ? String(formData.workshopId) : '';
  let list = [];
  if (typeof formData.planAmount1 === 'number' && formData.planAmount1 > 0) {
    let data = { ...formData };
    data.modelCode = workshopIdStr === '4' ? 'L' : null;
    data.materialId = workshopIdStr === '4' ? formData.materialIdL : formData.materialId;
    data.materialBomVersion = workshopIdStr === '4' ? formData.materialBomVersionL : formData.materialBomVersion;
    data.shiftId = '1';
    data.planAmount = formData.planAmount1;
    list.push(data);
  }
  if (typeof formData.planAmount2 === 'number' && formData.planAmount2 > 0) {
    let data = { ...formData };
    data.modelCode = workshopIdStr === '4' ? 'L' : null;
    data.shiftId = '2';
    data.planAmount = formData.planAmount2;
    data.materialId = workshopIdStr === '4' ? formData.materialIdL : formData.materialId;
    data.materialBomVersion = workshopIdStr === '4' ? formData.materialBomVersionL : formData.materialBomVersion;
    list.push(data);
  }
  if (typeof formData.planAmount3 === 'number' && formData.planAmount3 > 0) {
    let data = { ...formData };
    data.modelCode = workshopIdStr === '4' ? 'L' : null;
    data.shiftId = '3';
    data.planAmount = formData.planAmount3;
    data.materialId = workshopIdStr === '4' ? formData.materialIdL : formData.materialId;
    data.materialBomVersion = workshopIdStr === '4' ? formData.materialBomVersionL : formData.materialBomVersion;
    list.push(data);
  }
  if (typeof formData.planAmount4 === 'number' && formData.planAmount4 > 0) {
    let data = { ...formData };
    data.modelCode = 'R';
    data.shiftId = '1';
    data.planAmount = formData.planAmount4;
    data.materialId = workshopIdStr === '4' ? formData.materialIdR : formData.materialId;
    data.materialBomVersion = workshopIdStr === '4' ? formData.materialBomVersionR : formData.materialBomVersion;
    list.push(data);
  }
  if (typeof formData.planAmount5 === 'number' && formData.planAmount5 > 0) {
    let data = { ...formData };
    data.modelCode = 'R';
    data.shiftId = '2';
    data.planAmount = formData.planAmount5;
    data.materialId = workshopIdStr === '4' ? formData.materialIdR : formData.materialId;
    data.materialBomVersion = workshopIdStr === '4' ? formData.materialBomVersionR : formData.materialBomVersion;
    list.push(data);
  }
  if (typeof formData.planAmount6 === 'number' && formData.planAmount6 > 0) {
    let data = { ...formData };
    data.modelCode = 'R';
    data.shiftId = '3';
    data.planAmount = formData.planAmount6;
    data.materialId = workshopIdStr === '4' ? formData.materialIdR : formData.materialId;
    data.materialBomVersion = workshopIdStr === '4' ? formData.materialBomVersionR : formData.materialBomVersion;
    list.push(data);
  }
  return list;
};

/** 删除按钮操作 */
const handleDelete = async (row?: PlanInfoVO) => {
  const _planIds = row?.planId || ids.value;
  await proxy?.$modal.confirm('是否确认删除生产计划信息编号为"' + _planIds + '"的数据项？').finally(() => loading.value = false);
  await delPlanInfo(_planIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};


/** 下发选中计划 */
const handleIssuePlanInfo = async (row?: PlanInfoVO) => {
  const _planIds = row?.planId || ids.value;
  await proxy?.$modal.confirm('是否下发已选中的生产计划？').finally(() => loading.value = false);
  await issuePlanInfo(workshopId.value, _planIds);
  proxy?.$modal.msgSuccess('下发选中计划成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('mes/planInfo/export', {
    ...queryParams.value
  }, `planInfo_${new Date().getTime()}.xlsx`);
};

/** 新增物料按钮操作 */
const handleMaterialAdd = (modelCode) => {
  modelCodeRef.value = modelCode;
  materialOpen.value = true;
};

/** 提交物料信息按钮 */
const submitMaterialForm = () => {
  let selectedRow = materialSelectRef.value.tableRef.store.states.currentRow.value;
  if (modelCodeRef.value === 'L') {
    form.value.materialIdL = selectedRow.materialId;
    form.value.materialNameL = selectedRow.materialName;
    getMaterialBomVersionSelect('L');
  } else if (modelCodeRef.value === 'R') {
    form.value.materialIdR = selectedRow.materialId;
    form.value.materialNameR = selectedRow.materialName;
    getMaterialBomVersionSelect('R');
  } else {
    form.value.materialId = selectedRow.materialId;
    form.value.materialName = selectedRow.materialName;
    getMaterialBomVersionSelect('');
  }
  materialIdForm.value = selectedRow.materialId;
  materialOpen.value = false;
};

/** 新增物料BOM按钮操作 */
// const handleMaterialBomAdd = (modelCode) => {
//   if (form.value.materialId == null && form.value.materialIdL == null
//     && form.value.materialIdR == null) {
//     proxy?.$modal.msgWarning('请先选择物料！');
//     return;
//   }
//   modelCodeRef.value = modelCode;
//   materialBomOpen.value = true;
// };

/** 提交物料BOM信息按钮 */
const submitMaterialBomForm = () => {
  let selectedRow = bomSelectRef.value.tableRef.store.states.currentRow.value;
  if (modelCodeRef.value === 'L') {
    form.value.materialBomIdL = selectedRow.materialBomId;
    form.value.materialBoMNameL = selectedRow.materialName;
  } else if (modelCodeRef.value === 'R') {
    form.value.materialBomIdR = selectedRow.materialBomId;
    form.value.materialBoMNameR = selectedRow.materialName;
  } else {
    form.value.materialBomId = selectedRow.materialBomId;
    form.value.materialBoMName = selectedRow.materialName;
  }
  materialBomOpen.value = false;
};

/** 搜索机台信息按钮操作 */
function handleMachineQuery() {
  getReleaseSelect();
}

const getMachine = async () => {
  console.log(form.value.processId);
  if (workshopId.value == 2 && form.value.processId != null) {
    await getReleaseSelect();
  }
};

/** 查询物料bom版本下拉列表 */
const getMaterialBomVersionSelect = async (type: string) => {

  if (type === 'L') {//硫化计划左模物料
    materialBomVersionLOptions.value = [];
    if (form.value.materialIdL && form.value.materialIdL !== '') {
      const query = {parentId: form.value.materialIdL  };
      const res = await materialBomVersionSelect(query);
      materialBomVersionLOptions.value = res.data;
    }

  } else if (type === 'R') {//硫化计划右模物料
    materialBomVersionROptions.value = [];
    if (form.value.materialIdR && form.value.materialIdR !== '') {
      const query = {  parentId: form.value.materialIdR  };
      const res = await materialBomVersionSelect(query);
      materialBomVersionROptions.value = res.data;
    }
  } else {//半制品计划或成型计划
    materialBomVersionOptions.value = [];
    if (form.value.materialId && form.value.materialId !== '') {
      const query = {  parentId: form.value.materialId  };
      const res = await materialBomVersionSelect(query);
      materialBomVersionOptions.value = res.data;
    }
  }

};


/** 查询物料bom下拉树结构 */
const getTreeSelect = async () => {
  const res = await materialBomTreeSelect();
  materialBomVersionOptions.value = res.data;
};


onMounted(() => {
  getWorkshopId();
  getShiftSelect();
  getClassTeamSelect();
  getProcessSelect();
  if (form.value.processId != null) {
    getReleaseSelect();
  }
  getList();
});

// 监听 processId 的变化
// watch(
//   () => form.value.processId, (newValue, oldValue) => {
//     // 监听到变化时执行的函数
//     getReleaseSelect();
//   }
// );
</script>
<style>
.my-header {
  width: 100%;
  text-align: center;
}

.el-overlay .el-overlay-dialog .el-dialog .el-dialog__header {
  border-bottom: none;
}
</style>
