<template>
  <div class="app-container mes-admin-page">
    <el-card class="topCard">
      <div class="topDiv topToolbar">
        <span style="margin-left: 10px">{{ $t('releaseOfProductionPlan.orderNumberLabel') }}</span>
        <el-input v-model="orderNumberValue" clearable :placeholder="$t('releaseOfProductionPlan.filterOrderNumber')" size="small" style="width: 200px"/>
        <span style="margin-left: 10px">{{ $t('releaseOfProductionPlan.productModelLabel') }}</span>
        <el-select
          v-model="engineTypeValue"
          :placeholder="$t('releaseOfProductionPlan.selectProductModel')"
          clearable
          size="small"
          style="width: 150px"
        >
          <el-option
            v-for="item in engineType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            size="mini"
          />
        </el-select>
        <span style="margin-left: 10px">{{ $t('releaseOfProductionPlan.startDateLabel') }}</span>
        <el-date-picker
          v-model="startPlanTime"
          type="date"
          size="small"
          value-format="yyyy-MM-dd"
          :placeholder="$t('releaseOfProductionPlan.selectStartDate')"
        />
        <span style="margin-left: 10px">{{ $t('releaseOfProductionPlan.endDateLabel') }}</span>
        <el-date-picker
          v-model="endPlanTime"
          type="date"
          size="small"
          value-format="yyyy-MM-dd"
          :placeholder="$t('releaseOfProductionPlan.selectEndDate')"
        />
        <el-button
          type="primary"
          plain
          size="small"
          icon="el-icon-search"
          style="margin-left: 10px"
          @click="
            pageSize = 30;
            pageCurrent = 1;
            searchOrder();
          "
        >{{ $t('releaseOfProductionPlan.searchOrder') }}</el-button>
        <el-button
          type="warning"
          size="small"
          icon="el-icon-circle-plus"
          @click="creatOrder('form')"
        >{{ $t('releaseOfProductionPlan.createOrder') }}</el-button>
        <!--        <el-button type="info" plain size="small" icon="el-icon-upload2" @click="importOrder('form')">订单导入</el-button>-->
        <!--        <el-button type="info" plain size="small" icon="el-icon-download" @click="exportExcel()">订单导出</el-button>-->
      </div>
      <div class="tablePanel">
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="tableData"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          :cell-class-name="tableRowClassName"
          :expand-row-keys="expandsDetail"
          :row-key="getRowKeys"
          :element-loading-text="$t('releaseOfProductionPlan.loadingData')"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.2)"
          class="main"
          tooltip-effect="dark"
          style="width: 100%; max-height: 700px"
          border
          height="800px"
          size="mini"
          @expand-change="selectPlan"
          @selection-change="handleSelectionChange"
        >
          <el-table-column align="center" type="index" :label="$t('releaseOfProductionPlan.sort')" />
          <el-table-column align="center" type="expand" label="" fixed width="35">
            <template>
              <div style="display: flex">
                <!-- 详细数据盒子 -->
                <div style="margin: 5px 10px; width: 1000px; z-index: 99">
                  <el-table
                    :data="tableDataPrintDetail"
                    :header-cell-style="{
                      background: '#e5e7f8',
                      color: '#606266',
                    }"
                    :element-loading-text="$t('releaseOfProductionPlan.loadingData')"
                    element-loading-spinner="el-icon-loading"
                    element-loading-background="rgba(0, 0, 0, 0.2)"
                    class="main"
                    tooltip-effect="dark"
                    style="width: 100%; z-index: 99"
                    max-height="400px"
                    border
                    size="mini"
                  >
                    <el-table-column align="center" type="index" :label="$t('releaseOfProductionPlan.sequence')" />
                    <el-table-column align="center" label="缸体码">
                      <template slot-scope="scope">
                        {{ scope.row.箱体码 }}
                      </template>
                    </el-table-column>
                    <el-table-column align="center" :label="$t('releaseOfProductionPlan.crankcaseAssemblyNo')">
                      <template slot-scope="scope">
                        {{ scope.row.发动机号 }}
                      </template>
                    </el-table-column>
                    <el-table-column align="center" :label="$t('releaseOfProductionPlan.onlineTime')" width="150">
                      <template slot-scope="scope">
                        {{ scope.row.上线时间 }}
                      </template>
                    </el-table-column>
                    <el-table-column align="center" :label="$t('releaseOfProductionPlan.offlineTime')" width="150">
                      <template slot-scope="scope">
                        {{ scope.row.下线时间 }}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('releaseOfProductionPlan.orderNumber')">
            <template slot-scope="scope">
              {{ scope.row.订单号 }}
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('releaseOfProductionPlan.productModel')">
            <template slot-scope="scope">
              {{ scope.row.产品型号 }}
            </template>
          </el-table-column>
          <!--        <el-table-column align="center" label="总成号">-->
          <!--          <template slot-scope="scope">-->
          <!--            {{ scope.row.零件号 }}-->
          <!--          </template>-->
          <!--        </el-table-column>-->
          <el-table-column align="center" :label="$t('releaseOfProductionPlan.planQuantity')">
            <template slot-scope="scope">
              {{ scope.row.计划数量 }}
            </template>
          </el-table-column>
          <!--        <el-table-column align="center" label="完成数量">-->
          <!--          <template slot-scope="scope">-->
          <!--            {{ scope.row.完成数量 }}-->
          <!--          </template>-->
          <!--        </el-table-column>-->
          <!--        <el-table-column align="center" label="状态">-->
          <!--          <template slot-scope="scope">-->
          <!--            <el-tag v-if="parseInt(scope.row.订单状态) === 0" effect="plain" style="width: 70px" type="info">已结束</el-tag>-->
          <!--            <el-tag v-if="parseInt(scope.row.订单状态) === 1" effect="plain" style="width: 70px" type="success">生产中</el-tag>-->
          <!--            <el-tag v-if="parseInt(scope.row.订单状态) === 2" effect="plain" style="width: 70px" type="text">未上线</el-tag>-->
          <!--            <el-tag v-if="parseInt(scope.row.订单状态) === 3" effect="plain" style="width: 70px" type="warning">未完成</el-tag>-->
          <!--            <el-tag v-if="parseInt(scope.row.订单状态) === 4" effect="plain" style="width: 70px" type="danger">已超额</el-tag>-->
          <!--          </template>-->
          <!--        </el-table-column>-->
          <el-table-column align="center" :label="$t('releaseOfProductionPlan.planStartDate')">
            <template slot-scope="scope">
              {{ scope.row.计划开始时间 }}
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('releaseOfProductionPlan.planEndDate')">
            <template slot-scope="scope">
              {{ scope.row.计划完成时间 }}
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('releaseOfProductionPlan.productionStatus')">
            <template slot-scope="scope">
              <el-tag
                v-if="Number(scope.row.订单状态) === 1"
                size="mini"
                type="info"
              >{{ $t('releaseOfProductionPlan.notStarted') }}</el-tag>
              <el-tag
                v-if="Number(scope.row.订单状态) === 2"
                size="mini"
                type="warning"
              >{{ $t('releaseOfProductionPlan.inProduction') }}</el-tag>
              <el-tag
                v-if="Number(scope.row.订单状态) === 3"
                size="mini"
                type="success"
              >{{ $t('releaseOfProductionPlan.completed') }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('releaseOfProductionPlan.operation')" min-width="150">
            <template slot-scope="scope">
              <el-button
                v-if="parseInt(scope.row.订单状态) === 2"
                size="mini"
                type="text"
                icon="el-icon-check"
                @click="competeOrder(scope.row)"
              >{{ $t('releaseOfProductionPlan.completeOrder') }}</el-button>
              <el-button
                v-if="parseInt(scope.row.订单状态) === 1"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleEdit(scope.row)"
              >{{ $t('releaseOfProductionPlan.modify') }}</el-button>
              <el-button
                v-if="parseInt(scope.row.订单状态) === 1"
                size="mini"
                type="text"
                icon="el-icon-delete"
                style="color: red"
                @click="deleteOrder(scope.row)"
              >{{ $t('releaseOfProductionPlan.delete') }}</el-button>
              <el-button
                v-if="parseInt(scope.row.是否下发) === 0"
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="ordersIssuedEditor(scope.row)"
              >{{ $t('releaseOfProductionPlan.issue') }}</el-button>
              <el-button
                v-if="parseInt(scope.row.是否下发) === 1 && parseInt(scope.row.订单状态) === 1"
                size="mini"
                type="text"
                icon="el-icon-upload2"
                @click="ordersIssuedEditor1(scope.row)"
              >{{ $t('releaseOfProductionPlan.withdraw') }}</el-button>
              <el-button
                v-if="parseInt(scope.row.是否下发) === 0 && parseInt(scope.row.订单状态) === 1"
                size="mini"
                type="text"
                icon="el-icon-top"
                @click="topOrder(scope.row)"
              >{{ $t('releaseOfProductionPlan.moveUp') }}</el-button>
              <el-button
                v-if="parseInt(scope.row.是否下发) === 0 && parseInt(scope.row.订单状态) === 1"
                size="mini"
                type="text"
                icon="el-icon-bottom"
                @click="downOrder(scope.row)"
              >{{ $t('releaseOfProductionPlan.moveDown') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="block" style="margin-top: 10px">
        <el-pagination
          v-if="!loading"
          :current-page="pageCurrent"
          :page-sizes="[30, 50, 100]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="$t('releaseOfProductionPlan.createProductionOrder')"
      center
      style="min-height: 200px"
      width="400px"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-position="right"
        label-width="110px"
      >
        <el-form-item :label="$t('releaseOfProductionPlan.orderNumber')" prop="orderNumber" style="display: inline-block">
          <el-input v-model="form.orderNumber" clearable size="small" :placeholder="$t('releaseOfProductionPlan.enterOrderNumber')" />
        </el-form-item>
        <el-form-item
          :label="$t('releaseOfProductionPlan.productModel')"
          prop="engineTypeValue"
          style="display: inline-block"
        >
          <el-select
            v-model="form.engineTypeValue"
            size="small"
            filterable
            :placeholder="$t('releaseOfProductionPlan.selectProductModel')"
          >
            <el-option
              v-for="item in engineType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="总成号" prop="partCode" style="display: inline-block">-->
        <!--          <el-select v-model="form.partCode" size="small" filterable placeholder="请选择总成号">-->
        <!--            <el-option v-for="item in partCodeList" :key="item.value" :label="item.label" :value="item.value" />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item
          :label="$t('releaseOfProductionPlan.planQuantity')"
          prop="planQuantity"
          style="display: inline-block"
        >
          <el-input-number
            v-model="form.planQuantity"
            :min="1"
            :step="1"
            size="small"
            style="width: 200px"
            :placeholder="$t('releaseOfProductionPlan.enterPlanQuantity')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('releaseOfProductionPlan.planStartTime')"
          prop="startPlanTime"
          style="display: inline-block"
        >
          <el-date-picker
            v-model="form.startPlanTime"
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('releaseOfProductionPlan.selectStartTime')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('releaseOfProductionPlan.planEndTime')"
          prop="endPlanTime"
          style="display: inline-block"
        >
          <el-date-picker
            v-model="form.endPlanTime"
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('releaseOfProductionPlan.selectEndTime')"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOff('form')">{{ $t('common.cancel') }}</el-button>
        <el-button
          type="primary"
          size="small"
          @click="submitAdd('form')"
        >{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogFormVisible1"
      :title="$t('releaseOfProductionPlan.editProductionOrder')"
      center
      style="min-height: 200px"
      width="400px"
    >
      <el-form
        ref="form1"
        :model="form1"
        :rules="rules1"
        label-position="right"
        label-width="110px"
      >
        <el-form-item
          :label="$t('releaseOfProductionPlan.orderNumber')"
          prop="orderNumber"
          style="display: inline-block"
        >
          <el-input
            v-model="form1.orderNumber"
            readonly
            size="small"
            :placeholder="$t('releaseOfProductionPlan.enterOrderNumber')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('releaseOfProductionPlan.productModel')"
          prop="engineTypeValue"
          style="display: inline-block"
        >
          <el-input
            v-model="form1.engineTypeValue"
            readonly
            size="small"
            :placeholder="$t('releaseOfProductionPlan.productModel')"
          />
        </el-form-item>
        <!--<el-form-item label="总成号" prop="partCode" style="display: inline-block">-->
        <!--  <el-input v-model="form1.partCode" readonly size="small" placeholder="总成号" />-->
        <!--</el-form-item>-->
        <el-form-item
          :label="$t('releaseOfProductionPlan.planQuantity')"
          prop="planQuantity"
          style="display: inline-block"
        >
          <el-input-number
            v-model="form1.planQuantity"
            :min="1"
            :step="1"
            size="small"
            style="width: 200px"
            :placeholder="$t('releaseOfProductionPlan.enterPlanQuantity')"
          />
        </el-form-item>
        <!--        <el-form-item-->
        <!--          label="桥壳上线数"-->
        <!--          prop="planQuantity"-->
        <!--          style="display: inline-block"-->
        <!--        >-->
        <!--          <el-input-number-->
        <!--            v-model="form1.qiaoKeOverNumber"-->
        <!--            :min="0"-->
        <!--            :step="1"-->
        <!--            size="small"-->
        <!--            style="width: 200px"-->
        <!--            placeholder="请输入计划数量"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item-->
        <!--          label="轮毂上线数"-->
        <!--          prop="planQuantity"-->
        <!--          style="display: inline-block"-->
        <!--        >-->
        <!--          <el-input-number-->
        <!--            v-model="form1.lunGuOverNumber"-->
        <!--            :min="0"-->
        <!--            :step="1"-->
        <!--            size="small"-->
        <!--            style="width: 200px"-->
        <!--            placeholder="请输入计划数量"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item
          :label="$t('releaseOfProductionPlan.planStartTime')"
          prop="startPlanTime"
          style="display: inline-block"
        >
          <el-date-picker
            v-model="form1.startPlanTime"
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('releaseOfProductionPlan.selectStartTime')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('releaseOfProductionPlan.planEndTime')"
          prop="endPlanTime"
          style="display: inline-block"
        >
          <el-date-picker
            v-model="form1.endPlanTime"
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('releaseOfProductionPlan.selectEndTime')"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOff1()">{{ $t('common.cancel') }}</el-button>
        <el-button
          type="primary"
          size="small"
          @click="submitAdd1()"
        >{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogFormVisible3"
      :title="$t('releaseOfProductionPlan.orderImport')"
      center
      style="min-height: 200px"
      width="900px"
    >
      <div class="app-container">
        <upload-excel-component
          style="margin-left: 15%"
          @on-selected-file="selected"
        />
        <div style="margin-left: 395px">
          <span
            v-show="worksheet.length > 1"
            style="cursor: pointer; width: 50px"
            @click="removeAll"
          ><i
            class="el-icon-close"
          /></span>
          <el-upload
            :on-remove="handleRemove"
            :file-list="itemFile"
            style="width: 220px"
            action=""
          />
        </div>
        <div v-if="worksheet.length !== 0" style="margin: 3px 0 0 395px">
          <el-button
            icon="el-icon-upload2"
            type="primary"
            size="small"
            @click="basicPartsToSQL"
          >{{ $t('releaseOfProductionPlan.importToDatabase') }}</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogFormVisible4"
      :title="$t('releaseOfProductionPlan.printTransmissionBarcode')"
      center
      style="min-height: 200px"
      width="400px"
    >
      <el-form
        ref="printForm"
        :model="printForm"
        :rules="printRules"
        label-position="right"
        label-width="110px"
      >
        <el-form-item
          :label="$t('releaseOfProductionPlan.productModel')"
          prop="产品型号"
          style="display: inline-block"
        >
          <el-input
            v-model="printForm.产品型号"
            readonly
            size="small"
            :placeholder="$t('releaseOfProductionPlan.enterProductModel')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('releaseOfProductionPlan.assemblyNo')"
          prop="零件号"
          style="display: inline-block"
        >
          <el-input
            v-model="printForm.零件号"
            readonly
            size="small"
            :placeholder="$t('releaseOfProductionPlan.enterAssemblyNo')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('releaseOfProductionPlan.serialNo')"
          prop="起始号码"
          style="display: inline-block"
        >
          <el-input
            v-model="printForm.起始号码"
            :disabled="printCountPlanIsShow"
            size="small"
            :placeholder="$t('releaseOfProductionPlan.enterEightDigitSerialNo')"
            @blur="startKeyChange(printForm.起始号码)"
          />
          <!--          <el-input-number-->
          <!--            v-model="printForm.起始号码"-->
          <!--            :min="1"-->
          <!--            :step="1"-->
          <!--            size="small"-->
          <!--            style="width: 200px;"-->
          <!--            placeholder="请输入计划数量" />-->
        </el-form-item>
        <el-form-item
          :label="$t('releaseOfProductionPlan.printDate')"
          prop="打印日期"
          style="display: inline-block"
        >
          <el-date-picker
            v-model="printForm.打印日期"
            :disabled="printCountPlanIsShow"
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('releaseOfProductionPlan.selectPrintDate')"
            @change="getPrintDate"
          />
        </el-form-item>
        <el-form-item
          :label="$t('releaseOfProductionPlan.printQuantity')"
          prop="打印数量"
          style="display: inline-block"
        >
          <el-input-number
            v-model="printForm.打印数量"
            :disabled="printCountPlanIsShow"
            :min="1"
            :step="1"
            size="small"
            style="width: 200px"
            :placeholder="$t('releaseOfProductionPlan.enterPrintQuantity')"
          />
        </el-form-item>
        <div
          v-if="printCountPlanIsShow"
          style="text-align: center; color: #3c9445; font-size: 20px"
        >
          {{ $t('releaseOfProductionPlan.printProgress') }}{{ printCountPlan }} / {{ printForm.打印数量 }}
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOffPrint()">{{ $t('common.cancel') }}</el-button>
        <el-button
          :disabled="isAllowAddClike"
          type="primary"
          size="small"
          @click="submitAddPrint('printForm')"
        >{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UploadExcelComponent from './UploadExcel.vue'
import { sleep } from '../../../utils/tool'
// import { Mqtt } from '../../../utils/mqtt.js'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      expands: [],
      expandsDetail: [],
      mqttClient: null,
      mqttConnection: {
        host: window.g.mqttIP,
        port: window.g.mqttPortNumber,
        endpoint: '/mqtt',
        clean: true, // 保留会话
        connectTimeout: 4000, // 超时时间
        reconnectPeriod: 4000, // 重连时间间隔
        clientId: '', // 同一个ID 无法二次连接
        username: 'MES_Manager',
        password: '123456'
      },
      subscription: {
        topic: '',
        qos: 0
      },
      publication: {
        topic: '',
        qos: 0,
        payload: ''
      },
      worksheet: [],
      itemFile: [],
      unSpecification: [],
      method1: '', // 机床1加工方式
      method2: '', // 机床2加工方式
      method1Explain: '', // 机床1加工方式说明
      method2Explain: '', // 机床2加工方式说明
      stockQuantity: '', // 库存数量
      stockNum: '', // 库位号
      explain: false,
      orderNumber: [],
      orderNumberValue: '',
      OrderNumber_check: 0,
      engineTypeValue: '',
      engineType: [],
      partCodeList: [],
      OKWarehouseValue: '',
      OKWarehouse: [],
      NGWarehouseValue: '',
      NGWarehouse: [],
      engineType_check: 0,
      printForm: {
        // 创建订单
        订单号: '',
        零件号: '',
        产品型号: '',
        产品型号代码: '',
        起始号码: '',
        打印日期: '',
        打印数量: 1
      },
      printRules: {},
      form: {
        // 创建订单
        planQuantity: '',
        orderNumber: '',
        engineTypeValue: '',
        partCode: '123',
        startPlanTime: '',
        endPlanTime: '',
        quantityCompletion: ''
      },
      rules: {},
      form1: {
        // 修改订单
        planQuantity: '',
        orderNumber: '',
        engineTypeValue: '',
        startPlanTime: '',
        endPlanTime: '',
        partCode: '',
        quantityCompletion: 0,
        MID: '',
        rank: '',
        qiaoKeOverNumber: 0,
        lunGuOverNumber: 0
      },
      rules1: {},
      form2: {
        // 订单下发
        planQuantity: '',
        orderNumber: '',
        engineTypeValue: '',
        MID: '',
        IssuedQuantity: 1
      },
      rules2: {},
      form3: {
        // 订单下发
        planQuantity: '',
        orderNumber: '',
        engineTypeValue: '',
        MID: '',
        IssuedQuantity: 1
      },
      rules3: {},
      // planTime: [new Date(new Date().getTime() - 3600 * 1000 * 24 * 3000), new Date(new Date().getTime())],
      planTime: [],
      startPlanTime: '',
      startPlanTime_check: 0,
      endPlanTime: '',
      endPlanTime_check: 0,
      tableData: [],
      tableDataPrint: [],
      tableDataPrintDetail: [],
      importData: [],
      dialogFormVisible: false, // 创建订单
      dialogFormVisible1: false, // 修改订单
      dialogFormVisible3: false, // 订单导入
      dialogFormVisible4: false, // 打印
      isAllowAddClike: false, // 打印按钮是否禁用
      states: '', // 当前库存状态
      printCountPlan: 0, // 打印进度条
      printCountPlanIsShow: false, // 打印进度条是否显示
      MIDGroup: [],
      total: 0, // 总条数
      pageList: 30, // 每页显示条数
      pageSize: 30, // 每页显示条数
      pageCurrent: 1, // 后台获取页
      loading: false
    }
  },
  watch: {
    '$i18n.locale'() {
      this.initValidationRules()
    }
  },
  created() {
    this.initValidationRules()
    this.getOrderNumber()
    this.getEndStation()
    this.getPartCodeList()
    this.searchOrder()
  },
  mounted() {
    // if (window.g.mqttClient) {
    //   window.g.mqttClient.destroyConnection()
    // }
    // this.mqttConnection.username = 'MES_Manager_Plan'
    // window.g.mqttClient = new Mqtt(this.mqttConnection)
    // window.g.mqttClient.createConnection()
    // window.g.mqttClient.client.on('connect', () => {
    //   console.log('MQTT Connection succeeded!')
    // })
    // // 使用过程中的报错 断开连接 服务端出问题
    // window.g.mqttClient.client.on('error', error => {
    //   console.log('Connection failed', error)
    // })
    // window.g.mqttClient.client.on('message', (topic, message) => {
    //   console.log('Received message:', topic, message.toString())
    // })
  },
  beforeDestroy() {
    // if (window.g.mqttClient.client.connected) {
    //   const destroyConnection = window.g.mqttClient.destroyConnection()
    //   if (destroyConnection) {
    //     this.$message({
    //       message: 'MQTT断开成功！',
    //       type: 'success'
    //     })
    //   } else {
    //     this.$message({
    //       message: 'MQTT断开失败！',
    //       type: 'error'
    //     })
    //   }
    // }
  },
  methods: {
    initValidationRules() {
      this.printRules = {
        零件号: [{ required: true, message: this.$t('releaseOfProductionPlan.enterAssemblyNoRequired'), trigger: 'blur' }],
        订单号: [{ required: true, message: this.$t('releaseOfProductionPlan.enterOrderNumberRequired'), trigger: 'blur' }],
        产品型号: [{ required: true, message: this.$t('releaseOfProductionPlan.enterProductModelRequired'), trigger: 'blur' }],
        起始号码: [{ required: true, min: 8, message: this.$t('releaseOfProductionPlan.serialNoMinLength'), trigger: 'blur' }],
        打印日期: [{ required: true, message: this.$t('releaseOfProductionPlan.selectPrintDateRequired'), trigger: 'blur' }],
        打印数量: [{ required: true, message: this.$t('releaseOfProductionPlan.enterPrintQuantityRequired'), trigger: 'blur' }]
      }
      this.rules = {
        planQuantity: [{ required: true, message: this.$t('releaseOfProductionPlan.enterPlanQuantityRequired'), trigger: 'blur' }],
        orderNumber: [{ required: true, message: this.$t('releaseOfProductionPlan.enterOrderNumberRequired'), trigger: 'blur' }],
        engineTypeValue: [{ required: true, message: this.$t('releaseOfProductionPlan.selectEngineTypeRequired'), trigger: 'blur' }],
        partCode: [{ required: true, message: this.$t('releaseOfProductionPlan.selectAssemblyNoRequired'), trigger: 'blur' }],
        startPlanTime: [{ required: true, message: this.$t('releaseOfProductionPlan.selectPlanStartTimeRequired'), trigger: 'blur' }],
        endPlanTime: [{ required: true, message: this.$t('releaseOfProductionPlan.selectPlanEndTimeRequired'), trigger: 'blur' }],
        quantityCompletion: [{ required: true, message: this.$t('releaseOfProductionPlan.enterPlannedCompletionRequired'), trigger: 'blur' }]
      }
      this.rules1 = {
        planQuantity: [{ required: true, message: this.$t('releaseOfProductionPlan.enterPlanQuantityRequired'), trigger: 'blur' }],
        partCode: [{ required: true, message: this.$t('releaseOfProductionPlan.selectAssemblyNoRequired'), trigger: 'blur' }],
        startPlanTime: [{ required: true, message: this.$t('releaseOfProductionPlan.selectPlanStartTimeRequired'), trigger: 'blur' }],
        endPlanTime: [{ required: true, message: this.$t('releaseOfProductionPlan.selectPlanEndTimeRequired'), trigger: 'blur' }],
        quantityCompletion: [{ required: true, message: this.$t('releaseOfProductionPlan.enterPlannedCompletionRequired'), trigger: 'blur' }]
      }
      this.rules2 = {
        planQuantity: [{ required: true, message: this.$t('releaseOfProductionPlan.enterPlanQuantityRequired'), trigger: 'blur' }],
        orderNumber: [{ required: true, message: this.$t('releaseOfProductionPlan.enterOrderNumberRequired'), trigger: 'blur' }],
        engineTypeValue: [{ required: true, message: this.$t('releaseOfProductionPlan.selectEngineTypeRequired'), trigger: 'blur' }],
        IssuedQuantity: [{ required: true, message: this.$t('releaseOfProductionPlan.enterIssuedQuantityRequired'), trigger: 'blur' }]
      }
      this.rules3 = {
        planQuantity: [{ required: true, message: this.$t('releaseOfProductionPlan.enterPlanQuantityRequired'), trigger: 'blur' }],
        orderNumber: [{ required: true, message: this.$t('releaseOfProductionPlan.enterOrderNumberRequired'), trigger: 'blur' }],
        engineTypeValue: [{ required: true, message: this.$t('releaseOfProductionPlan.selectEngineTypeRequired'), trigger: 'blur' }],
        IssuedQuantity: [{ required: true, message: this.$t('releaseOfProductionPlan.enterIssuedQuantityRequired'), trigger: 'blur' }]
      }
    },
    buildOrderConfirmHtml(messageKey, orderNo) {
      return this.$t(messageKey, {
        orderNo: `<p style="color: deepskyblue;display: inline-block"> ${orderNo}</p>`
      })
    },
    printShow(row) {
      this.printForm.订单号 = row.订单号
      this.printForm.产品型号 = row.产品型号
      this.printForm.产品型号代码 = row.机型代码
      this.printForm.零件号 = row.零件号
      this.printForm.打印日期 = this.getNowFormatDate()
      this.printForm.打印数量 = 1
      this.dialogFormVisible4 = true
    },
    removeAll() {
      this.worksheet = []
      this.itemFile = []
    },
    async selected(data) {
      // 选择需要导入的文件
      console.log(data, 1111)
      this.worksheet = data.worksheet // 获取每个多选文件的表格坐标及值
      this.itemFile = data.itemFile
    },
    handleRemove(file) {
      // 移除文件
      for (let i = 0; i < this.itemFile.length; i++) {
        if (this.itemFile[i].name === file.name) {
          this.worksheet.splice(i, 1)
          this.itemFile.splice(i, 1)
        }
      }
    },
    /* 验证内容是否英文数字以及下划线*/
    // isPassword(rule, value, callback) {
    //   const reg = /^[_a-zA-Z0-9]+$/
    //   if (value === '' || value === undefined || value == null) {
    //     callback()
    //   } else {
    //     if (!reg.test(value) || value.length !== 7) {
    //       callback(new Error('订单仅由数字和字母组成，且只能位7位'))
    //     } else {
    //       callback()
    //     }
    //   }
    // },
    // 初始化获取产品型号
    getEndStation() {
      this.engineType = []
      var param = []
      var Data = this.CreateData('11', 'MES_基本变量_机型代码_查询', param)
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          this.engineType.push({
            label: response.data[i].发动机型号,
            value: response.data[i].发动机型号
          })
        }
      })
    },
    // 日期框点击事件
    getPrintDate(date) {
      this.printForm.打印日期 = date
    },
    // 获取当前日期函数
    getNowFormatDate() {
      const date = new Date()
      const year = date.getFullYear() // 获取完整的年份(4位)
      let month = date.getMonth() + 1 // 获取当前月份(0-11,0代表1月)
      let strDate = date.getDate() // 获取当前日(1-31)
      if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
      if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0

      return `${year}-${month}-${strDate}`
    },
    // 初始化获取产品型号
    getPartCodeList() {
      this.partCodeList = []
      var param = []
      param[0] = ['基本机型', this.form.engineTypeValue]
      var Data = this.CreateData('11', '北汽福田订单创建零件号_查询', param)
      this.ExecDatabase(Data).then((response) => {
        if (response.data.length === 0) {
          this.$message({
            type: 'error',
            message: this.$t('releaseOfProductionPlan.noPartCodeForModel')
          })
          return false
        } else {
          for (let i = 0; i < response.data.length; i++) {
            this.partCodeList.push({
              label: response.data[i].零件号,
              value: response.data[i].零件号
            })
          }
          this.form.partCodeValue = this.partCodeList[0].value
        }
      })
    },
    // 初始化获取订单号
    getOrderNumber() {
      this.orderNumber = []
      var param = []
      param[0] = ['开始时间', this.planTime[0]]
      param[1] = ['结束时间', this.planTime[1]]
      var Data = this.CreateData('11', '订单计划_订单号_查询', param)
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          this.orderNumber.push({
            label: response.data[i].订单号,
            value: response.data[i].订单号
          })
        }
      })
    },
    // 控制展开列
    selectPlan(row, expandedRows) {
      if (expandedRows.length) {
        this.expands = []
        this.expandsDetail = []
        if (row) {
          this.tableDataPrint = []
          var param = []
          param[0] = ['工单号', row.订单号]
          var Data = this.CreateData(
            '11',
            '生产计划_派工订单_打印_查询',
            param
          )
          this.ExecDatabase(Data).then((response) => {
            console.log(response.data)
            if (response.data.length !== 0) {
              this.tableDataPrint = response.data
            }
            this.expands.push(row.订单号)
          })

          this.tableDataPrintDetail = []
          var Data2 = this.CreateData(
            '11',
            '生产计划_派工订单_打印详细_查询',
            param
          )
          this.ExecDatabase(Data2).then((response) => {
            console.log(response.data)
            if (response.data.length !== 0) {
              this.tableDataPrintDetail = response.data
            }
            this.expandsDetail.push(row.订单号)
          })
        }
      } else {
        this.expands = []
        this.expandsDetail = []
      }
    },
    // 获取展开列的工单号
    getRowKeys(row) {
      return row.订单号
    },
    // 查询订单
    searchOrder() {
      this.expands = []
      this.tableData = []
      this.startPlanTime
        ? (this.startPlanTime_check = 1)
        : (this.startPlanTime_check = 0)
      this.endPlanTime
        ? (this.endPlanTime_check = 1)
        : (this.endPlanTime_check = 0)
      this.orderNumberValue
        ? (this.OrderNumber_check = 1)
        : (this.OrderNumber_check = 0)
      this.engineTypeValue
        ? (this.engineType_check = 1)
        : (this.engineType_check = 0)
      if (this.startPlanTime === null) {
        this.startPlanTime = ''
      }
      if (this.endPlanTime === null) {
        this.endPlanTime = ''
      }
      var param = []
      param[0] = ['计划开始时间_check', this.startPlanTime_check]
      param[1] = ['计划开始时间', this.startPlanTime]
      param[2] = ['计划完成时间_check', this.endPlanTime_check]
      param[3] = ['计划完成时间', this.endPlanTime]
      param[4] = ['订单号_check', this.OrderNumber_check]
      param[5] = ['订单号', this.orderNumberValue]
      param[6] = ['产品型号_check', this.engineType_check]
      param[7] = ['产品型号', this.engineTypeValue]
      param[8] = ['PageCurrent', this.pageCurrent]
      param[9] = ['PageSize', this.pageSize]
      param[10] = ['PageCount', '1111', 'int', '1']
      param[11] = ['ItemCount', '1111', 'int', '1']
      var Data = this.CreateData(
        '11',
        'MES_计划BOM_发动机订单计划_查询分页',
        param
      )
      this.ExecDatabase(Data).then((response) => {
        if (response.data.result.length !== 0) {
          this.tableData = response.data.result
        }
        this.total = parseInt(response.data.output[0].ItemCount)
        this.loading = false
      })
    },
    // 创建订单
    creatOrder(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
      this.form.planQuantity = ''
      this.form.orderNumber = ''
      this.form.startPlanTime = ''
      this.form.endPlanTime = ''
      this.dialogFormVisible = true
    },
    // 提交新增订单
    submitAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var param = []
          param[0] = ['订单号', this.form.orderNumber]
          param[1] = ['产品型号', this.form.engineTypeValue]
          param[2] = ['开始时间', this.form.startPlanTime]
          param[3] = ['结束时间', this.form.endPlanTime]
          param[4] = ['数量', this.form.planQuantity]
          var Data = this.CreateData(
            '12',
            'MES_计划BOM_发动机订单计划_订单手动增加',
            param
          )
          this.ExecDatabase(Data).then((response) => {
            if (response.data[0].result === '1') {
              this.$message({
                message: this.$t('releaseOfProductionPlan.orderCreateSuccess'),
                type: 'success'
              })
              this.pageCurrent = 1
              this.pageSize = 30
              this.searchOrder()
            } else if (response.data[0].result.结果 === '2') {
              this.$message.error(this.$t('releaseOfProductionPlan.orderDuplicateCreateFailed'))
            } else {
              this.$message.error(this.$t('releaseOfProductionPlan.orderCreateFailed'))
            }
          })
          this.dialogFormVisible = false
        } else {
          return false
        }
      })
    },
    submitAddPrint(formName) {
      if (this.printForm.起始号码.length < 8) return
      this.$refs[formName].validate((valid) => {
        const scope = this
        var param = []
        param[0] = ['工单号', this.printForm.订单号]
        param[1] = ['零件号', this.printForm.零件号]
        param[2] = ['打印起始号', this.printForm.起始号码]
        param[3] = ['打印数量', this.printForm.打印数量]
        param[4] = ['打印日期', this.printForm.打印日期]
        var Data = this.CreateData('12', '生产计划_派工订单_打印_增加', param)
        this.ExecDatabase(Data).then((response) => {
          if (response.data[0].result === '1') {
            this.$message({
              message: this.$t('releaseOfProductionPlan.startPrintingTransmissionBarcode'),
              type: 'success'
            })
            // 置空进度条进度
            this.printCountPlan = 0
            this.printCountPlanIsShow = true
            this.searchPrintListFinal()
            const printPartCode = this.printForm.零件号
            const printTemplate = window.g.printTemplate
            const printStartNum = parseInt(this.printForm.起始号码)
            const printDate =
              typeof this.printForm.打印日期 === 'string'
                ? new Date(this.printForm.打印日期)
                : this.printForm.打印日期
            const printCount = this.printForm.打印数量
            const printDateFinal =
              printDate.getFullYear() +
              '' +
              (printDate.getMonth() + 1 >= 10
                ? printDate.getMonth() + 1
                : '0' + (printDate.getMonth() + 1)) +
              '' +
              (printDate.getDate() >= 10
                ? printDate.getDate()
                : '0' + printDate.getDate())
            for (let i = 0; i < printCount; i++) {
              (function(t) {
                // 注意这里是形参
                setTimeout(function() {
                  const printCountFinal = (printStartNum + t)
                    .toString()
                    .padStart(8, '0')
                  const printFinal =
                    printPartCode.replaceAll(' ', '') +
                    '*' +
                    printDateFinal +
                    '*' +
                    printCountFinal
                  scope.publication.topic = window.g.mqttPublishTopic
                  scope.publication.payload = `J07MA000~1~${printTemplate}|BarCode^Code0^${printFinal}|TEXT^TEXT0^${printFinal}`
                  const result = window.g.mqttClient.doPublish(
                    scope.publication
                  )
                  console.log(result, printFinal)
                  scope.submitAddPrintList(
                    scope.printForm.订单号,
                    scope.printForm.产品型号,
                    scope.printForm.产品型号代码,
                    scope.printForm.零件号,
                    printFinal
                  )
                }, 100 * t)
              })(i)
            }
          } else {
            this.$message.error(this.$t('releaseOfProductionPlan.printTransmissionBarcodeFailed'))
          }
        })
      })
    },
    // 判断起始号是否重复打印
    startKeyChange() {
      var param = []
      param[0] = ['起始号', this.printForm.起始号码]
      param[1] = ['机型', this.printForm.产品型号]
      var Data = this.CreateData(
        '11',
        '生产计划_派工订单_打印记录_是否重复_查询',
        param
      )
      this.ExecDatabase(Data).then((response) => {
        if (response.data[0].result === 2) {
          this.$message.error(response.data[0].msg)
          this.isAllowAddClike = true
        } else {
          this.isAllowAddClike = false
        }
      })
    },
    // 提交新增订单
    submitAddPrintList(
      orderCode,
      engineType,
      engineTypeValue,
      partCode,
      engineId
    ) {
      var param = []
      param[0] = ['订单号', orderCode]
      param[1] = ['零件号', partCode]
      param[2] = ['变速箱总成号', engineId]
      param[3] = ['机型代码', engineTypeValue]
      param[4] = ['机型', engineType]
      var Data = this.CreateData(
        '12',
        '生产计划_派工订单_打印记录_增加',
        param
      )
      this.ExecDatabase(Data).then((response) => {
        if (response.data[0].result === '1') {
          // this.$message({
          //   message: '订记录成功',
          //   type: 'success'
          // })
          this.printCountPlan++
          if (this.printCountPlan === Number(this.printForm.打印数量)) {
            this.$message({
              message: this.$t('releaseOfProductionPlan.allBarcodesPrinted'),
              type: 'success'
            })
            // 关闭进度条 关闭打印窗口
            this.printCountPlanIsShow = false
            this.dialogFormVisible4 = false
          }
        } else {
          this.$message.error(this.$t('releaseOfProductionPlan.recordFailed'))
        }
      })
    },
    callOffPrint() {
      this.searchPrintListFinal()
      this.dialogFormVisible4 = false
    },
    searchPrintListFinal() {
      this.tableDataPrint = []
      const param = []
      param[0] = ['工单号', this.printForm.订单号]
      const Data = this.CreateData('11', '生产计划_派工订单_打印_查询', param)
      this.ExecDatabase(Data).then((response) => {
        if (response.data.length !== 0) {
          this.tableDataPrint = response.data
        }
      })
    },
    // 取消新增订单
    callOff(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    // 导入订单
    importOrder() {
      this.dialogFormVisible3 = true
    },
    // 删除订单
    deleteOrder(row) {
      this.$confirm(this.$t('releaseOfProductionPlan.confirmDeleteOrder'), this.$t('releaseOfProductionPlan.prompt'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      })
        .then(() => {
          var param = []
          param[0] = ['MID', row.MID]
          var Data = this.CreateData('12', '订单计划_删除', param)
          this.ExecDatabase(Data).then((response) => {
            if (response.data[0].result === '1') {
              this.$message({
                message: this.$t('releaseOfProductionPlan.orderDeleteSuccess'),
                type: 'success'
              })
              this.pageCurrent = 1
              this.pageSize = 30
              this.searchOrder()
            } else {
              this.$message.error(this.$t('releaseOfProductionPlan.orderDeleteFailed'))
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('releaseOfProductionPlan.deleteCanceled')
          })
        })
    },
    // 修改订单
    handleEdit(row) {
      if (this.$refs['form1'] !== undefined) {
        this.$refs['form1'].resetFields()
      }
      console.log(row)
      this.form1.planQuantity = row.计划数量
      this.form1.orderNumber = row.订单号
      this.form1.partCode = row.零件号
      this.form1.startPlanTime = row.计划开始时间
      this.form1.endPlanTime = row.计划完成时间
      this.form1.quantityCompletion = row.完成数量
      this.form1.engineTypeValue = row.产品型号
      this.form1.rank = row.排序
      this.form1.MID = row.MID
      this.form1.qiaoKeOverNumber = row.总装上线
      this.form1.lunGuOverNumber = row.测试上线
      this.dialogFormVisible1 = true
    },
    // 提交修改订单
    submitAdd1() {
      this.$refs['form1'].validate((valid) => {
        if (valid) {
          var param = []
          param[0] = ['开始时间', this.form1.startPlanTime]
          param[1] = ['结束时间', this.form1.endPlanTime]
          param[2] = ['数量', this.form1.planQuantity]
          param[3] = ['MID', this.form1.MID]
          var Data = this.CreateData('12', 'MES_计划BOM_发动机订单计划_订单修改', param)
          this.ExecDatabase(Data).then((response) => {
            if (response.data[0].result === '1') {
              this.$message({
                message: this.$t('releaseOfProductionPlan.orderEditSuccess'),
                type: 'success'
              })
              this.pageCurrent = 1
              this.pageSize = 30
              this.searchOrder()
            } else {
              this.$message.error(response.data[0].msg)
            }
          })
          this.dialogFormVisible1 = false
        } else {
          return false
        }
      })
    },
    // 取消修改订单
    callOff1() {
      this.dialogFormVisible1 = false
      this.$refs['form1'].resetFields()
    },
    // 多选
    handleSelectionChange(val) {
      this.MIDGroup = []
      for (let i = 0; i < val.length; i++) {
        this.MIDGroup.push(val[i].MID)
      }
    },
    // 订单下发编辑
    ordersIssuedEditor(row) {
      this.$confirm(
        this.buildOrderConfirmHtml('releaseOfProductionPlan.confirmIssueOrder', row.订单号),
        this.$t('releaseOfProductionPlan.prompt'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      ).then(() => {
        var param = []
        param[0] = ['MID', row.MID]
        var Data = this.CreateData(
          '12',
          'MES_计划BOM_发动机订单计划_订单下发',
          param
        )
        this.ExecDatabase(Data).then((response) => {
          if (response.data[0].result === '1') {
            this.$message({
              message: this.$t('releaseOfProductionPlan.orderIssueSuccess'),
              type: 'success'
            })
            this.pageCurrent = 1
            this.pageSize = 30
            this.searchOrder()
          } else {
            this.$message.error(this.$t('releaseOfProductionPlan.orderIssueFailed'))
          }
        })
      })
    },
    // 取消下发编辑
    ordersIssuedEditor1(row) {
      this.$confirm(
        this.buildOrderConfirmHtml('releaseOfProductionPlan.confirmWithdrawOrder', row.订单号),
        this.$t('releaseOfProductionPlan.prompt'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      ).then(() => {
        var param = []
        param[0] = ['MID', row.MID]
        var Data = this.CreateData(
          '12',
          'MES_计划BOM_发动机订单计划_订单下发取消',
          param
        )
        this.ExecDatabase(Data).then((response) => {
          if (response.data[0].result === '1') {
            this.$message({
              message: this.$t('releaseOfProductionPlan.orderWithdrawSuccess'),
              type: 'success'
            })
            this.pageCurrent = 1
            this.pageSize = 30
            this.searchOrder()
          } else {
            this.$message.error(this.$t('releaseOfProductionPlan.orderWithdrawFailed'))
          }
        })
      })
    },
    handleAdd() {
      if (this.tableData.length === 0) {
        this.$message.error(this.$t('releaseOfProductionPlan.contentEmpty'))
      } else {
        var param = []
        var Data = this.CreateData('11', '确认导入物料字典_新增', param)
        this.ExecDatabase(Data).then((response) => {
          if (response.data.length > 0) {
            this.notes = ''
            for (var i = 0; i < response.data.length; i++) {
              this.notes = response.data[i].导入结果 + '、 ' + this.notes
            }
            this.$message({
              message: this.$t('releaseOfProductionPlan.materialDictionaryUpdated'),
              type: 'warning'
            })
            this.isShow = true
            this.tableData = []
          } else {
            this.tableData = []
            this.$message({
              message: this.$t('releaseOfProductionPlan.materialDictionaryUpdated'),
              type: 'success'
            })
          }
        })
      }
    },
    // 查询
    searchTable() {
      var param = []
      var Data = this.CreateData(
        '11',
        '生产计划导入_确认导入前临时表_查询',
        param,
        this.pageSize,
        this.pageList
      )
      this.ExecDatabase(Data).then((response) => {
        console.log(response.data)
        this.tableData = response.data.rows
        this.total = response.data.total
        this.loading = false
      })
    },
    // 表格颜色变化
    tableRowClassName({ row, rowIndex }) {
      // console.log(row, rowIndex)
      if (rowIndex % 2 === 0) {
        return 'black'
      } else {
        return 'red'
      }
    },
    async basicPartsToSQL() {
      try {
        this.loading = true
        this.err = 0
        for (let j = this.worksheet.length - 1; j >= 0; j--) {
          let sort, orderNumber, productModel, numberPlan, startDate, endDate
          var param = []
          param[0] = ['订单号', this.worksheet[j].B2.v]
          console.log('订单号', this.worksheet[j].B2.v)
          var Data = this.CreateData(
            '11',
            'MES_计划BOM_发动机订单计划_订单导入校验',
            param
          )
          const response = await this.ExecDatabase(Data)
          const res = response.data
          if (res[0].Column1 !== 0) {
            this.$notify.error(
              this.$t('releaseOfProductionPlan.alreadyExistsCheckFile', {
                name: this.worksheet[j].C2.v
              })
            )
            this.loading = false
            this.disabled = false
            return
          } else {
            for (let i = 0; i < 999; i++) {
              const attr = i + 2
              sort = this.worksheet[j][`A${attr}`]
                ? this.worksheet[j][`A${attr}`].v
                : ''
              orderNumber = this.worksheet[j][`B${attr}`]
                ? this.worksheet[j][`B${attr}`].v
                : ''
              productModel = this.worksheet[j][`C${attr}`]
                ? this.worksheet[j][`C${attr}`].v
                : ''
              numberPlan = this.worksheet[j][`D${attr}`]
                ? this.worksheet[j][`D${attr}`].v
                : ''
              startDate = this.worksheet[j][`E${attr}`]
                ? this.worksheet[j][`E${attr}`].v
                : ''
              endDate = this.worksheet[j][`F${attr}`]
                ? this.worksheet[j][`F${attr}`].v
                : ''
              console.log(
                sort,
                orderNumber,
                productModel,
                numberPlan,
                startDate,
                endDate
              )
              if (
                !sort &&
                !orderNumber &&
                !productModel &&
                !numberPlan &&
                !startDate &&
                !endDate
              ) {
                break
              } else if (!orderNumber) {
                // 名称不能为空
                this.$notify.error(this.$t('releaseOfProductionPlan.orderNumberRequired'))
                break
              } else if (Number(numberPlan) <= 0) {
                // 数量不能为0
                this.$notify.error(this.$t('releaseOfProductionPlan.planQuantityRequired'))
                break
              } else {
                if (orderNumber) {
                  await sleep(50)
                  await this.insertToSQL(
                    sort,
                    orderNumber,
                    productModel,
                    numberPlan,
                    startDate,
                    endDate
                  )
                } else {
                  this.loading = false
                  this.disabled = false
                  this.$notify.error(this.$t('releaseOfProductionPlan.confirmImportFile'))
                  return
                }
              }
            }
          }
          this.itemFile.splice(j, 1)
          this.worksheet.splice(j, 1)
          this.err === 0
            ? this.$message.success(this.$t('releaseOfProductionPlan.importCompleted'))
            : this.$message.error(
              this.$t('releaseOfProductionPlan.importFailedCount', {
                count: this.err
              })
            )
        }
        this.loading = false
        this.searchOrder()
      } catch (e) {
        this.err++
        this.loading = false
        this.$notify.error(this.$t('releaseOfProductionPlan.importDataErrorFile'))
        console.log(`导入数据错误${e}`)
      }
    },
    async insertToSQL(
      sort,
      orderNumber,
      productModel,
      numberPlan,
      startDate,
      endDate
    ) {
      console.log(startDate, endDate, 'startDate, endDate')
      try {
        var param = []
        param[0] = ['排序', sort]
        param[1] = ['订单号', orderNumber]
        param[2] = ['产品型号', productModel]
        param[3] = ['计划数量', numberPlan]
        param[4] = ['计划开始时间', startDate]
        param[5] = ['计划完成时间', endDate]
        param[6] = ['导入类型', '1', 'int', '1']
        var Data = this.CreateData(
          '12',
          'MES_计划BOM_发动机订单计划_订单导入',
          param
        )
        const response = await this.ExecDatabase(Data)
        const res = response.data
        if (Object.prototype.hasOwnProperty.call(res, 'output') === false) {
          if (res[0].result === '0') {
            this.$notify.error(this.$t('releaseOfProductionPlan.importFailedSuffix', { value: orderNumber }))
          }
        } else {
          if (res.result[0].result === '0') {
            this.$notify.error(this.$t('releaseOfProductionPlan.importFailedSuffix', { value: numberPlan }))
          }
          if (res.output[0].导入类型 === '2') {
            this.$notify.warning(this.$t('releaseOfProductionPlan.duplicateDataSuffix', { value: numberPlan }))
          }
        }
      } catch (e) {
        this.err++
        this.$message.error(this.$t('releaseOfProductionPlan.importDataError'))
        console.log(`导入数据错误${e}`)
      }
    },
    exportExcel() {
      if (this.tableData.length !== 0) {
        this.startPlanTime
          ? (this.startPlanTime_check = 1)
          : (this.startPlanTime_check = 0)
        this.endPlanTime
          ? (this.endPlanTime_check = 1)
          : (this.endPlanTime_check = 0)
        this.orderNumberValue
          ? (this.OrderNumber_check = 1)
          : (this.OrderNumber_check = 0)
        this.engineTypeValue
          ? (this.engineType_check = 1)
          : (this.engineType_check = 0)
        if (this.startPlanTime === null) {
          this.startPlanTime = ''
        }
        if (this.endPlanTime === null) {
          this.endPlanTime = ''
        }
        var param = []
        param[0] = ['计划开始时间_check', this.startPlanTime_check]
        param[1] = ['计划开始时间', this.startPlanTime]
        param[2] = ['计划完成时间_check', this.endPlanTime_check]
        param[3] = ['计划完成时间', this.endPlanTime]
        param[4] = ['订单号_check', this.OrderNumber_check]
        param[5] = ['订单号', this.orderNumberValue]
        param[6] = ['产品型号_check', this.engineType_check]
        param[7] = ['产品型号', this.engineTypeValue]
        var Data = this.CreateData(
          '2001',
          'MES_计划BOM_发动机订单计划_订单导出',
          param
        )
        this.exportExcel_NPOI(Data)
      } else {
        this.$message.warning(this.$t('releaseOfProductionPlan.noData'))
      }
    },
    // 上移订单
    topOrder(row) {
      if (row.MID) {
        var param = []
        param[0] = ['id', row.MID]
        console.log(param)
        var Data = this.CreateData('11', 'MES_计划BOM_发动机订单计划_订单上移', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === 1) {
            this.$message({
              message: response.data[0].msg,
              type: 'success'
            })
            this.searchOrder()
          } else {
            this.$message.error(response.data[0].msg)
          }
        })
      } else {
        this.$message.error(this.$t('releaseOfProductionPlan.selectOrder'))
      }
    },
    // 下移订单
    downOrder(row) {
      if (row.MID) {
        var param = []
        param[0] = ['id', row.MID]
        console.log(param)
        var Data = this.CreateData('11', 'MES_计划BOM_发动机订单计划_订单下移', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === 1) {
            this.$message({
              message: response.data[0].msg,
              type: 'success'
            })
            this.searchOrder()
          } else {
            this.$message.error(response.data[0].msg)
          }
        })
      } else {
        this.$message.error(this.$t('releaseOfProductionPlan.selectOrder'))
      }
    },
    // 订单完成
    competeOrder(row) {
      this.$confirm(
        this.buildOrderConfirmHtml('releaseOfProductionPlan.confirmCompleteOrder', row.订单号),
        this.$t('releaseOfProductionPlan.prompt'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning',
          dangerouslyUseHTMLString: true
        })
        .then(() => {
          var param = []
          param[0] = ['MID', row.MID]
          param[1] = ['type', 3]
          var Data = this.CreateData('12', 'MES_计划BOM_发动机订单计划_状态修改', param)
          this.ExecDatabase(Data).then((response) => {
            if (response.data[0].result === '1') {
              this.$message({
                message: this.$t('releaseOfProductionPlan.orderDeleteSuccess'),
                type: 'success'
              })
              this.pageCurrent = 1
              this.pageSize = 30
              this.searchOrder()
            } else {
              this.$message.error(this.$t('releaseOfProductionPlan.orderDeleteFailed'))
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('releaseOfProductionPlan.deleteCanceled')
          })
        })
    },
    // 分页
    handleSizeChange(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.expands = []
      this.searchOrder()
    },
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.expands = []
      this.searchOrder()
    }
  }
}
</script>

<style scoped>
.topCard {
  margin: 5px;
}

.topDiv {
  margin-bottom: 10px;
}

.topToolbar {
  align-items: center;
}

.tablePanel {
  padding: 4px 2px 0;
  border-radius: 14px;
  background: linear-gradient(180deg, rgba(255,255,255,0.55) 0%, rgba(244,248,252,0.92) 100%);
}

.el-select {
  width: 200px;
}

.el-input {
  width: 200px;
}

.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  position: absolute;
  right: 6px;
  top: 80px;
  width: 300px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

::v-deep .topToolbar .el-button {
  margin-bottom: 2px;
}

::v-deep .tablePanel .el-table__expanded-cell {
  background: #f8fbfe !important;
}
</style>
