<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-[0px]'>
        <el-card shadow='hover'>
          <el-form ref='queryFormRef' :model='queryParams' :inline='true' label-width='100px'>
            <el-form-item label='工艺路线名称' prop='routeName'>
              <el-input v-model='queryParams.routeName' placeholder='请输入工艺路线名称' clearable @keyup.enter='handleQuery' />
            </el-form-item>
            <el-form-item label='状态' prop='activeFlag'>
              <el-select v-model='queryParams.activeFlag' placeholder='请选择状态' clearable>
                <el-option v-for='dict in mes_route_active_flag' :key='dict.value' :label='dict.label' :value='dict.value'/>
              </el-select>
            </el-form-item>
            <!--            <el-form-item label='首件检验' prop='needFirstInspect'>-->
            <!--              <el-select v-model='queryParams.needFirstInspect' placeholder='请选择首件检验' clearable>-->
            <!--                <el-option v-for='dict in mes_need_first_inspect' :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:baseRoute:add']">新增
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='success' plain icon='Edit' :disabled='single' @click='handleUpdate()'
                       v-hasPermi="['mes:baseRoute:edit']">修改
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='danger' plain icon='Delete' :disabled='multiple' @click='handleDelete()'
                       v-hasPermi="['mes:baseRoute:remove']">删除
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='warning' plain icon='Download' @click='handleExport' v-hasPermi="['mes:baseRoute: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='baseRouteList' @selection-change='handleSelectionChange'>
        <el-table-column type='selection' width='55' align='center' />
        <el-table-column label='工艺路线ID' align='center' prop='routeId' v-if='columns[0].visible' />
        <el-table-column label='租户编号' align='center' prop='tenantId' v-if='columns[1].visible' />
        <el-table-column label='工艺路线名称' align='center' prop='routeName' v-if='columns[2].visible' width='110'/>
        <el-table-column label='工艺路线说明' align='center' prop='routeDesc' v-if='columns[3].visible' width='110'/>
        <el-table-column label='工艺路线版本' align='center' prop='routeVersion' v-if='columns[11].visible' width='110'/>
        <el-table-column label='生产类型' align='center' prop='productionType' v-if='columns[12].visible'>
          <template #default='scope'>
            <dict-tag :options='mes_process_production_type' :value='scope.row.productionType'/>
          </template>
        </el-table-column>
        <el-table-column label='路线类型' align='center' prop='routeType' v-if='columns[13].visible'>
          <template #default='scope'>
            <dict-tag :options='mes_route_type' :value='scope.row.routeType'/>
          </template>
        </el-table-column>
        <el-table-column label='审核原因' align='center' prop='auditReason' v-if='columns[14].visible'/>
        <el-table-column label='审核人' align='center' prop='approveBy' v-if='columns[15].visible'/>
        <el-table-column label='审核时间' align='center' prop='approveTime' width='180' v-if='columns[16].visible'>
          <template #default='scope'>
            <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label='首件检验' align='center' prop='needFirstInspect' v-if='columns[17].visible'>
          <template #default='scope'>
            <dict-tag :options='mes_need_first_inspect' :value='scope.row.needFirstInspect'/>
          </template>
        </el-table-column>
        <el-table-column label='打印流转卡' align='center' prop='printFlowCard' v-if='columns[18].visible' width='100'>
          <template #default='scope'>
            <dict-tag :options='mes_print_flow_card' :value='scope.row.printFlowCard'/>
          </template>
        </el-table-column>
        <el-table-column label='批次量' align='center' prop='batchSize' v-if='columns[19].visible'/>
        <el-table-column label='状态' align='center' prop='activeFlag' v-if='columns[4].visible'>
          <template #default='scope'>
            <dict-tag :options='mes_route_active_flag' :value='scope.row.activeFlag' />
          </template>
        </el-table-column>
        <el-table-column label='备注' align='center' prop='remark' v-if='columns[5].visible' />
        <el-table-column label='创建部门' align='center' prop='createDept' v-if='columns[6].visible' />
        <el-table-column label='创建人' align='center' prop='createBy' v-if='columns[7].visible' />
        <el-table-column label='创建时间' align='center' prop='createTime' width='180' v-if='columns[8].visible'>
          <template #default='scope'>
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label='更新人' align='center' prop='updateBy' v-if='columns[9].visible' />
        <el-table-column label='更新时间' align='center' prop='updateTime' width='180' v-if='columns[10].visible'>
          <template #default='scope'>
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label='操作' align='center' class-name='small-padding fixed-width'>
          <template #default='scope'>
            <!--            <el-tooltip content='修改' placement='top'>
                          <el-button link type='primary' icon='Edit' @click='handleUpdate(scope.row)'
                                     v-hasPermi="['mes:baseRoute:edit']"></el-button>
                        </el-tooltip>
                        <el-tooltip content='删除' placement='top'>
                          <el-button link type='primary' icon='Delete' @click='handleDelete(scope.row)'
                                     v-hasPermi="['mes:baseRoute:remove']"></el-button>
                        </el-tooltip>-->

            <el-button
              size="small"
              type="text"
              icon="el-icon-edit"
              @click="routeMaterialUpdate(scope.row)"
              v-hasPermi="['mes:baseRoute:edit']"
            >关联物料
            </el-button>

            <el-button
              size="small"
              type="text"
              icon="el-icon-edit"
              @click="routeProcessUpdate(scope.row)"
              v-hasPermi="['mes:baseRoute:edit']"
            >关联工艺步骤
            </el-button>

          </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='baseRouteFormRef' :model='form' :rules='rules' label-width='110px'>
        <el-form-item label='工艺路线名称' prop='routeName'>
          <el-input v-model='form.routeName' placeholder='请输入工艺路线名称' />
        </el-form-item>
        <el-form-item label='工艺路线说明' prop='routeDesc'>
          <el-input v-model='form.routeDesc' placeholder='请输入工艺路线说明' />
        </el-form-item>
        <el-form-item label='工艺路线版本' prop='routeVersion'>
          <el-input v-model='form.routeVersion' placeholder='请输入工艺路线版本' />
        </el-form-item>
        <el-form-item label='生产类型' prop='productionType'>
          <el-select v-model='form.productionType' placeholder='请选择生产类型'>
            <el-option
              v-for='dict in mes_process_production_type'
              :key='dict.value'
              :label='dict.label'
              :value='dict.value'
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='路线类型' prop='routeType'>
          <el-select v-model='form.routeType' placeholder='请选择路线类型'>
            <el-option
              v-for='dict in mes_route_type'
              :key='dict.value'
              :label='dict.label'
              :value='dict.value'
            ></el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label='审核原因' prop='auditReason'>-->
        <!--          <el-input v-model='form.auditReason' placeholder='请输入审核原因' />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label='审核人' prop='approveBy'>-->
        <!--          <el-input v-model='form.approveBy' placeholder='请输入审核人' />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label='审核时间' prop='approveTime'>-->
        <!--          <el-date-picker clearable-->
        <!--            v-model='form.approveTime'-->
        <!--            type='datetime'-->
        <!--            value-format='YYYY-MM-DD HH:mm:ss'-->
        <!--            placeholder='请选择审核时间'>-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <el-form-item label='首件检验' prop='needFirstInspect'>
          <el-radio-group v-model='form.needFirstInspect'>
            <el-radio
              v-for='dict in mes_need_first_inspect'
              :key='dict.value'
              :value='dict.value'
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='打印流转卡' prop='printFlowCard'>
          <el-radio-group v-model='form.printFlowCard'>
            <el-radio
              v-for='dict in mes_print_flow_card'
              :key='dict.value'
              :value='dict.value'
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='批次量' prop='batchSize'>
          <el-input-number v-model='form.batchSize' placeholder='请输入批次量' />
        </el-form-item>
        <!--        <el-form-item label='状态' prop='activeFlag'>-->
        <!--          <el-radio-group v-model='form.activeFlag'>-->
        <!--            <el-radio-->
        <!--              v-for='dict in mes_route_active_flag'-->
        <!--              :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>

    <!--维护工艺路线关联物料对话框-->
    <el-dialog :title='dialog.title' v-model='materialOpen' width='700px' append-to-body>
      <el-form ref='baseRouteFormRef' :model='form' :rules='rules' label-width='110px'>
        <el-form-item label='工艺路线名称' prop='routeName'>
          <el-input v-model='form.routeName' placeholder='请输入工艺路线名称' disabled />
        </el-form-item>
        <el-divider content-position='center'>工艺路线关联物料信息</el-divider>
        <el-row :gutter='10' class='mb8'>
          <el-col :span='1.5'>
            <el-button type='primary' icon='Plus' size='small' @click='handleAddRouteMaterial'>添加物料</el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='danger' icon='Delete' size='small' @click='handleDeleteRouteMaterial'>删除</el-button>
          </el-col>
        </el-row>
        <el-table
          :data="prodBaseRouteMaterialList"
          :row-class-name="rowRouteMaterialIndex"
          @selection-change="handleRouteMaterialSelectionChange"
          ref="mesBaseRouteMaterial"
        >
          <el-table-column type='selection' width='50' align='center' />
          <el-table-column label='序号' align='center' prop='index' v-if='false' />
          <el-table-column label='关联物料' prop='materialId' align='center'>
            <template #default='scope'>
              <el-input
                v-model='scope.row.materialName'
                placeholder='请选择物料'
                readonly
                @click='openMaterialDialog(scope.$index)'
              />
            </template>
          </el-table-column>
          <el-table-column label='激活标识' prop='activeFlag' align='center' width='150'>
            <template #default='scope'>
              <el-radio-group v-model='scope.row.activeFlag'>
                <el-radio
                  v-for='dict in active_flag'
                  :key='dict.value'
                  :value='dict.value'
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class='dialog-footer'>
          <el-button type='primary' @click='submitForm' >确 定</el-button>
          <el-button @click='cancel'>取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 物料选择弹窗 -->
    <el-dialog title='选择物料信息' v-model='materialDialogOpen' width='1200px' append-to-body>
      <MaterialSelect ref='materialSelectRef' v-if='materialDialogOpen'></MaterialSelect>
      <template #footer>
        <el-button type='primary' @click='handleMaterialSelection'>确 定</el-button>
        <el-button @click='materialDialogOpen = false'>取 消</el-button>
      </template>
    </el-dialog>

    <!-- 关联工艺步骤对话框 -->
    <el-dialog :title='dialog.title' v-model='processOpen' width='1200px' append-to-body>
      <el-form ref='baseRouteFormRef' :model='form' label-width='100px'>
        <el-form-item label='工艺路线名称' prop='routeName'>
          <el-input v-model='form.routeName' placeholder='请输入工艺路线名称' disabled />
        </el-form-item>
        <el-divider content-position='center'>工艺路线关联工艺步骤信息</el-divider>
        <el-row :gutter='10' class='mb8'>
          <el-col :span='1.5'>
            <el-button type='primary' icon='Plus' size='small' @click='handleAddRouteProcess'>添加工艺步骤</el-button>
          </el-col>
        </el-row>
        <el-table
          :data="routeProcessList"
          :row-class-name="rowRouteProcessIndex"
          ref="mesBaseRouteProcess"
        >
          <el-table-column type='selection' width='50' align='center' />
          <el-table-column label='序号' align='center' prop='index' v-if='false' />
          <el-table-column label='关联工序' prop='processId' align='center' width='180'>
            <template #default='scope'>
              <span>{{ getProcessName(scope.row.processId) }}</span>
            </template>
          </el-table-column>
          <el-table-column label='工艺路线顺序' prop='processOrder' align='center' width='120' />
          <el-table-column label='委外标识' prop='outsourcingFlag' align='center' width='120'>
            <template #default='scope'>
              <dict-tag :options='mes_outsourcing_flag' :value='scope.row.outsourcingFlag'/>
            </template>
          </el-table-column>
          <el-table-column label='工序类型' prop='operationType' align='center' width='120'>
            <template #default='scope'>
              <dict-tag :options='process_type' :value='scope.row.operationType'/>
            </template>
          </el-table-column>
          <el-table-column label='是否需要上料' prop='needFeeding' align='center' width='120'>
            <template #default='scope'>
              <dict-tag :options='mes_need_feeding' :value='scope.row.needFeeding'/>
            </template>
          </el-table-column>
          <el-table-column label='设备点检' prop='needEquipmentCheck' align='center' width='120'>
            <template #default='scope'>
              <dict-tag :options='mes_need_equipment_check' :value='scope.row.needEquipmentCheck'/>
            </template>
          </el-table-column>
          <el-table-column label='实际产出率(%)' prop='actualYieldRate' align='center' width='120' />
          <el-table-column label='领料方式' prop='materialIssuance' align='center' width='120'>
            <template #default='scope'>
              <dict-tag :options='mes_material_method' :value='scope.row.materialIssuance'/>
            </template>
          </el-table-column>
          <el-table-column label='委外提前期(秒)' prop='outsourcingLeadTime' align='center' width='120' />
          <el-table-column label='准备时间(秒)' prop='setupTime' align='center' width='120' />
          <el-table-column label='加工时间(秒)' prop='processingTime' align='center' width='120' />
          <el-table-column label='拆卸时间(秒)' prop='teardownTime' align='center' width='120' />
          <el-table-column label='生产节拍(秒/件)' prop='productionTakt' align='center' width='120' />
          <el-table-column label='质检方式' prop='inspectionMethod' align='center' width='120'>
            <template #default='scope'>
              <dict-tag :options='mes_inspection_method' :value='scope.row.inspectionMethod'/>
            </template>
          </el-table-column>
          <el-table-column label='质量检验规则ID' prop='qualityRuleId' align='center' width='120' />
          <el-table-column label='关键工序' prop='isKeyOperation' align='center' width='120'>
            <template #default='scope'>
              <dict-tag :options='mes_is_key_operation' :value='scope.row.isKeyOperation'/>
            </template>
          </el-table-column>
          <el-table-column label='下工序要求' prop='nextStepRequirement' align='center' width='120'>
            <template #default='scope'>
              <dict-tag :options='mes_next_step_requirement' :value='scope.row.nextStepRequirement'/>
            </template>
          </el-table-column>
          <el-table-column label='最后工序' prop='isFinalStep' align='center' width='120'>
            <template #default='scope'>
              <dict-tag :options='mes_is_final_step' :value='scope.row.isFinalStep'/>
            </template>
          </el-table-column>
          <el-table-column label='生成流转卡任务' prop='generatePrepareTask' align='center' width='120'>
            <template #default='scope'>
              <dict-tag :options='generate_prepare_task' :value='scope.row.generatePrepareTask'/>
            </template>
          </el-table-column>
          <el-table-column label='瓶颈工序' prop='bottleneckFlag' align='center' width='120'>
            <template #default='scope'>
              <dict-tag :options='mes_bottleneck_flag' :value='scope.row.bottleneckFlag'/>
            </template>
          </el-table-column>
          <el-table-column label='瓶颈设置' prop='bottleneckSetting' align='center' width='120'>
            <template #default='scope'>
              <dict-tag :options='mes_bottleneck_setting' :value='scope.row.bottleneckSetting'/>
            </template>
          </el-table-column>
          <el-table-column label='接续关系' prop='successorRelation' align='center' width='120'>
            <template #default='scope'>
              <dict-tag :options='mes_successor_relation' :value='scope.row.successorRelation'/>
            </template>
          </el-table-column>
          <el-table-column label='偏置时间(秒)' prop='offsetTime' align='center' width='120' />
          <el-table-column label='技术附件' prop='techAttachments' align='center' width='120' />
          <el-table-column label='质检员' prop='inspectors' align='center' width='120' />
          <el-table-column label='备注' prop='remark' align='center' width='120' />
          <el-table-column label='操作' align='center' width='120'>
            <template #default='scope'>
              <el-button
                size="small"
                type="text"
                icon="Edit"
                @click="handleEditRouteProcess(scope.row)"
              >修改</el-button>
              <el-button
                size="small"
                type="text"
                icon="Delete"
                @click="handleDeleteRouteProcess(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class='dialog-footer'>
          <el-button type='primary' @click='submitForm'>确 定</el-button>
          <el-button @click='cancel'>取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 工艺步骤编辑弹窗 -->
    <el-dialog :title='processDialog.title' v-model='processDialog.visible' width='800px' append-to-body>
      <el-form ref='processFormRef' :model='processForm' :rules='processRules' label-width='120px'>
        <el-form-item label='关联工序' prop='processId'>
          <el-select v-model='processForm.processId' placeholder='请选择关联工序' clearable>
            <el-option
              v-for='item in processList'
              :key='item.processId'
              :label='item.processName'
              :value='item.processId'
              :disabled='routeProcessList.some(i => i.processId === item.processId && i !== processForm)'
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='工艺路线顺序' prop='processOrder'>
          <el-input-number v-model='processForm.processOrder' :min='1' :controls='false' />
        </el-form-item>
        <el-form-item label='委外标识' prop='outsourcingFlag'>
          <el-radio-group v-model='processForm.outsourcingFlag'>
            <el-radio
              v-for='dict in mes_outsourcing_flag'
              :key='dict.value'
              :value='dict.value'
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='工序类型' prop='operationType'>
          <el-select v-model='processForm.operationType' placeholder='请选择工序类型'>
            <el-option
              v-for='dict in process_type'
              :key='dict.value'
              :label='dict.label'
              :value='dict.value'
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='是否需要上料' prop='needFeeding'>
          <el-radio-group v-model='processForm.needFeeding'>
            <el-radio
              v-for='dict in mes_need_feeding'
              :key='dict.value'
              :value='dict.value'
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='设备点检' prop='needEquipmentCheck'>
          <el-radio-group v-model='processForm.needEquipmentCheck'>
            <el-radio
              v-for='dict in mes_need_equipment_check'
              :key='dict.value'
              :value='dict.value'
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='实际产出率(%)' prop='actualYieldRate'>
          <el-input-number v-model='processForm.actualYieldRate' :min='0' :max='100' :controls='false' />
        </el-form-item>
        <el-form-item label='领料方式' prop='materialIssuance'>
          <el-select v-model='processForm.materialIssuance' placeholder='请选择领料方式'>
            <el-option
              v-for='dict in mes_material_method'
              :key='dict.value'
              :label='dict.label'
              :value='dict.value'
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='委外提前期(秒)' prop='outsourcingLeadTime'>
          <el-input-number v-model='processForm.outsourcingLeadTime' :min='0' :controls='false' />
        </el-form-item>
        <el-form-item label='准备时间(秒)' prop='setupTime'>
          <el-input-number v-model='processForm.setupTime' :min='0' :controls='false' />
        </el-form-item>
        <el-form-item label='加工时间(秒)' prop='processingTime'>
          <el-input-number v-model='processForm.processingTime' :min='0' :controls='false' />
        </el-form-item>
        <el-form-item label='拆卸时间(秒)' prop='teardownTime'>
          <el-input-number v-model='processForm.teardownTime' :min='0' :controls='false' />
        </el-form-item>
        <el-form-item label='生产节拍(秒/件)' prop='productionTakt'>
          <el-input-number v-model='processForm.productionTakt' :min='0' :controls='false' />
        </el-form-item>
        <el-form-item label='质检方式' prop='inspectionMethod'>
          <el-select v-model='processForm.inspectionMethod' placeholder='请选择质检方式'>
            <el-option
              v-for='dict in mes_inspection_method'
              :key='dict.value'
              :label='dict.label'
              :value='dict.value'
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='质量检验规则ID' prop='qualityRuleId'>
          <el-input v-model='processForm.qualityRuleId' placeholder='请输入质量检验规则ID' />
        </el-form-item>
        <el-form-item label='关键工序' prop='isKeyOperation'>
          <el-radio-group v-model='processForm.isKeyOperation'>
            <el-radio
              v-for='dict in mes_is_key_operation'
              :key='dict.value'
              :value='dict.value'
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='下工序要求' prop='nextStepRequirement'>
          <el-radio-group v-model='processForm.nextStepRequirement'>
            <el-radio
              v-for='dict in mes_next_step_requirement'
              :key='dict.value'
              :value='dict.value'
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='最后工序' prop='isFinalStep'>
          <el-radio-group v-model='processForm.isFinalStep'>
            <el-radio
              v-for='dict in mes_is_final_step'
              :key='dict.value'
              :value='dict.value'
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='生成流转卡任务' prop='generatePrepareTask'>
          <el-radio-group v-model='processForm.generatePrepareTask'>
            <el-radio
              v-for='dict in generate_prepare_task'
              :key='dict.value'
              :value='dict.value'
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='瓶颈工序' prop='bottleneckFlag'>
          <el-radio-group v-model='processForm.bottleneckFlag'>
            <el-radio
              v-for='dict in mes_bottleneck_flag'
              :key='dict.value'
              :value='dict.value'
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='瓶颈设置' prop='bottleneckSetting'>
          <el-radio-group v-model='processForm.bottleneckSetting'>
            <el-radio
              v-for='dict in mes_bottleneck_setting'
              :key='dict.value'
              :value='dict.value'
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='接续关系' prop='successorRelation'>
          <el-radio-group v-model='processForm.successorRelation'>
            <el-radio
              v-for='dict in mes_successor_relation'
              :key='dict.value'
              :value='dict.value'
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='偏置时间(秒)' prop='offsetTime'>
          <el-input-number v-model='processForm.offsetTime' :min='0' :controls='false' />
        </el-form-item>
        <el-form-item label='技术附件' prop='techAttachments'>
          <el-input v-model='processForm.techAttachments' placeholder='请输入技术附件' />
        </el-form-item>
        <el-form-item label='质检员' prop='inspectors'>
          <el-input v-model='processForm.inspectors' placeholder='请输入质检员' />
        </el-form-item>
        <el-form-item label='备注' prop='remark'>
          <el-input v-model='processForm.remark' placeholder='请输入备注' />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class='dialog-footer'>
          <el-button type='primary' @click='submitProcessDialog'>确 定</el-button>
          <el-button @click='cancelProcessDialog'>取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name='BaseRoute' lang='ts'>
