<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="工艺路线描述" prop="routeDescription">
        <el-input
          v-model="queryParams.routeDescription"
          placeholder="请输入工艺路线描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料编码" prop="materialCode">
        <el-input
          v-model="queryParams.materialCode"
          placeholder="请输入物料编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input
          v-model="queryParams.unit"
          placeholder="请输入单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工序号" prop="processNo">
        <el-input
          v-model="queryParams.processNo"
          placeholder="请输入工序号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工作中心" prop="workCenter">
        <el-input
          v-model="queryParams.workCenter"
          placeholder="请输入工作中心"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工序名称" prop="processName">
        <el-input
          v-model="queryParams.processName"
          placeholder="请输入工序名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="原材料编码" prop="rawMaterialCode">
        <el-input
          v-model="queryParams.rawMaterialCode"
          placeholder="请输入原材料编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="原材料名称" prop="rawMaterialName">
        <el-input
          v-model="queryParams.rawMaterialName"
          placeholder="请输入原材料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="金碟重量" prop="discWeight">
        <el-input
          v-model="queryParams.discWeight"
          placeholder="请输入金碟重量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="金碟用量" prop="discUsage">
        <el-input
          v-model="queryParams.discUsage"
          placeholder="请输入金碟用量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工序说明" prop="processDescription">
        <el-input
          v-model="queryParams.processDescription"
          placeholder="请输入工序说明"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form :model="queryParams">
        <el-form-item label="项目令号" prop="routeDescription">
          <el-select v-model="queryParams.routeDescription" filterable remote :remote-method="handleQuery1"
            placeholder="请输入令号" clearable :loading="loading">
            <el-option v-for="item in projectCodes" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!--      <el-form-item label="工序控制" prop="processControl">
              <el-input v-model="queryParams.processControl" placeholder="请输入工序控制" clearable
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="活动时长" prop="activityDuration">
              <el-input v-model="queryParams.activityDuration" placeholder="请输入活动时长" clearable
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="活动单位" prop="activityUnit">
              <el-input v-model="queryParams.activityUnit" placeholder="请输入活动单位" clearable
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>-->

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:route:add']">新增
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:route:edit']">修改
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:route:remove']">删除
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:route:export']">导出
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['system:details:import']">导入工艺
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="pushRouteBom"
          v-hasPermi="['system:details:import']">推送工艺
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="updateProcessPlan"
          v-hasPermi="['system:details:import']">更新计划时间
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="generatePDFs"
          v-hasPermi="['system:details:import']">生成PDF
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-form :inline="true" :model="form" ref="ruleForm" size="mini" :rules="rules">
      <el-table v-if="showtable" v-loading="loading" row-key="id" ref="tree" v-drag:[config]="form.routeList"
        :tree-props="{ children: 'children' }" :data="form.routeList" stripe :row-class-name="tableRowClassName"
        :cell-style="columnStyle" border max-height="680px" @cell-click="cellhand" :default-expand-all="true"
        @selection-change="handleSelectionChange">

        <el-table-column type="selection" width="55" align="center" />
        <!--     <el-table-column label="主键ID" align="center" prop="id" v-if="true"/>-->
        <el-table-column label="操作" align="center">
          <template slot-scope="props">
            <!-- <el-button type="text" icon="el-icon-check" v-if="scope.row.id < 0" @click="onSaveChild()" /> -->
            <!-- <fromed v-if="props.row.parentId" /> -->
            <!-- {{props.row.materialCode}} -->
            <el-button v-if="props.row.parentId" size="mini" class="handle" icon="el-icon el-icon-rank" />
          </template>
        </el-table-column>

        <!-- <el-table-column label="项目令号" align="center">
          <template slot-scope="scope">
            <router-link :to="'/route1/' + scope.row.routeDescription" type="primary" :underline="false">{{
      scope.row.routeDescription }}</router-link>
          </template>
        </el-table-column> -->
        <el-table-column label="物料编码" width="100" align="center" prop="materialCode" />
        <el-table-column label="名称" width="100" align="center" prop="materialName" />
        <el-table-column label="材质" width="80" align="center" prop="material" />
        <el-table-column label="单重" width="60" align="center" prop="discWeight" />
        <!--
      <el-table-column label="材料BOM物料编码" width="220"align="center" prop="rawMaterialCode" />
      <el-table-column label="材料BOM物料名称"width="220" align="center" prop="rawMaterialName" />
      <el-table-column label="用量"width="60"align="center" prop="discUsage" />
      <el-table-column label="单位"width="60" align="center" prop="bomUnit" />-->
        <el-table-column label="工序号" width="60" align="center" prop="processNo" />
        <el-table-column label="工作中心" width="150" align="center">
          <template slot-scope="scope">
            <el-form-item v-if="scope.row.id < 0" :prop="'routeList.' + scope.$index + '.workCenter'">
              <el-select v-model="scope.row.workCenter" placeholder="工作中心" clearable @keyup.enter.native="handleQuery2">
                <el-option label="机一工段" value="机一工段"></el-option>
                <el-option label="机二工段" value="机二工段"></el-option>
                <el-option label="机三工段" value="机三工段"></el-option>
                <el-option label="装一工段" value="装一工段"></el-option>
                <el-option label="装二工段" value="装二工段"></el-option>
                <el-option label="铆焊工段" value="铆焊工段"></el-option>
                <el-option label="电钳工段" value="电钳工段"></el-option>
                <el-option label="委外中心" value="委外中心"></el-option>
              </el-select>
            </el-form-item>
            <span v-else>{{ scope.row.workCenter }}</span>
          </template>
        </el-table-column>

        <el-table-column label="工序名称" width="150" align="center">
          <template slot-scope="scope">
            <el-form-item v-if="scope.row.id < 0" :prop="'routeList.' + scope.$index + '.processName'">
              <el-select v-model="scope.row.processName" filterable remote :remote-method="handleQuery3"
                placeholder="请输入工序名称" clearable :loading="loading" @change="handleProcessNameChange(scope)">
                <el-option v-for="item in processName" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <span v-else>{{ scope.row.processName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="工序说明" width="300" align="center">
          <template slot-scope="scope">
            <el-form-item v-if="scope.row.id < 0" :prop="'routeList.' + scope.$index + '.processDescription'">
              <el-input v-model="scope.row.processDescription"></el-input>
            </el-form-item>
            <span v-else>{{ scope.row.processDescription }}</span>
          </template>
        </el-table-column>

        <el-table-column label="工序控制" width="220" align="center">
          <template slot-scope="scope">
            <el-form-item v-if="scope.row.id < 0" :prop="'routeList.' + scope.$index + '.processControl'">
              <el-select v-model="scope.row.processControl" placeholder="工序控制" clearable @keyup.enter.native="handleQuery2">
                <el-option label="汇报+免检" value="汇报+免检"></el-option>
                <el-option label="委外+质量" value="委外+质量"></el-option>
                <el-option label="汇报+质量" value="汇报+质量"></el-option>

              </el-select>
            </el-form-item>
            <span v-else>{{ scope.row.processControl }}</span>
          </template>
        </el-table-column>

        <el-table-column label="活动时长" align="center" prop="activityDuration">
          <template slot-scope="scope">
            <el-form-item v-if="scope.row.id < 0" :prop="'routeList.' + scope.$index + '.activityDuration'">
              <el-input v-model="scope.row.activityDuration"></el-input>
            </el-form-item>
            <span v-else>{{ scope.row.activityDuration }}</span>
          </template>
        </el-table-column>

        <el-table-column label="活动单位" align="center" prop="activityUnit" />
        <el-table-column label="序开始时间" align="center" prop="xuStartTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.xuStartTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="序结束时间" align="center" prop="xuEndTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.xuEndTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" prop="bomUnit" />
        <el-table-column label="单台数量" align="center" prop="unitQuantity" />
        <el-table-column label="本批数量" align="center" prop="batchQuantity" />
        <el-table-column label="首批数量" align="center" prop="firstBatchQuantity" />
        <el-table-column label="计划开始时间" align="center" prop="planStartTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.planStartTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划结束时间" align="center" prop="planEndTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.planEndTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>

        <el-table-column class="maxWidth" label="操作" width="220" fixed="right" align="center"
          class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button class="btn" size="mini" @click="onAddChild(scope)" v-if="!scope.row.parentId">
              添加工艺
            </el-button>
            <el-button class="btn" size="mini" type="success" @click="onSave(scope)"
              v-if="!scope.row.parentId && showParentSaveBtn === scope.row.id">
              保存工艺
            </el-button>
            <el-button class="btn" size="mini" type="danger" @click="onDelete(scope)" v-if="scope.row.id < 0">
              删除工艺
            </el-button>
            <el-button class="btn" size="mini" type="primary" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:route:edit']" v-if="scope.row.id > 0 && scope.row.parentId">修改
            </el-button>
            <el-button class="btn" size="mini" type="danger" @click="handleDelete(scope.row)"
              v-hasPermi="['system:route:remove']" v-if="scope.row.id > 0">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改工艺路线对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工艺路线描述" prop="routeDescription">
          <el-input v-model="form.routeDescription" placeholder="请输入工艺路线描述" />
        </el-form-item>
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="单位" prop="bomUnit">
          <el-input v-model="form.bomUnit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="工序号" prop="processNo">
          <el-input v-model="form.processNo" placeholder="请输入工序号" />
        </el-form-item>
        <el-form-item label="工作中心" prop="workCenter">
          <el-input v-model="form.workCenter" placeholder="请输入工作中心" />
        </el-form-item>
        <el-form-item label="工序名称" prop="processName">
          <el-input v-model="form.processName" placeholder="请输入工序名称" />
        </el-form-item>
        <el-form-item label="原材料编码" prop="rawMaterialCode">
          <el-input v-model="form.rawMaterialCode" placeholder="请输入原材料编码" />
        </el-form-item>
        <el-form-item label="原材料名称" prop="rawMaterialName">
          <el-input v-model="form.rawMaterialName" placeholder="请输入原材料名称" />
        </el-form-item>
        <el-form-item label="金碟重量" prop="discWeight">
          <el-input v-model="form.discWeight" placeholder="请输入金碟重量" />
        </el-form-item>
        <el-form-item label="金碟用量" prop="discUsage">
          <el-input v-model="form.discUsage" placeholder="请输入金碟用量" />
        </el-form-item>
        <el-form-item label="工序说明" prop="processDescription">
          <el-input v-model="form.processDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="工序控制" prop="processControl">
          <el-input v-model="form.processControl" placeholder="请输入工序控制" />
        </el-form-item>
        <el-form-item label="活动时长" prop="activityDuration">
          <el-input v-model="form.activityDuration" placeholder="请输入活动时长" />
        </el-form-item>
        <el-form-item label="活动单位" prop="activityUnit">
          <el-input v-model="form.activityUnit" placeholder="请输入活动单位" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的物料数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!--          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                             @click="importTemplate">下载模板
                    </el-link>-->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer title="添加BOM" :visible.sync="BOMpop" :before-close="bomClose" :size="850">
      <div style="padding: 20px;">
        <el-table :data="bomList" stripe max-height="400px" border>
          <el-table-column label="生产令号" width="100" align="center" prop="projectNumber" />
          <el-table-column label="物料编码" width="150" align="center" prop="materialCode" />
          <el-table-column label="物料名称" width="150" align="center" prop="materialName" />
          <el-table-column label="材质" width="70" align="center" prop="materialType" />
          <el-table-column label="用量" width="88" align="center" prop="quantity" />
          <el-table-column label="单位" width="88" align="center" prop="unit" />
          <el-table-column class="maxWidth" label="操作" width="150" fixed="right" align="center"
            class-name="small-padding fixed-width" />
        </el-table>
        <Bomfrom v-if="BOMpop" style="padding-top: 20px;" />
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listRoute,
  getRoute,
  delRoute,
  addRoute,
  updateRoute,
  getDistinctProjectCodes,
  updateProcessPlan, generatePDFs
} from "@/api/system/route";
import upload from "svg-sprite-loader/examples/custom-runtime-generator/build/main";
import { getToken } from "../../../utils/auth";
import Fromed from './fromed'
import Bomfrom from './bomfrom'
import { getProcessInfoList, pushRouteBom, onSave } from "../../../api/system/route";

export default {
  name: "",
  components: {
    Fromed,
    Bomfrom
  },
  props: {
    showdel: {
      type: Boolean,
      default: true
    },
    obj: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      showtable: true,
      expand: true,
      BOMpop: false,
      bomList: [],
      //expandRowKeys:[],
      omdelData: '',
      routeDescription: '', // 用于存储 productionOrderNo 的变量
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 显示父级的保存工艺按钮
      showParentSaveBtn: null,
      // 总条数
      total: 0,
      form: {
        // 工艺路线表格数据
        routeList: [],
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 500,
        routeDescription: [],
        materialCode: undefined,
        materialName: undefined,
        bomUnit: undefined,
        processNo: undefined,
        workCenter: undefined,
        processName: undefined,
        rawMaterialCode: undefined,
        rawMaterialName: undefined,
        discWeight: undefined,
        discUsage: undefined,
        processDescription: undefined,
        processControl: undefined,
        activityDuration: undefined,
        activityUnit: undefined,
      },
      // 对应关系映射：工序名称 -> 工作中心
      processToWorkCenterMap: {
        // 铆焊工段
        '数控火焰下料': '铆焊工段',
        '数控激光下料': '铆焊工段',
        '数控切管下料': '铆焊工段',
        '水虎鱼剪折冲': '铆焊工段',
        '锯床下料': '铆焊工段',
        '抛丸': '铆焊工段',
        '组焊': '铆焊工段',
        '普车': '机一工段',
        '普铣': '机一工段',
        '龙门铣': '机一工段',
        '立磨': '机一工段',
        '平磨': '机一工段',
        '钻床': '机一工段',
        '数车': '机二工段',
        '数控外圆磨': '机二工段',
        '走芯机': '机二工段',
        '双主轴': '机二工段',
        '车铣复合': '机二工段',
        '线切割': '机二工段',
        '卧加63': '机三工段',
        '5032龙门': '机三工段',
        '3018龙门': '机三工段',
        '2013龙门': '机三工段',
        '立加1370': '机三工段',
        '立加1177': '机三工段',
        '立加850': '机三工段',
        '数插5035': '机三工段',
        '装配1': '装一工段',
        '装配2': '装二工段',
        '电装': '电钳工段',
        '正火': '委外中心',
        '回火': '委外中心',
        '调质': '委外中心',
        '真空调质': '委外中心',
        '整体淬火': '委外中心',
        '表面淬火': '委外中心',
        '真空淬火': '委外中心',
        '渗碳淬火': '委外中心',
        '渗氮': '委外中心',
        '碳氮共渗': '委外中心',
        '制齿': '委外中心',
        '电火花': '委外中心',
        '插床': '委外中心',
        '按图订制': '委外中心',
        '磷化处理': '委外中心',
        '发蓝处理': '委外中心',
        'QPQ处理': '委外中心',
        '镀锌': '委外中心',
        '镀硬铬': '委外中心',
        '镀锌镍合金': '委外中心',
        '阳极氧化': '委外中心',
        '达克罗': '委外中心',
        '喷漆': '委外中心',
        '喷塑': '委外中心',
        '喷砂': '委外中心',
        '喷砂底漆': '委外中心'
      },
      // 表单参数

      projectCodes: [],        // 存储查询到的项目令号
      processName: [],
      activeRows: [],          // 转换为列表的数据
      config: {
        elementSeletor: "tbody",  //元素选择
        filter: ".filtered",  // 过滤
        onEnd: (event, oldValue, newValue) => {
          console.log("源数据", oldValue);
          console.log("改变后的数据", newValue);
        },
      },
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/route/importData"
      },
      id: 0,//动态增加表格列的ID
      // 表单校验
      rules: {
        id: [
          { required: true, message: "主键ID不能为空", trigger: "blur" }
        ],
        routeDescription: [
          { required: true, message: "工艺路线描述不能为空", trigger: "blur" }
        ],
        materialCode: [
          { required: true, message: "物料编码不能为空", trigger: "blur" }
        ],
        materialName: [
          { required: true, message: "物料名称不能为空", trigger: "blur" }
        ],
        bomUnit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
        processNo: [
          { required: true, message: "工序号不能为空", trigger: "blur" }
        ],
        workCenter: [
          { required: true, message: "工作中心不能为空", trigger: "blur" }
        ],
        processName: [
          { required: true, message: "工序名称不能为空", trigger: "blur" }
        ],
        rawMaterialCode: [
          { required: true, message: "原材料编码不能为空", trigger: "blur" }
        ],
        rawMaterialName: [
          { required: true, message: "原材料名称不能为空", trigger: "blur" }
        ],
        discWeight: [
          { required: true, message: "金碟重量不能为空", trigger: "blur" }
        ],
        discUsage: [
          { required: true, message: "金碟用量不能为空", trigger: "blur" }
        ],
        processDescription: [
          { required: true, message: "工序说明不能为空", trigger: "blur" }
        ],
        processControl: [
          { required: true, message: "工序控制不能为空", trigger: "blur" }
        ],
        activityDuration: [
          { required: true, message: "活动时长不能为空", trigger: "blur" }
        ],
        activityUnit: [
          { required: true, message: "活动单位不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建者不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    const productionOrderNo = this.$route.query.productionOrderNo;
    if (productionOrderNo) {
      this.queryParams.routeDescription = productionOrderNo;
    } else {
    }
    this.getList();
  },
  watch: {
    '$route.query.productionOrderNo': function (newVal) {
      // 当路由参数 productionOrderNo 变化时，重新获取
      this.setTotalWeight();
      this.getList();
    }
  },
  mounted() {
    this.rowDrop();
  },
  methods: {
    handleProcessNameChange(scope) {
      console.log(scope)
      const selectedProcessName = scope.row.processName;
      console.log(selectedProcessName)
      if (this.processToWorkCenterMap[selectedProcessName]) {
        scope.row.workCenter = this.processToWorkCenterMap[selectedProcessName];
      } else {
        scope.row.workCenter = '';
      }
    },

    handleQuery3(query) {
      if (query === '') {
        this.processName = [];
        return;
      }
      // 开始加载
      this.loading = true;
      // 调用后端接口获取匹配的项目令号
      getProcessInfoList(query).then((response) => {
        // 加载完成
        this.loading = false;
        this.processName = response;

      }).catch(() => {
        this.loading = false; // 加载失败
        this.processName = []; // 如果请求失败，清空选项
      });
    },
    // 控制表格可移动部分
    tableRowClassName({ row, rowIndex }) {
      // 过滤掉父节点
      if (!row.parentId) {
        return "filtered";
      }
      return "";
    },
    // 添加子集
    onAddChild(props) {
      // 是否为父级,返回父级所在下标
      var index = this.form.routeList.findIndex(item => item.id === props.row.id);
      // -1为未检索到，不为父级
      if (index === -1) {
        alert("刷新试试,为检索到此目录,可能不存在")
        return;
      }

      var routeList = this.form.routeList[index].children;
      var route = routeList.sort(function (a, b) {
        return a.processNo - b.processNo
      })[routeList.length - 1];
      var processNo = !route ? 0 : route.processNo + 10;
      routeList.push({ id: --this.id, parentId: props.row.id, processNo: processNo, children: null });
      this.showParentSaveBtn = props.row.id;
    },
    // 保存子集
    onSave(props) {
      // 找到需要保存的新加子集
      var list = this.form.routeList.find(item => item.id === props.row.id);
      var newChildrenList = list.children.filter(item => item.id < 0).map(v => ({
        id: v.parentId,
        routeDescription: list.routeDescription,
        materialCode: list.materialCode,
        materialName: list.materialName,
        material: list.material,
        discWeight: list.discWeight,
        processNo: v.processNo,
        workCenter: v.workCenter,
        processControl: v.processControl,
        processDescription: v.processDescription,
        processName: v.processName,
        activityDuration: v.activityDuration
      }))

      // 调用后端保存
      onSave(newChildrenList)
        .then((response) => {
          Messages.success('工艺路线保存成功');
          // 刷新表格
          this.getList();
        })
        .catch((error) => {
          Messages.error('工艺路线保存失败');
        });
    },
    // 删除子集
    onDelete(props) {
      // 获取父级的所在下标
      var index = this.form.routeList.findIndex(item => item.id === props.row.parentId);
      // 获取子集的所在下标
      var childrenIndex = this.form.routeList[index].children.findIndex(item => item.id === props.row.id);
      // 找到子集并删除
      this.form.routeList[index].children.splice(childrenIndex, 1);
      // 修改其它子集的工序号
      for (let i = 0; i < this.form.routeList[index].children.length; i++) {
        // 修改子集中工序号
        this.form.routeList[index].children[i].processNo = (i + 1) * 10;
      }
    },
    cellhand(row, column) {
      if (/单重|材料BOM物料编码|材料BOM物料名称|用量/.test(column.label)) {
        this.BOMpop = true
      }
    },
    bomClose() {
      this.BOMpop = false
    },
    shouhide() {
      this.showtable = false
      setTimeout(() => {
        this.showtable = true
        this.expand = !this.expand
      }, 0);

    },
    setTotalWeight() {
      const totalWeight = this.$route.query.productionOrderNo;
      if (totalWeight) {
        this.queryParams.totalWeight = totalWeight;
      }
    },

    /** 查询工艺路线列表 */
    getList() {
      this.loading = true;
      listRoute(this.queryParams).then(response => {
        this.form.routeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        routeDescription: undefined,
        materialCode: undefined,
        materialName: undefined,
        bomUnit: undefined,
        processNo: undefined,
        workCenter: undefined,
        processName: undefined,
        rawMaterialCode: undefined,
        rawMaterialName: undefined,
        discWeight: undefined,
        discUsage: undefined,
        processDescription: undefined,
        processControl: undefined,
        activityDuration: undefined,
        activityUnit: undefined,
        createBy: undefined,
        updateBy: undefined,
        createTime: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "工艺导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/route/importTemplate', {}, `route_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>"
        + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleQuery1(query) {
      if (query === '') {
        this.projectCodes = []; // 如果没有输入任何关键字，清空选项
        return;
      }
      // 开始加载
      this.loading = true;
      // 调用后端接口获取匹配的项目令号
      getDistinctProjectCodes(query).then((response) => {
        // 加载完成
        this.loading = false;
        this.projectCodes = response;

      }).catch(() => {
        this.loading = false; // 加载失败
        this.projectCodes = []; // 如果请求失败，清空选项
      });
    },
    //获取工序列表


    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工艺路线";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getRoute(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改工艺路线";
      });
    },


    /**推送工艺 */
    pushRouteBom(row) {
      // 显示加载状态
      this.loading = true;
      // 调用 reset 方法，重置表单或状态
      this.reset();
      // 获取生产订单号
      const rooteProdet = this.$route.query.productionOrderNo;
      console.log(rooteProdet);

      // 调用封装好的 API 方法
      pushRouteBom(rooteProdet)
        .then(response => {
          // 假设后端返回的数据可以直接赋值给表单
          this.form = response;
          // 弹出成功消息
          this.$modal.msgSuccess("推送成功");
          // 调用方法更新列表
          this.getList();
        })
        .catch(error => {
          // 处理错误，弹出错误提示
          this.$modal.msgError("推送失败，请重试！");
          console.error('推送工艺失败:', error);
        })
        .finally(() => {
          // 隐藏加载状态
          this.loading = false;
        });
    },
    /** 更新计划时间*/
    updateProcessPlan(row) {
      // 显示加载状态
      this.loading = true;
      // 调用 reset 方法，重置表单或状态
      this.reset();
      // 获取生产订单号
      const rooteProdet = this.$route.query.productionOrderNo;
      console.log(rooteProdet);

      // 调用封装好的 API 方法
      updateProcessPlan(rooteProdet)
        .then(response => {
          // 假设后端返回的数据可以直接赋值给表单
          this.form = response;
          // 弹出成功消息
          this.$modal.msgSuccess("更新" + rooteProdet + "工序计划时间成功");
          // 调用方法更新列表
          this.getList();
        })
        .catch(error => {
          // 处理错误，弹出错误提示
          this.$modal.msgError("更新，请重试！");
          console.error('更新工序计划失败:', error);
        })
        .finally(() => {
          // 隐藏加载状态
          this.loading = false;
        });
    },
    /** 更新计划时间*/
    generatePDFs(row) {
      // 显示加载状态
      this.loading = true;
      // 调用 reset 方法，重置表单或状态
      this.reset();
      // 获取生产订单号
      const rooteProdet = this.$route.query.productionOrderNo;
      console.log(rooteProdet);

      // 调用封装好的 API 方法
      generatePDFs(rooteProdet)
        .then(response => {
          // 假设后端返回的数据可以直接赋值给表单
          this.form = response;
          // 弹出成功消息
          this.$modal.msgSuccess("生成" + rooteProdet + "的PDF 成功 ");
          // 调用方法更新列表
          this.getList();
        })
        .catch(error => {
          // 处理错误，弹出错误提示
          this.$modal.msgError("更新，请重试！");
          console.error('更新工序计划失败:', error);
        })
        .finally(() => {
          // 隐藏加载状态
          this.loading = false;
        });
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateRoute(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addRoute(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除工艺路线编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delRoute(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/route/export', {
        ...this.queryParams
      }, `route_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.btn {
  font-size: 12px;
  padding: 7px 10px !important;
  border-radius: 0;
}

.handle {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 20px;
  border: none;
  background-color: #FAFAFA;
}
</style>
