<template>
  <div class="app-container">
    <el-form :model="queryParams" @submit.native.prevent ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <!-- <el-form-item label="工单编码" prop="workorderCode">
        <el-input
          v-model="queryParams.workorderCode"
          placeholder="请输入工单编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.statusArr" clearable placeholder="请选择状态" multiple>
          <el-option v-for="dict in dict.type.mes_workorder_status" :key="dict.value" :label="dict.label"
            :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否急单" prop="rushOrder">
        <el-select v-model="queryParams.rushOrder" placeholder="请选择是否急单" clearable>
          <el-option v-for="dict in dict.type.rush_order" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工单编码" prop="workorderCodes">
        <el-input v-model="queryParams.workorderCodes" placeholder="请输入工单编码" clearable type="textarea" :rows="2"
        resize="none"  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="来源单据" prop="sourceCode">
        <el-input v-model="queryParams.sourceCode" placeholder="请输入来源单据" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="订单编号" prop="salesVouchers">
        <el-input v-model="queryParams.salesVouchers" placeholder="请输入订单编号" clearable type="textarea" :rows="2" resize="none" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品编号" prop="productCodes">
        <el-input
          v-model="queryParams.productCodes"
          placeholder="请输入产品编号"
          type="textarea"
          :rows="2"
          resize="none"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="客户编码" prop="clientCode">
        <el-input
          v-model="queryParams.clientCode"
          placeholder="请输入客户编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="客户名称" prop="clientName">
        <el-input v-model="queryParams.clientName" placeholder="请输入客户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="品牌名称" prop="brandName">
        <el-input v-model="queryParams.brandName" placeholder="请输入品牌名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品分类" prop="itemTypeName">
        <el-input v-model="queryParams.itemTypeName" placeholder="请输入产品分类" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工单类型" prop="workorderType">
        <el-select v-model="queryParams.workorderType" clearable placeholder="请选择状态" >
          <el-option v-for="dict in dict.type.mes_workorder_type"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="编排单号" prop="arrangeCodes">
        <el-input v-model="queryParams.arrangeCodes" placeholder="请输入编排单号" clearable type="textarea" :rows="2" resize="none"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="工单类型" prop="workorderType">
        <el-input
          v-model="queryParams.workorderType"
          placeholder="请选择工单类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="工单生成日期">
        <el-date-picker v-model="daterangePurchaseDate" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="排版状态" prop="dtaActions">
        <el-select v-model="queryParams.dtaActions" placeholder="请选择排版状态" clearable multiple>
          <el-option v-for="dict in dict.type.dta_action" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="完工状态" prop="complate">
        <el-select v-model="queryParams.complate" placeholder="请选择完工状态" clearable>
          <el-option label="未完工"
            value="Incomplete"></el-option>
          <el-option label="完工"
          value="Completed"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="需求日期">
        <el-date-picker v-model="beginRequestDate" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </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-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="['mes:pro:workorder: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="['mes:pro:workorder: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="['mes:pro:workorder: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="['mes:pro:workorder: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="['mes:pro:workorder:edit']">导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-plus" size="mini" :disabled="single" @click="handleTurnWorry">
          转急单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-plus" size="mini" :disabled="multiple" @click="handleToolNumCheck"
          v-hasPermi="['mes:pro:workorder:dofinish']">刀模版具齐套检查
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-plus" size="mini" :disabled="multiple || combinationDisable" @click="handleCombination"
          v-hasPermi="['pro:combination:add']">订单组合
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-edit" size="mini" @click="()=>handleCombination('del')" :disabled="combinationDisable"
          >取消组合
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-plus" size="mini" :disabled="multiple || combinationDisable" @click="handleArrange"
          v-hasPermi="['mes:pro:workorder:dofinish']">生产编排
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-edit" size="mini" @click="()=>checkArrange()" :disabled="multiple"
          >编排分析
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-edit" size="mini" @click="()=>handleArrange('del')" :disabled="combinationDisable"
          >取消编排
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single || combination" @click="handleMake"
          v-hasPermi="['mes:pro:workorder:make']">生产补单
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <!-- <el-button
          type="warning"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="multiple"
          @click="handleDofinish"
          v-hasPermi="['mes:pro:workorder:dofinish']"
        >生成任务单
        </el-button> -->
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-plus" size="mini" :disabled="single" @click="handleCommandClick"
          v-hasPermi="['mes:pro:workorder:dofinish']">手工工单下达
        </el-button>
      </el-col>
      <el-col :span="1.2">
        <el-button type="warning" plain size="mini" v-print="printContent" id="printbtn" style="display: none"
          >打印工单
        </el-button>
        <el-button type="warning" plain size="mini" style="margin-left: 0;" icon="el-icon-printer" ref="printbtn" @click="handlePrint" :loading="printloading" v-hasPermi="['mes:pro:workorder:print']"
          >打印工单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-close" size="mini" @click="handleClose" :disabled="single"
          v-hasPermi="['mes:pro:workorder:close']">关闭
        </el-button>
      </el-col>
      <!-- <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar> -->
    </el-row>

    <!-- 手工工单下达 -->
    <el-dialog title="手工排产" :visible.sync="commandVisible" width="1200px" append-to-body>
      <CommandList v-if="commandVisible" ref="CommandListRef" :currentData="currentData" @close="commandVisible = false"
        :workorderId="currentData.workorderId"></CommandList>
      <div slot="footer" class="dialog-footer">
        <el-button @click="commandVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmCommand">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="textRulesVisible" width="500px" append-to-body>
      <div style="max-height: 400px;overflow:auto;" v-html="textRules"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="textRulesVisible = false">否</el-button>
        <el-button type="primary" @click="handleTipByYes">是</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog title="导入工单" :visible.sync="upload.open" width="400px">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :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">
          <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-table v-loading="loading" :data="workorderList" row-key="workorderId" default-expand-all :max-height="tableHeight" ref="tableRef"
      @selection-change="handleSelectionChange" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :summary-method="getSummaries" show-summary>
      <!-- 新增复选框 -->
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工单编码" width="180" prop="workorderCode">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleView(scope.row)" v-hasPermi="['mes:pro:workorder:query']">{{
            scope.row.workorderCode }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="是否急单" align="center" prop="rushOrder">
        <template slot-scope="scope">
          {{scope.row.rushOrder === 'Y' ? '是' : ''}}
        </template>
      </el-table-column>
      <el-table-column label="排版状态" align="center" prop="dtaAction">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dta_action" :value="scope.row.dtaAction" />
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_workorder_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="完工状态" align="center" prop="status">
        <template slot-scope="scope">
          {{scope.row.workorderStatus === 'Completed' ? '完工' : '未完工'}}
        </template>
      </el-table-column>
      <el-table-column label="工单类型" align="center" prop="workorderType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_workorder_type" :value="scope.row.workorderType" />
        </template>
      </el-table-column>
      <el-table-column label="需求用途" width="150" align="center" prop="requirementType" />
      <el-table-column label="下单时间" width="150" align="center" prop="createTime" />
      <el-table-column label="组合单号" width="180" align="center" prop="combinationCode" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="showCombDetail(scope.row, scope.row.combinationCode)">{{
            scope.row.combinationCode }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="编排单号" width="140px" align="center" prop="arrangeCode">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="showArrangDetail(scope.row, scope.row.arrangeCode)">{{
            scope.row.arrangeCode }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="订单编号" width="140" align="center" prop="salesVoucher" />
      <el-table-column label="刀具到货时间" width="140" align="center" prop="toolArrivalTime" />
      <el-table-column label="产品分类" width="200" align="center" prop="itemTypeName" :show-overflow-tooltip="true" />
      <el-table-column label="产品编号" width="120" align="center" prop="sapItemCode" />
      <el-table-column label="产品名称" width="200" align="center" prop="productName" />
      <el-table-column label="规格型号" align="center" prop="productSpc" :show-overflow-tooltip="true" />
      <el-table-column label="品牌名称" align="center" prop="brandName" :show-overflow-tooltip="true" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="过期天数" align="center" prop="expiredDay" :show-overflow-tooltip="true" />
      <el-table-column label="需求日期" align="center" prop="requestDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.requestDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="工单数量" align="center" prop="quantity" />
      <el-table-column label="开始序列码" align="center" prop="startSerial" width="100px" />
      <el-table-column label="结束序列码" align="center" prop="endSerial" width="100px" />
      <el-table-column label="调整数量" align="center" prop="quantityChanged" />
      <el-table-column label="已生产数量" align="center" width="100px" prop="quantityProduced" />
      <el-table-column label="不合格数" align="center" width="100px" prop="quantityUnqualify" />
      <el-table-column label="批次号" align="center" width="100px" prop="batchCode" />
      <el-table-column label="客户编码" align="center" prop="clientCode" />
      <el-table-column label="客户名称" align="center" width="150px" prop="clientName" />
      <!-- <el-table-column
        label="工单名称"
        width="200"
        align="center"
        prop="workorderName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="工单类型" align="center" prop="workorderType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.mes_workorder_type"
            :value="scope.row.workorderType"
          />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="工单来源" align="center" prop="orderSource">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.mes_workorder_sourcetype"
            :value="scope.row.orderSource"
          />
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        label="工艺名称"
        width="160"
        align="center"
        prop="routeName"
        show-overflow-tooltip
      /> -->

      <el-table-column label="操作" width="220px" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.status == 'PREPARE'"
            @click="handleUpdate(scope.row)" v-hasPermi="['mes:pro:workorder:edit']">修改
          </el-button> -->
          <el-button size="mini" type="text" icon="el-icon-search" @click="handleViewRecord(scope.row)">查看更新记录
          </el-button>

          <!-- <el-button size="mini" type="text" icon="el-icon-delete" v-if="scope.row.status == 'PREPARE'"
            @click="handleDelete(scope.row)" v-hasPermi="['mes:pro:workorder:remove']">删除
          </el-button> -->
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            v-if="
              scope.row.status == 'CONFIRMED' &&
              scope.row.workorderType == 'SELF'
            "
            @click="handleAdd(scope.row)"
            v-hasPermi="['mes:pro:workorder:update']"
            >新增</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            v-if="scope.row.status == 'CONFIRMED'"
            @click="handleFinish(scope.row)"
            v-hasPermi="['mes:pro:workorder:update']"
            >完成</el-button
          > -->

          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            v-if="scope.row.status =='PREPARE'"
            @click="confirmWorkorder(scope.row)"
            v-hasPermi="['mes:pro:workorder:update']"
          >确认</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page-sizes="[50, 100, 500, 1000, 2000, 3000, 4000]"
      :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改生产工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="工单编号" prop="workorderCode">
              <el-input v-model="form.workorderCode" placeholder="请输入工单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch v-model="autoGenFlag" active-color="#13ce66" active-text="自动生成"
                @change="handleAutoGenChange(autoGenFlag)" v-if="optType != 'view' && form.status == 'PREPARE'">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工单名称" prop="workorderName">
              <el-input v-model="form.workorderName" placeholder="请输入工单名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="8">
            <el-form-item label="来源类型" prop="orderSource">
              <el-radio-group
                v-model="form.orderSource"
                disabled
                v-if="optType == 'view'"
              >
                <el-radio
                  v-for="dict in dict.type.mes_workorder_sourcetype"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio
                >
              </el-radio-group>
              <el-radio-group v-model="form.orderSource" v-else>
                <el-radio
                  v-for="dict in dict.type.mes_workorder_sourcetype"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <el-col :span="8" v-if="form.orderSource == 'ORDER'">
            <el-form-item label="订单编号" prop="salesVoucher">
              <el-input v-model="form.salesVoucher" placeholder="请输入订单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据状态" prop="status">
              <el-select v-model="form.status" disabled placeholder="请选择单据状态">
                <el-option v-for="dict in dict.type.mes_workorder_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工单类型" prop="workorderType">
              <el-select v-model="form.workorderType" placeholder="请选择类型">
                <el-option v-for="dict in dict.type.mes_workorder_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="产品编号" prop="productCode">
              <el-input v-model="form.productCode" placeholder="请选择产品" >
                <el-button slot="append" @click="handleSelectProduct" icon="el-icon-search"></el-button>
              </el-input>
              <ItemSelect ref="itemSelect" @onSelected="onItemSelected" > </ItemSelect>
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请选择产品" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="productSpc">
              <el-input v-model="form.productSpc" placeholder="请选择产品" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" placeholder="请选择产品" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工单数量" prop="quantity">
              <el-input-number :min="1" v-model="form.quantity" placeholder="请输入生产数量" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="需求日期" prop="requestDate">
              <el-date-picker clearable v-model="form.requestDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择需求日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次号" prop="batchCode">
              <el-input v-model="form.batchCode" placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.orderSource == 'ORDER'">
          <el-col :span="12">
            <el-form-item label="客户编码" prop="clientCode">
              <el-input v-model="form.clientCode" placeholder="请选择客户">
                <el-button slot="append" @click="handleSelectClient" icon="el-icon-search"></el-button>
              </el-input>
              <ClientSelect ref="clientSelect" @onSelected="onClientSelected">
              </ClientSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="form.clientName" readonly="readonly" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col></el-col>
        </el-row>
        <el-row v-if="
          form.workorderType == 'OUTSOURCE' ||
          form.workorderType == 'PURCHASE'
        ">
          <el-col :span="12">
            <el-form-item label="供应商编码" prop="vendorCode">
              <el-input v-model="form.vendorCode" placeholder="请选择供应商">
                <el-button slot="append" @click="handleSelectVendor" icon="el-icon-search"></el-button>
              </el-input>
              <VendorSelect ref="vendorSelect" @onSelected="onVendorSelected" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="vendorName">
              <el-input v-model="form.vendorName" readonly="readonly" placeholder="请选择供应商" />
            </el-form-item>
          </el-col>
          <el-col></el-col>
        </el-row>
        <el-row>
          <el-col></el-col>
          <el-col></el-col>
          <el-col></el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-tabs type="border-card" v-if="form.workorderId != null">
        <el-tab-pane label="BOM组成">
          <Workorderbom ref="bomlist" :optType="optType" :workorder="form" @handleAddSub="handleSubAdd"></Workorderbom>
        </el-tab-pane>
        <el-tab-pane label="物料需求"></el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType == 'view' || form.status != 'PREPARE'">返回
        </el-button>
        <el-button type="primary" @click="submitForm" v-if="form.status == 'PREPARE' && optType != 'view'">保 存
        </el-button>
        <el-button type="success" @click="handleConfirm" v-if="
          form.status == 'PREPARE' &&
          optType != 'view' &&
          form.workorderId != null
        ">确 认
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog title="组合单明细" v-if="combOpen" :visible.sync="combOpen" width="1000px" append-to-body>
      <CombinationInfos :combinationCodes="combinationCodes" :showBtn="showCombinationBtn"></CombinationInfos>
    </el-dialog>

    <el-dialog title="编排单明细" v-if="arrangeOpen" :visible.sync="arrangeOpen" width="1000px" append-to-body>
      <ArrangeInfo :arrange-code="arrangeCode" :showBtn="showArrangBtn"></ArrangeInfo>
    </el-dialog>

    <el-dialog title="编排单明细" v-if="arrangeOpen2" :visible.sync="arrangeOpen2" width="1000px" append-to-body>
      <ArrangeInfo :group-code="groupCode" :addBtn="false"></ArrangeInfo>
    </el-dialog>
    <WorkorderRecordSelect ref="WorkorderRecordSelectRef" :data="currentData" />
    <div style="overflow: hidden;width: 0;height: 0;">

      <div id="productOrderDetail">
        <div v-for="(item, index) in productionSolutionTable" :key="'productionSolutionTable' + index">
          <productOrderSpecification :productionSolutionTable="item" style="page-break-after:always"></productOrderSpecification>
          <productOrderDetail :workOrderTable="workOrderTable[index]" style="page-break-after:always"></productOrderDetail>
        </div>
      </div>
    </div>
    <el-dialog title="添加转急单" :visible.sync="turnWorryVisible" width="340px" append-to-body>
      <el-form ref="turnWorryFormRef" :model="turnWorryForm" :rules="turnWorryFormRules" label-width="80px">
          <el-form-item label="需求时间" prop="requestDate">
          <el-date-picker
            v-model="turnWorryForm.requestDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleTurnWorrySubmit">确 定</el-button>
        <el-button @click="handleTurnWorryCancle">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="刀模版齐套确认" :visible.sync="daoConfirmVisible" width="1050px" append-to-body :close-on-click-modal="false">
      <el-table :data="daoConfirmList">
        <el-table-column label="工单编码" align="center" prop="workorderCode" width="130px" />
        <el-table-column label="提示信息" align="center" prop="word" show-overflow-tooltip />
        <el-table-column label="是否强制检查完成" align="center" prop="word" width="125px">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.isBool"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="刀模版计划到厂时间" align="center" prop="allQuantity" >
          <template slot-scope="scope">
            <el-date-picker
            v-model="scope.row.toolArrivalTime"
            :picker-options="option"
            v-if="scope.row.isBool"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handledaoConfirmSubmit">确 定</el-button>
        <el-button @click="daoConfirmVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import RoutesProcessSelect from "@/components/routesProcessSelect/index.vue";
import WorkorderRecordSelect from "@/components/workorderRecordSelect/index.vue";
import productOrderDetail from "./print/productOrderDetail.vue";
import productOrderSpecification from "./print/productOrderSpecification.vue";

import {
  listWorkorder,
  getWorkorder,
  delWorkorder,
  addWorkorder,
  updateWorkorder,
  dofinish,
  printInfo,
  doCheckToolNum,
  checkTheMaintenanceApi,
  delComWorkorder,
  closeWorkorder,
  closeCheck,
  updateRequestDateApi,
  tmtoolForcePass,
  changePublishedApi
} from "@/api/mes/pro/workorder";
import { addProtaskList } from "@/api/mes/pro/protask";
import shiftSelectMixin from '@/utils/shiftSelectMixin'
import Workorderbom from "./bom/bom.vue";
import WorkorderItemList from "./items/item.vue";
import ItemSelect from "@/components/itemSelect/single.vue";
import ClientSelect from "@/components/clientSelect/single.vue";
import VendorSelect from "@/components/vendorSelect/single.vue";
import { genCode } from "@/api/system/autocode/rule";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";
import { addCombination, batchAddCombination,batchAddCombinations } from "@/api/mes/pro/combination";
import CombinationInfos from "@/views/mes/pro/combination/infos.vue";
import { batchAddArrange, delArrange,delArrange2, checkArrangeRulesApi,checkArrange } from "@/api/mes/pro/arrange";
import ArrangeInfo from "@/views/mes/pro/arrange/info.vue";
import CommandList from "./commandList.vue";
import dayjs from 'dayjs';
import print from 'vue-print-nb';
export default {
  directives: { print },
  name: "Workorder",
  dicts: [
    "mes_workorder_status",
    "dta_action",
    "rush_order",
    "mes_workorder_sourcetype",
    "mes_workorder_type",
  ],
  mixins: [shiftSelectMixin],
  components: {
    productOrderDetail,
    productOrderSpecification,
    ArrangeInfo,
    CombinationInfos,
    Treeselect,
    RoutesProcessSelect,
    WorkorderRecordSelect,
    ItemSelect,
    ClientSelect,
    VendorSelect,
    Workorderbom,
    WorkorderItemList,
    CommandList
  },
  data() {
    return {
      commandVisible: false,
      tableHeight: 0,
      daoConfirmVisible: false,
      daoConfirmList: [],
      showArrangBtn: false,
      showCombinationBtn: false,
      currentData: {},
      option: {
        disabledDate:(time)=> {
            return time.getTime() < Date.now() -1 * 24 * 3600 * 1000
        }
      },
      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      combOpen: false,
      printContent: {
        id: 'productOrderDetail',
        // preview: true, // 预览工具是否启用
        // previewTitle: '储能服务费结算单', // 预览页面的标题
        popTitle: '', // 打印页面的页眉
        extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
        previewBeforeOpenCallback() {
        },
        previewOpenCallback() {},
        beforeOpenCallback(vue) {
          // vue.printLoading = true;
        },
        openCallback(vue) {
          vue.printloading = false;
        },
        closeCallback() {},
        clickMounted(vue) {
          console.log('clickMounted')
        },
      },
      combinationDisable: false,
      combination: false,
      combinationCodes: [],
      arrangeOpen: false,
      enablePrint: false,
      arrangeOpen2: false,
      arrangeCode: [],
      groupCode: "",
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 非单个禁用
      single: true,
      // 总条数
      total: 0,
      // 非多个禁用
      multiple: true,
      // 生产工单表格数据
      workorderList: [],
      // 生产工单树选项
      workorderOptions: [],
      selectedRows: [],
      textRulesVisible: false,
      textRules: '',
      daterangePurchaseDate: [],
      beginRequestDate: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/mes/pro/workorder/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        workorderCodes: null,
        arrangeCodes: null,
        dtaActions: [],
        complate: null,
        workorderName: null,
        orderSource: null,
        sapItemCode: null,
        // sourceCode: null,
        salesVouchers: null,
        productId: null,
        productCodes: null,
        productName: null,
        productSpc: null,
        routeName: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        brandName: null,
        parentId: null,
        ancestors: null,
        statusArr: ["PREPARE", "PUBLISHED"],
        rushOrder: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        workorderCode: [
          { required: true, message: "工单编码不能为空", trigger: "blur" },
        ],
        workorderName: [
          { required: true, message: "工单名称不能为空", trigger: "blur" },
        ],
        workorderType: [
          { required: true, message: "请选择生产工单类型", trigger: "blur" },
        ],
        orderSource: [
          { required: true, message: "来源类型不能为空", trigger: "blur" },
        ],
        productId: [
          { required: true, message: "产品不能为空", trigger: "blur" },
        ],
        productCode: [
          { required: true, message: "产品编号不能为空", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" },
        ],
        quantity: [
          { required: true, message: "生产数量不能为空", trigger: "blur" },
        ],
        requestDate: [
          { required: true, message: "需求日期不能为空", trigger: "blur" },
        ],
      },
      productionSolutionTable: [],
      workOrderTable: [],
      printloading: false,
      turnWorryVisible: false,
      turnWorryForm: {
        workorderId: '',
        requestDate: ''
      },
      turnWorryFormRules: {
        requestDate: [
          { required: true, message: "需求时间不能为空", trigger: "blur" },
        ],
      }
    };
  },
  activated() {
    this.getList();
  },
  created() {
    this.setDate();
    this.getList();
  },
  mounted(){
    this.$nextTick(()=>{
      this.tableHeight = window.innerHeight - 358
    })

  },
  methods: {
    //筛选日期设置默认值
    setDate() {

      this.daterangePurchaseDate = [dayjs().format('YYYY-MM-DD'), dayjs().add(7, 'day').format('YYYY-MM-DD')]
    },
    handlePrint(){
      if(!this.ids || this.ids.length === 0) return this.$message.warning('请选择工单')
      this.printloading = true;
      printInfo(this.ids).then(res=>{
        if(!res.data || res.data.length === 0) {
          return this.$message.warning('没有数据')
        }
        if(res.code === 200 && res.data) {
          this.productionSolutionTable = res.data.map(v=>v.productionSolutionTable)
          this.workOrderTable = res.data.map(v=>v.workOrderTable)
          this.$nextTick(() => {
            document.getElementById('printbtn').click()
          })
        }
      }).finally(() => {
        this.printloading = false;
      })
    },
    handleCommandClick() {
      this.currentData = this.selectedRows[0]
      if ((this.selectedRows[0].workorderType == 'prototype' || this.selectedRows[0].workorderType == 'cutting' || this.selectedRows[0].workorderType == 'reback') && this.selectedRows[0].status === "PUBLISHED") {
        this.commandVisible = true
      } else {
        this.$message.warning('请选择工单类型为打样工单、切料工单、状态为已发布的数据')
      }
    },
    handleViewRecord(row) {
      this.currentData = row
      this.$refs.WorkorderRecordSelectRef.showFlag = true
    },
    showCombDetail(row, combinationCode) {
      this.combOpen = true;
      if (row.status === 'COMBINED') {
        this.showCombinationBtn = true
      } else {
        this.showCombinationBtn = false
      }
      this.combinationCodes = [combinationCode];
    },
    handleClose(){
      if(this.ids.length === 0) return this.$message.warning('请勾选要关闭的工单')
      const obj = this.ids.map(v=>({
        workorderId: v,
        status: "CLOSE"
      }))
      const params = this.selectedRows.map(v=>({
        workorderId: v.workorderId,
        workorderCode: v.workorderCode,
        checkState: 1
      }))
      closeCheck(params).then(async res => {
        let confirmRes = null
        if(res.msg) {
          confirmRes = await this.$modal.confirm(res.msg)
        }
        if(!res.msg || confirmRes === 'confirm') {
          params.forEach(vv=> {
            vv.checkState = 2
          })
          closeCheck(params).then(async res => {
            let confirmRes1 = null
            if(res.msg) {
              confirmRes1 = await this.$modal.confirm(res.msg)
            }
            if(!res.msg || confirmRes1 === 'confirm') {
              params.forEach(vv=> {
                vv.checkState = 3
              })
              closeCheck(params).then(async res => {
              let confirmRes2 = null
                if(res.msg) {
                  confirmRes2 = await this.$modal.confirm(res.msg)
                }
                if(!res.msg || confirmRes2 === 'confirm') {
                  this.$modal.confirm('经检查，工单符合关闭条件，是否确认关闭工单？（注意：一经确认关闭，无法取消关闭。）').then(() => {
                    this.$modal.confirm('请再次确认是否关闭工单？（注意：一经确认关闭，无法取消关闭。）').then(() => {
                      closeWorkorder(JSON.stringify(obj)).then(({data}) => {
                        this.$message.success('关闭工单成功')
                        this.getList();
                      })
                    })
                  })
                }
              })
            }
          })
        }
      })


    },
    showArrangDetail(row, arrangeCode) {
      this.arrangeOpen = true;
      if (row.status === 'ORCHESTRATED') {
        this.showArrangBtn = true
      } else {
        this.showArrangBtn = false
      }
      this.arrangeCode = arrangeCode;
    },
    checkArrange(){
      if(this.ids.length !== 2) return this.$message.warning('请选择两条工单记录进行分析！')
      checkArrange({workorderIdList: this.ids}).then(res => {
        if (res.code == 200) {
          this.$modal.msgSuccess("可以编排在一起");
        }
      }
      )
    },
    handleTipByYes() {
      let params = [];
      this.selectedRows.forEach((item, index) => {
        params.push({
          arrangeSort: index + 1,
          workorderId: item.workorderId,
          workorderCode: item.workorderCode,
          arrangeCode: null
        })
      });
      batchAddArrange(params).then(response => {
        this.arrangeOpen2 = true;
        this.groupCode = response;
        this.$modal.msgSuccess("新增编排单成功");
        this.getList();
      }).finally(() => {
        this.textRulesVisible = false
      });
    },
    async handleArrange(type) {
      if(type === 'del') {
        if(this.ids.length === 0) return this.$message.warning('请勾选要取消编排的工单')
        this.$modal.confirm('确认取消编排？').then(() => {
          return delArrange2(this.ids)//执行报工
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("取消成功");
        }).catch(() => {});
        return
      }
      // status: "COMBINED"
      // for(const item in this.selectedRows){
      //   if (item.arrangeCode != '' && item.arrangeCode != null) {
      //     this.$modal.msgWarning(`${item.workorderCode}生产单已绑定编排单，不能再绑定！`);
      //     return false;
      //   }
      // }
      let workorderCode = []
      this.selectedRows.forEach(item => {
        if (item.status !== 'COMBINED' || (item.status === 'COMBINED' && (item.dtaAction === '0' || !item.dtaAction))) {
          workorderCode.push(item.workorderCode)
          return
        }
      })
      if (workorderCode.length > 0) {
        this.$modal.msgWarning(`${workorderCode[0]}只允许操作单据状态为已组合数据和单据状态为已排版或单据状态为已组合数据和单据状态为无需排版的数据！`);
        return
      }
      const cparams = []
      this.selectedRows.forEach((item, index) => {
        cparams.push({
          workorderId: item.workorderId,
        })
      });
      checkArrangeRulesApi(cparams).then(res => {
        if(res.data && typeof res.data == 'object' && res.data.length > 0) {
          this.textRules = res.data.join('<br />')
          this.textRulesVisible = true
        } else {
          let params = [];
          this.selectedRows.forEach((item, index) => {
            params.push({
              arrangeSort: index + 1,
              workorderId: item.workorderId,
              workorderCode: item.workorderCode,
              arrangeCode: null
            })
          });
          batchAddArrange(params).then(response => {
            this.arrangeOpen2 = true;
            this.groupCode = response;
            this.$modal.msgSuccess("新增编排单成功");
            this.getList();
          });
        }
      })
    },
    async handleCombination(type) {
      if(type === 'del') {
        if(this.ids.length === 0) return this.$message.warning('请勾选要取消组合的工单')
        this.$modal.confirm('确认取消组合？').then(() => {
          return delComWorkorder(this.ids)//执行报工
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("取消成功");
        }).catch(() => {});
        return
      }
      let params = []
      let hasNonEmptyCombination = false;
      this.selectedRows.every((item, index) => {
        if (item.combinationCode != '' && item.combinationCode != null) {
          this.$modal.msgWarning(`${item.workorderCode}生产单已绑定组合单，不能再绑定！`);
          hasNonEmptyCombination = true;
          return false; // 结束every循环
        }
        return true; // 继续检查下一个项
      });
      if (!hasNonEmptyCombination) {
        this.selectedRows.forEach((item, index) => {
          params.push({
            combinationSort: index + 1,
            workorderId: item.workorderId,
            workorderCode: item.workorderCode,
            salesOrderId: 0,
            combinationCode: null
          })
        });

        batchAddCombination(params).then(response => {
         if (response && response.length > 0) {
            if(response[0]=='0'){
              this.$modal
             .confirm(
          '生产规格书的印张长度或者模数是空的，是否继续组合？'
        )
        .then(function () {
          return batchAddCombinations(params);
        })
        .then(responses => {
          this.combOpen = true
          this.combinationCodes = responses
          this.$modal.msgSuccess("新增组合单成功1");
        })
        .catch(() => {
        });
          }else{
            this.combOpen = true
            this.combinationCodes = response
            this.$modal.msgSuccess("新增组合单成功2");
             }

          } else{
            this.$modal
        .confirm(
          '的最大米数、最大印张数没有设置，是否继续组合？'
        )
        .then(function () {
          return batchAddCombinations(params);
        })
        .then(responses => {
          this.combOpen = true
          this.combinationCodes = responses
          this.$modal.msgSuccess("新增组合单成功12");
        })
        .catch(() => {
        });
          }
          this.getList();
        });
      }
    },
    /** 查询生产工单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangePurchaseDate && '' != this.daterangePurchaseDate) {
        this.queryParams.params["beginPurchaseDate"] = this.daterangePurchaseDate[0];
        this.queryParams.params["endPurchaseDate"] = this.daterangePurchaseDate[1];
      }
      if (null != this.beginRequestDate && '' != this.beginRequestDate) {
        this.queryParams.params["beginRequestDate"] = this.beginRequestDate[0];
        this.queryParams.params["endRequestDate"] = this.beginRequestDate[1];
      }
      const params = {
        ...this.queryParams,
        workorderCodes: this.queryParams.workorderCodes ? this.queryParams.workorderCodes.split(/[\n,;，、；。]/).filter(item => item) : null,
        salesVouchers: this.queryParams.salesVouchers ? this.queryParams.salesVouchers.split(/[\n,;，、；。]/).filter(item => item) : null,
        productCodes: this.queryParams.productCodes ? this.queryParams.productCodes.split(/[\n,;，、；。]/).filter(item => item) : null,
        arrangeCodes: this.queryParams.arrangeCodes ? this.queryParams.arrangeCodes.split(/[\n,;，、；。]/).filter(item => item) : null
      }
      listWorkorder(params).then((response) => {
        this.workorderList = this.handleTree(
          response.rows,
          "workorderId",
          "parentId"
        );
        this.total = response.total;
        this.loading = false;
      });
    },
    importTemplate() {
      this.download(
        "mes/pro/workorder/importTemplate",
        {},
        `work_order_template_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.open = true;
    },
    // 文件上传中处理
    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();
    },
    /** 转换生产工单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.workorderId,
        label: node.workorderName,
        children: node.children,
      };
    },
    /** 查询生产工单下拉树结构 */
    getTreeselect() {
      listWorkorder().then((response) => {
        this.workorderOptions = [];
        const data = {
          workorderId: 0,
          workorderName: "顶级节点",
          children: [],
        };
        data.children = this.handleTree(
          response.data,
          "workorderId",
          "parentId"
        );
        this.workorderOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        workorderType: "SELF",
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        routeName: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        salesVoucher: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        sapItemCode: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        requestDate: null,
        parentId: null,
        status: "PREPARE",
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.autoGenFlag = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.daterangePurchaseDate = [];
      this.beginRequestDate = []
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //从BOM行中直接新增
    handleSubAdd(row) {
      this.open = false;
      this.reset();
      this.getTreeselect();
      if (row != null && row.workorderId) {
        this.form = row;
        this.form.parentId = row.workorderId;
        this.form.workorderId = null;
        this.form.workorderCode = null;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加生产工单";
      this.optType = "add";
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.getTreeselect();
      // 跳转到申请单界
      this.$router.push("/mes/pro/workorder/apply");
      return;
    },
    // 查询明细按钮操作
    handleView(row) {
      if (row.workorderType === 'complements') {
        this.reset();
        this.getTreeselect();
        const workorderId = row.workorderId || this.ids;
        this.$router.push("/mes/pro/workorder/makeInfo?workorderId=" + workorderId);
      } else {
        this.reset();
        this.getTreeselect();
        const workorderId = row.workorderId || this.ids;
        this.$router.push("/mes/pro/workorder/info?workorderId=" + workorderId);
      }

      // this.reset();
      // this.getTreeselect();
      // const workorderId = row.workorderId || this.ids;
      // getWorkorder(workorderId).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "查看工单信息";
      //   this.optType = "view";
      // });
    },
    handleSelectionChange(selection, row) {
      const data = this.$refs.tableRef.tableData; // 获取table当前数据
      const startIdx = this.startIndex; // 获取首次选择对应列的索引
      const lastindex = data.findIndex(v => v === selection[selection.length - 1])
      this.selectedRows = selection;
      if (this.keepDown && selection.includes(data[startIdx])) {
        const sum = Math.abs(startIdx - lastindex) + 1; // 用户可能反向选取，所以要取绝对值
        const min = Math.min(startIdx, lastindex); // 获取起点和终点较小的值
        let i = 0;
        while (i < sum) {
          const index = min + i;
          if (!this.selectedRows.includes(data[index])) {
            this.$refs.tableRef.toggleRowSelection(data[index], true);
          }
          i++;
        }
      } else {
        this.startIndex = lastindex

      }
      this.ids = this.selectedRows.map(item => item.workorderId)
      this.single = this.selectedRows.length !== 1
      this.multiple = !this.selectedRows.length
      this.combinationDisable = false
      this.selectedRows.forEach(item => {
        if (['cutting', 'prototype','reback' ].indexOf(item.workorderType) > -1) {
          this.combinationDisable = true
        }
        if (['reback', 'prototype'].indexOf(item.workorderType) > -1) {
          this.combination = true
        } else {
          this.combination = false
        }
      })
    },
    //   // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.toolId)
    //   this.single = selection.length!==1
    //   this.multiple = !selection.length
    // },
    getSummaries(param){
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '总数量'
          } else if (column.label === '工单数量') {
            const temp = data.reduce((prev, curr) => {
              return prev + Number(curr.quantity);
            }, 0)
            sums[index] =  Number.isInteger(temp) ? temp : temp.toFixed(3);
          } else {
            sums[index] = ''
          }
        })
        return sums
      },

    //  查询记录
    handleSelectChangerecord() {
      this.reset();
      this.$router.push("/mes/pro/workorder/changerecord");
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();

      const workorderId = row.workorderId || this.ids;
      console.log('workorderId', workorderId, this.ids)
      this.$router.push("/mes/pro/workorder/edit?workorderId=" + workorderId);

      // this.reset();
      // this.getTreeselect();
      // if (row != null) {
      //   this.form.parentId = row.workorderId;
      // }
      // getWorkorder(row.workorderId).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改生产工单";
      //   this.optType="edit";
      // });
    },
    handleMake() {
      if (this.selectedRows[0].workorderType === 'complements') return this.$message.warning('补数工单类型不可以再继续补数操作')
      // if (this.selectedRows[0].workorderType == 'product' && this.selectedRows[0].status == "SCHEDULED"
      // ) {
        const workorderId = this.selectedRows[0].workorderId
        this.$router.push("/mes/pro/workorder/make?workorderId=" + workorderId);
      // } else {
      //   this.$message.warning('请选择工单类型为生产订单、工单状态为已排产的数据')
      // }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.workorderId != null) {
            updateWorkorder(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              //this.open = false;
              this.$refs["bomlist"].getList();
              this.getList();
            });
          } else {
            addWorkorder(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              //this.open = false;
              this.form.workorderId = response.data;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm(
          '是否确认删除生产工单编号为"' + row.workorderId + '"的数据项？'
        )
        .then(function () {
          return delWorkorder(row.workorderId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        });
    },
    /** 生产任务单操作 */
    handleDofinish() {
      this.$modal
        .confirm("是否生成选中的任务单？")
        .then(() => {
          let allCodesNotEmpty = true;

          this.selectedRows.every(row => {
            if (row.arrangeCode == '' || row.arrangeCode == null) {
              allCodesNotEmpty = false;
              return false; // 结束every循环
            }
            return true; // 继续检查下一个元素
          });

          if (allCodesNotEmpty) {
            const ids = this.selectedRows.map((v) => v.workorderId);
            console.log("00000", ids);
            return addProtaskList(ids);
          } else {
            this.$modal.msgWarning("存在未编排工单，请编排后再试！");
            return Promise.reject(); // 或者返回一个已解决的Promise以停止链式调用
          }
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("生成成功");
        })
        .catch(() => {
          // 用户取消或出现错误时的处理
        });

    },
    async checkTheMaintenance(ids) {
      const res = await checkTheMaintenanceApi(ids);
      if(res.code == 200) {
        const noticeList = [];
        if(!res.data || res.data.length == 0) {
          this.getList();
          this.$modal.msgSuccess("已齐套");
        } else {
          this.daoConfirmList = []
          res.data.forEach(item1 => {
            const word = item1.noticeList.join('')
            const row = this.selectedRows.find(i => i.workorderId === item1.workorderId)
            this.daoConfirmList.push({
              workorderCode: row.workorderCode,
              workorderId: item1.workorderId,
              word: word,
              toolArrivalTime: '',
              isBool: false
            })
            this.daoConfirmVisible = true
          })
        }
      }
    },
    handleToolNumCheck() {
      this.$modal
        .confirm("是否检查刀具模版齐套？")
        .then(() => {
          const ids = this.selectedRows.map((v) => v.workorderId);
          this.checkTheMaintenance(ids);
        })
        .catch(() => {
        });
    },
    handleSelectProduct() {
      this.$refs.itemSelect.showFlag = true;
    },
    handleSelectClient() {
      this.$refs.clientSelect.showFlag = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      const params = {
        ...this.queryParams,
        workorderCodes: this.queryParams.workorderCodes ? this.queryParams.workorderCodes.split(/[\n,;，、；。]/).filter(item => item) : null,
        salesVouchers: this.queryParams.salesVouchers ? this.queryParams.salesVouchers.split(/[\n,;，、；。]/).filter(item => item) : null,
        productCodes: this.queryParams.productCodes ? this.queryParams.productCodes.split(/[\n,;，、；。]/).filter(item => item) : null,
        arrangeCodes: this.queryParams.arrangeCodes ? this.queryParams.arrangeCodes.split(/[\n,;，、；。]/).filter(item => item) : null
      }
      if(this.ids && this.ids.length > 0) {
        params.workorderCodes = this.selectedRows.map(item => item.workorderCode)
      }
      params.statusArr = params.statusArr.length > 0 ? params.statusArr : null;
      params.dtaActions = params.dtaActions.length > 0 ? params.dtaActions : null;
      delete params.pageNum;
      delete params.pageSize;
      this.download1(
        "mes/pro/workorder/export",
        params,
        `workorder_${new Date().getTime()}.xlsx`
      );
    },
    confirmCommand(){
      if (this.$refs.CommandListRef.submit()) {
        this.getList()
      }
    },
    handleConfirm() {
      let that = this;
      this.$modal
        .confirm("是确认完成工单编制？【确认后将不能更改】")
        .then(function () {
          that.form.status = "CONFIRMED";
          that.submitForm();
        });
    },
    handleFinish(row) {
      const workorderIds = row.workorderId || this.ids;
      this.$modal
        .confirm("确认完成工单？一旦完成，此工单将无法继续报工")
        .then(function () {
          return dofinish(workorderIds); //完成工单
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("更改成功");
        })
        .catch(() => {
        });
    },
    // //物料选择弹出框
    // onItemSelected(obj){
    //     if(obj != undefined && obj != null){
    //       this.form.productId = obj.itemId;
    //       this.form.productCode = obj.itemCode;
    //       this.form.productName = obj.itemName;
    //       this.form.productSpc = obj.specification;
    //       this.form.unitOfMeasure = obj.unitOfMeasure;
    //     }
    // },
    //客户选择弹出框
    onClientSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.clientId = obj.clientId;
        this.form.clientCode = obj.clientCode;
        this.form.clientName = obj.clientName;
      }
    },
    //供应商选择
    handleSelectVendor() {
      this.$refs.vendorSelect.showFlag = true;
    },
    //供应商选择弹出框
    onVendorSelected(obj) {
      debugger;
      if (obj != undefined && obj != null) {
        this.form.vendorId = obj.vendorId;
        this.form.vendorCode = obj.vendorCode;
        this.form.vendorName = obj.vendorName;
      }
    },
    /** 完成任务单操作 */
    confirmWorkorder(row) {
      this.$modal
        .confirm(
          '是否将工单编号"' + row.workorderCode + '"的草稿数据项改为已确认？'
        )
        .then(function () {
          return confirmedWorkorder(row.workorderId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("已确认成功");
        })
        .catch(() => {
        });
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode("WORKORDER_CODE").then((response) => {
          this.form.workorderCode = response;
        });
      } else {
        this.form.workorderCode = null;
      }
    },
    handleTurnWorry() {
      if(["PREPARE", "PUBLISHED"].includes(this.selectedRows[0].status)) {
        this.turnWorryForm.workorderId = this.selectedRows[0].workorderId;
        this.turnWorryVisible = true;
      } else {
        this.$message({
          message: '所选工单不处于已发布或者待发布状态不允许更改！',
          type: 'warning'
        });
      }
    },
    handledaoConfirmSubmit(){
      const list = this.daoConfirmList.filter(v=> v.isBool && !v.toolArrivalTime)
      if (list.length) {
        return this.$modal.msgWarning("强制检查完成必须选择刀模版计划到厂时间")
      }
      const list11 = this.daoConfirmList.filter(v=> v.isBool && v.toolArrivalTime)
      const list1 = list11.map(v => ({toolArrivalTime: v.toolArrivalTime, workorderId: v.workorderId}))
      if (list1.length > 0) {
        tmtoolForcePass(list1).then(response => {
          this.$modal.msgSuccess("操作成功");
            this.daoConfirmVisible = false
            this.getList();
        });
      } else {
        this.daoConfirmVisible = false
        this.getList();
      }

    },
    handleTurnWorrySubmit() {
      this.$refs["turnWorryFormRef"].validate(valid => {
        if (valid) {
            updateRequestDateApi(this.turnWorryForm).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.handleTurnWorryCancle();
              this.getList();
            });
          }
      });
    },
    handleTurnWorryCancle() {
      this.turnWorryVisible = false;
    }
  }
}
</script>
<style>
@page {
    size: auto;
    margin: 0mm;
  }
</style>