import { listBaseRoute, getBaseRoute, delBaseRoute, addBaseRoute, updateBaseRoute } from '@/api/mes/baseRoute';
import { BaseRouteVO, BaseRouteQuery, BaseRouteForm, ProdBaseRouteProcess, ProdBaseRouteMaterial } from '@/api/mes/baseRoute/types';
import { getMaterialList } from '@/api/wms/linkage';
import MaterialSelect from '@/views/mes/baseMaterialInfo/addMaterial.vue';
import { listBaseProcessInfo } from '@/api/mes/baseProcessInfo';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { mes_route_active_flag, mes_process_production_type, mes_need_first_inspect, mes_route_type, mes_print_flow_card, active_flag, mes_outsourcing_flag, process_type, mes_need_feeding, mes_need_equipment_check, mes_material_method, mes_inspection_method, mes_is_key_operation, mes_next_step_requirement, mes_is_final_step, generate_prepare_task, mes_bottleneck_flag, mes_bottleneck_setting, mes_successor_relation } = toRefs<any>(proxy?.useDict(
  'mes_route_active_flag',
  'mes_process_production_type',
  'mes_need_first_inspect',
  'mes_route_type',
  'mes_print_flow_card',
  'active_flag',
  'mes_outsourcing_flag',
  'process_type',
  'mes_need_feeding',
  'mes_need_equipment_check',
  'mes_material_method',
  'mes_inspection_method',
  'mes_is_key_operation',
  'mes_next_step_requirement',
  'mes_is_final_step',
  'generate_prepare_task',
  'mes_bottleneck_flag',
  'mes_bottleneck_setting',
  'mes_successor_relation'
));

const baseRouteList = ref<BaseRouteVO[]>([]);
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 baseRouteFormRef = ref<ElFormInstance>();

// 关联物料相关
const materialOpen = ref(false);
const prodBaseRouteMaterialList = ref<ProdBaseRouteMaterial[]>([]);
const checkedRouteMaterial = ref<ProdBaseRouteMaterial[]>([]);
const materialList = ref<any[]>([]);

// 关联工艺步骤相关
const processOpen = ref(false);
const routeProcessList = ref<ProdBaseRouteProcess[]>([]);
const checkedRouteProcess = ref<ProdBaseRouteProcess[]>([]);
const processList = ref<any[]>([]);

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

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `工艺路线ID`, visible: false },
  { key: 1, label: `租户编号`, visible: false },
  { key: 2, label: `工艺路线名称`, visible: true },
  { key: 3, label: `工艺路线说明`, visible: true },
  { key: 4, label: `状态`, visible: true },
  { key: 5, label: `备注`, visible: true },
  { key: 6, label: `创建部门`, visible: false },
  { key: 7, label: `创建人`, visible: false },
  { key: 8, label: `创建时间`, visible: false },
  { key: 9, label: `更新人`, visible: false },
  { key: 10, label: `更新时间`, visible: false },
  { key: 11, label: `工艺路线版本`, visible: true },
  { key: 12, label: `生产类型`, visible: true },
  { key: 13, label: `路线类型`, visible: true },
  { key: 14, label: `审核原因`, visible: false },
  { key: 15, label: `审核人`, visible: false },
  { key: 16, label: `审核时间`, visible: false },
  { key: 17, label: `首件检验`, visible: true },
  { key: 18, label: `打印流转卡`, visible: true },
  { key: 19, label: `批次量`, visible: true }
]);

const initFormData: BaseRouteForm = {
  routeId: undefined,
  routeName: undefined,
  routeDesc: undefined,
  activeFlag: '1',
  remark: undefined,
  routeVersion: undefined,
  productionType: '1',
  routeType: '1',
  auditReason: undefined,
  approveBy: undefined,
  approveTime: undefined,
  needFirstInspect: '0',
  printFlowCard: '0',
  batchSize: 0,
  routeProcessBoList: [],//工艺步骤
  // prodBaseRouteMaterialList 不在BaseRouteForm类型定义中，但后端需要，TS忽略类型检查
  // @ts-ignore
  prodBaseRouteMaterialList: []
};
const data = reactive<PageData<BaseRouteForm, BaseRouteQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    routeId: undefined,
    routeName: undefined,
    routeDesc: undefined,
    activeFlag: undefined,
    routeVersion: undefined,
    productionType: undefined,
    routeType: undefined,
    auditReason: undefined,
    approveBy: undefined,
    approveTime: undefined,
    needFirstInspect: undefined,
    printFlowCard: undefined,
    batchSize: undefined,
    params: {}
  },
  rules: {
    routeName: [
      { required: true, message: '工艺路线名称不能为空', trigger: 'blur' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询工艺路线列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBaseRoute(queryParams.value);
  baseRouteList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  materialOpen.value = false;
  processOpen.value = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  baseRouteFormRef.value?.resetFields();
  prodBaseRouteMaterialList.value = [];
  routeProcessList.value = [];
};

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加工艺路线';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: BaseRouteVO) => {
  reset();
  const _routeId = row?.routeId || ids.value[0];
  const res = await getBaseRoute(_routeId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改工艺路线';
};

/** 提交按钮 */
const submitForm = () => {
  baseRouteFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // 校验物料是否已选择
      const hasEmptyMaterial = prodBaseRouteMaterialList.value.some(item => !item.materialId || item.materialId === '');
      if (hasEmptyMaterial) {
        proxy?.$modal.msgError('请选择所有关联物料');
        return;
      }

      buttonLoading.value = true;
      form.value.prodBaseRouteMaterialList = prodBaseRouteMaterialList.value;
      form.value.routeProcessList = routeProcessList.value;
      if (form.value.routeId) {
        await updateBaseRoute(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addBaseRoute(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      materialOpen.value = false;
      processOpen.value = false;
      routeProcessList.value = [];
      form.value.prodBaseRouteMaterialList = [];
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: BaseRouteVO) => {
  const _routeIds = row?.routeId || ids.value;
  await proxy?.$modal.confirm('是否确认删除工艺路线编号为"' + _routeIds + '"的数据项？').finally(() => loading.value = false);
  await delBaseRoute(_routeIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

/** 维护工艺路线关联物料 */
const routeMaterialUpdate = async (row: BaseRouteVO) => {
  reset();
  const _routeId = row?.routeId || ids.value[0];
  const routeRes = await getBaseRoute(_routeId);
  form.value = routeRes.data;
  prodBaseRouteMaterialList.value = routeRes.data.prodBaseRouteMaterialList || [];
  materialOpen.value = true;
  dialog.title = '维护工艺路线关联物料';
};

/** 修改rowRouteMaterialIndex方法，返回类名字符串 */
const rowRouteMaterialIndex = ({ row, rowIndex }: { row: any; rowIndex: number }): string => {
  row.index = rowIndex + 1;
  return '';
};

/** 工艺路线关联物料添加按钮操作 */
const handleAddRouteMaterial = () => {
  prodBaseRouteMaterialList.value.push({
    materialId: '',
    activeFlag: '1',
    remark: '',
  });
};

/** 工艺路线关联物料删除按钮操作 */
const handleDeleteRouteMaterial = () => {
  if (checkedRouteMaterial.value.length === 0) {
    proxy?.$modal.msgError('请先选择要删除的工艺路线关联物料数据');
  } else {
    prodBaseRouteMaterialList.value = prodBaseRouteMaterialList.value.filter(
      item => !checkedRouteMaterial.value.some(checked => checked.materialId === item.materialId)
    );
    checkedRouteMaterial.value = [];
  }
};

/** 复选框选中数据 */
const handleRouteMaterialSelectionChange = (selection: ProdBaseRouteMaterial[]) => {
  checkedRouteMaterial.value = selection;
};

const materialSelectRef = ref();
const materialDialogOpen = ref(false);
const currentMaterialRowIndex = ref(-1);

const openMaterialDialog = (rowIndex) => {
  currentMaterialRowIndex.value = rowIndex;
  materialDialogOpen.value = true;
};

const handleMaterialSelection = () => {
  const selectedRow = materialSelectRef.value.tableRef.store.states.currentRow.value;
  if (selectedRow && currentMaterialRowIndex.value !== -1) {
    prodBaseRouteMaterialList.value[currentMaterialRowIndex.value].materialId = selectedRow.materialId;
    prodBaseRouteMaterialList.value[currentMaterialRowIndex.value].materialName = selectedRow.materialName;
  }
  materialDialogOpen.value = false;
};

// 获取工序列表
const getProcessList = async () => {
  const res = await listBaseProcessInfo(null);
  processList.value = res.rows;
};

// 打开关联工艺步骤对话框
const routeProcessUpdate = async (row: BaseRouteVO) => {
  reset();
  const _routeId = row?.routeId || ids.value[0];
  const routeRes = await getBaseRoute(_routeId);
  form.value = routeRes.data;
  // 处理工艺步骤数据，将null值转换为默认值
  routeProcessList.value = routeRes.data.routeProcessList || [];
  processOpen.value = true;
  dialog.title = '维护工艺路线关联工艺步骤';
};

// 修改rowRouteProcessIndex方法
const rowRouteProcessIndex = ({ row, rowIndex }: { row: any; rowIndex: number }): string => {
  row.index = rowIndex + 1;
  return '';
};

// 在script setup部分添加以下代码
const processDialog = reactive({
  visible: false,
  title: '',
  isEdit: false
});

const processFormRef = ref<ElFormInstance>();
const processForm = ref<any>({
  processId: '',
  processOrder: 1,
  outsourcingFlag: '0',
  operationType: '1',
  needFeeding: '0',
  needEquipmentCheck: '0',
  actualYieldRate: 100,
  materialIssuance: '1',
  outsourcingLeadTime: 0,
  setupTime: 0,
  processingTime: 0,
  teardownTime: 0,
  productionTakt: 0,
  inspectionMethod: '1',
  qualityRuleId: '',
  isKeyOperation: '0',
  nextStepRequirement: '0',
  isFinalStep: '0',
  generatePrepareTask: '0',
  bottleneckFlag: '0',
  bottleneckSetting: '0',
  successorRelation: '0',
  offsetTime: 0,
  techAttachments: '',
  inspectors: '',
  remark: ''
});

const processRules = {
  processId: [
    { required: true, message: '请选择关联工序', trigger: 'change' }
  ],
  processOrder: [
    { required: true, message: '请输入工艺路线顺序', trigger: 'blur' }
  ]
};

// 获取工序名称
const getProcessName = (processId: string) => {
  const process = processList.value.find(item => item.processId === processId);
  return process ? process.processName : '';
};

// 添加工艺步骤
const handleAddRouteProcess = () => {
  processDialog.isEdit = false;
  processDialog.title = '添加工艺步骤';
  processForm.value = {
    processId: '',
    processOrder: routeProcessList.value.length + 1,
    outsourcingFlag: '0',
    operationType: '1',
    needFeeding: '0',
    needEquipmentCheck: '0',
    actualYieldRate: 100,
    materialIssuance: '1',
    outsourcingLeadTime: 0,
    setupTime: 0,
    processingTime: 0,
    teardownTime: 0,
    productionTakt: 0,
    inspectionMethod: '1',
    qualityRuleId: '',
    isKeyOperation: '0',
    nextStepRequirement: '0',
    isFinalStep: '0',
    generatePrepareTask: '0',
    bottleneckFlag: '0',
    bottleneckSetting: '0',
    successorRelation: '0',
    offsetTime: 0,
    techAttachments: '',
    inspectors: '',
    remark: ''
  };
  processDialog.visible = true;
};

// 修改工艺步骤
const handleEditRouteProcess = (row: any) => {
  processDialog.isEdit = true;
  processDialog.title = '修改工艺步骤';
  processForm.value = { ...row };
  processDialog.visible = true;
};

// 删除工艺步骤
const handleDeleteRouteProcess = (row: any) => {
  proxy?.$modal.confirm('是否确认删除该工艺步骤？').then(() => {
    const index = routeProcessList.value.findIndex(item => item === row);
    if (index !== -1) {
      routeProcessList.value.splice(index, 1);
    }
  });
};

// 提交工艺步骤弹窗
const submitProcessDialog = () => {
  processFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (processDialog.isEdit) {
        const index = routeProcessList.value.findIndex(item => item === processForm.value);
        if (index !== -1) {
          routeProcessList.value[index] = { ...processForm.value };
        }
      } else {
        routeProcessList.value.push({ ...processForm.value });
      }
      processDialog.visible = false;
    }
  });
};

// 取消工艺步骤弹窗
const cancelProcessDialog = () => {
  processDialog.visible = false;
  processFormRef.value?.resetFields();
};

onMounted(() => {
  getList();
  getProcessList();
});
</script>
