<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="margin-left: 10px">订单号：</span>
        <el-select v-model="orderNumberValue" clearable placeholder="请选择订单" size="small" style="width: 150px">
          <el-option v-for="item in orderNumber" :key="item.value" :label="item.label" :value="item.value"
            size="mini" />
        </el-select>
        <span style="margin-left: 10px">产品型号：</span>
        <el-select v-model="engineTypeValue" clearable placeholder="请选择产品型号" 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">生产类型：</span>
        <el-input v-model="workType" clearable placeholder="生产类型" size="small" style="width: 150px" />
        <span style="margin-left: 10px">开始日期：</span>
        <el-date-picker v-model="startPlanTime" placeholder="选择开始日期" size="small" type="date"
          value-format="yyyy-MM-dd" />
        <span style="margin-left: 10px">结束日期：</span>
        <el-date-picker v-model="endPlanTime" placeholder="选择结束日期" size="small" type="date" value-format="yyyy-MM-dd" />
        <el-button icon="el-icon-search" plain size="small" style="margin-left: 10px" type="primary"
          @click="pageSize = 30; pageCurrent = 1; searchOrder()">查询订单
        </el-button>
        <el-button icon="el-icon-circle-plus" size="small" type="distribution" @click="creatOrder('form')">创建订单
        </el-button>

        <!-- <el-button icon="el-icon-s-release" size="small" type="distribution" style="float: right"
          @click="viewModifyOrder()">强制下线记录
        </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>
      <el-table v-loading="loading" ref="multipleTable" :cell-class-name="tableRowClassName" :data="tableData"
        :expand-row-keys="expandsDetail" :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        :row-key="getRowKeys" border class="main" element-loading-background="rgba(0, 0, 0, 0.2)"
        element-loading-spinner="el-icon-loading" element-loading-text="数据加载中" height="800px" size="mini"
        style="width: 100%;max-height: 700px" tooltip-effect="dark" @expand-change="selectPlan"
        @selection-change="handleSelectionChange">
        <el-table-column align="center" label="排序" prop="排序" width="60" />
        <el-table-column align="center" fixed label="" type="expand" width="35">
          <template slot-scope="scope">
            <div style="display: flex">
              <!-- 详细数据盒子 -->
              <div style="margin: 5px 10px;width: 1400px;z-index: 99;">
                <h4 style="margin: 5px 0; color: #606266;">工序任务进度</h4>
                <el-table :data="tableDataWorkProcess" :header-cell-style="{ background: '#f0f2f5', color: '#606266' }"
                  border class="main" max-height="300px" size="mini" style="width: 100%;" tooltip-effect="dark">
                  <el-table-column align="center" label="任务ID" prop="任务ID" width="300" />
                  <el-table-column align="center" label="工序编号" prop="工序编号" width="100" />
                  <el-table-column align="center" label="工序名称" prop="工序名称" min-width="150" />
                  <el-table-column align="center" label="到达时间" prop="到达时间" width="150">
                    <template slot-scope="scope">
                      {{ scope.row.到达时间 || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="离开时间" prop="离开时间" width="150">
                    <template slot-scope="scope">
                      {{ scope.row.离开时间 || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="开工报工" prop="开工报工" width="100">
                    <template slot-scope="scope">
                      <el-tag v-if="scope.row.开工报工 == 0" size="mini" type="info" style="cursor: pointer;" @click="handleManualJob(scope.row, 'start')">未报工</el-tag>
                      <el-tag v-else size="mini" type="success">已报工</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="完工报工" prop="完工报工" width="100">
                    <template slot-scope="scope">
                      <el-tag v-if="scope.row.完工报工 == 0" size="mini" type="info" style="cursor: pointer;" @click="handleManualJob(scope.row, 'finish')">未报工</el-tag>
                      <el-tag v-else size="mini" type="success">已报工</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="状态" width="100">
                    <template slot-scope="scope">
                      <el-tag v-if="!scope.row.到达时间" size="mini" type="info">未开始</el-tag>
                      <el-tag v-else-if="scope.row.到达时间 && !scope.row.离开时间" size="mini" type="warning">进行中</el-tag>
                      <el-tag v-else size="mini" type="success">已完成</el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="订单号" prop="订单号" /> -->
        <el-table-column align="center" label="项目名称" prop="项目名称" width="220" />
        <el-table-column align="center" label="工件编号" prop="工件编号" width="180" />
        <el-table-column align="center" label="产品型号" prop="产品型号" width="140" />
        <el-table-column align="center" label="产品名称" prop="产品名称" min-width="120" />
        <el-table-column align="center" label="生产类型" prop="生产类型" width="80" />
        <el-table-column align="center" label="小机型" width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.小机型 == 0" size="mini" type="success">无</el-tag>
            <el-tag v-else-if="scope.row.小机型 == 1" size="mini" type="info">静端</el-tag>
            <el-tag v-else-if="scope.row.小机型 == 2" size="mini" type="warning">动端</el-tag>
            <el-tag v-else-if="scope.row.小机型 == 3" size="mini" type="danger">拐臂箱</el-tag>
            <el-tag v-else size="mini" type="info">无</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="生产开始时间" prop="生产开始时间" width="140" />
        <el-table-column align="center" label="生产完成时间" prop="生产完成时间" width="140" />
        <el-table-column align="center" label="执行状态" width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.执行状态 == 0" type="info">未开始</el-tag>
            <el-tag v-else-if="scope.row.执行状态 == 1" type="warning">进行中</el-tag>
            <el-tag v-else-if="scope.row.执行状态 == 2" type="success">已完成</el-tag>
            <el-tag v-else size="mini" type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" min-width="150" fixed="right">
          <template slot-scope="scope">
            <el-button v-if="scope.row.订单状态 == 3" icon="el-icon-position" size="mini" type="text"
              @click="planIssue(scope.row)">开始生产
            </el-button>
            <el-button v-else-if="scope.row.订单状态 == 0" icon="el-icon-document-delete" size="mini" style="color: #ff7f29"
              type="text" @click="planIsStop(scope.row)">挂起订单
            </el-button>
            <el-button v-else-if="scope.row.订单状态 == 2" :disabled="true" icon="el-icon-document-delete" size="mini"
              style="color: #c2c7d0" type="text">生产完成
            </el-button>
            <el-button v-if="scope.row.订单状态 == 4" icon="el-icon-document-delete" size="mini" style="color: #67c23a"
              type="text" @click="continueIssue(scope.row)">继续生产
            </el-button>
            <!--<el-button-->
            <!--  :disabled="parseInt(scope.row.订单状态) == 3 || scope.row.是否下发 == 1"-->
            <!--  icon="el-icon-edit"-->
            <!--  size="mini"-->
            <!--  type="text"-->
            <!--  @click="handleEdit(scope.row)">修改-->
            <!--</el-button>-->
            <el-button :disabled="parseInt(scope.row.订单状态) != 0" icon="el-icon-delete" size="mini" style="color: red"
              type="text" @click="deleteOrder(scope.row)">删除
            </el-button>
            <el-button :disabled="scope.row.执行状态 != 0" icon="el-icon-sort" size="mini" style="color: #409EFF"
              type="text" @click="modifyOrderSort(scope.row)">调序
            </el-button>
            <!--<el-button-->
            <!--  :disabled="buttonIsDisabled(scope.row)"-->
            <!--  size="mini"-->
            <!--  type="text"-->
            <!--  icon="el-icon-top"-->
            <!--  @click="downOrder(scope.row)">上移-->
            <!--</el-button>-->
            <!--<el-button-->
            <!--  :disabled="buttonIsDisabled(scope.row)"-->
            <!--  size="mini"-->
            <!--  type="text"-->
            <!--  icon="el-icon-bottom"-->
            <!--  @click="topOrder(scope.row)">下移-->
            <!--</el-button>-->
            <!--<el-button-->
            <!--  :disabled=" scope.row.是否下发 == 0"-->
            <!--  icon="el-icon-document-copy"-->
            <!--  type="text"-->
            <!--  @click="updateMainWorkCount(scope.row)">-->
            <!--  修改剩余数量-->
            <!--</el-button>-->
            <!--<el-button-->
            <!--  :disabled="scope.row.订单状态 != 3"-->
            <!--  icon="el-icon-document-copy"-->
            <!--  type="text"-->
            <!--  @click="uploadCheckDataExcel(scope.row)">-->
            <!--  导出检查项-->
            <!--</el-button>-->
          </template>
        </el-table-column>

      </el-table>
      <div class="block" style="margin-top: 10px;">
        <el-pagination v-if="!loading" :current-page="pageCurrent" :page-size="pageSize" :page-sizes="[30, 50, 100]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>
    <el-dialog v-el-drag-dialog :visible.sync="dialogFormVisible" center style="min-height: 200px;" title="创建生产订单"
      width="700px">
      <el-form ref="form" :model="form" :rules="rules" label-position="right" label-width="110px">
        <el-form-item label="订单号" prop="orderCode" style="display: inline-block">
          <el-input v-model="form.orderCode" clearable placeholder="请输入订单号" size="small" />
        </el-form-item>
        <el-form-item label="机型" prop="engineType" style="display: inline-block">
          <el-select v-model="form.engineType" clearable placeholder="请选择机型" size="small" style="width: 200px">
            <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="productName" style="display: inline-block">
          <el-input v-model="form.productName" clearable placeholder="请输入产品名称" size="small" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName" style="display: inline-block">
          <el-input v-model="form.projectName" clearable placeholder="请输入项目名称" size="small" />
        </el-form-item>
        <el-form-item label="计划开始时间" prop="startPlanTime" style="display: inline-block">
          <el-date-picker v-model="form.startPlanTime" placeholder="选择计划开始时间" size="small" type="date"
            value-format="yyyy-MM-dd" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOff('form')">取消</el-button>
        <el-button size="small" type="primary" @click="submitAdd('form')">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisible1" center style="min-height: 200px" title="编辑生产订单" width="400px">
      <el-form ref="form1" :model="form1" :rules="rules1" label-position="right" label-width="110px">
        <el-form-item label="订单号" prop="orderNumber" style="display: inline-block">
          <el-input v-model="form1.orderNumber" placeholder="请输入订单号" readonly size="small" />
        </el-form-item>
        <el-form-item label="产品型号" prop="engineTypeValue" style="display: inline-block">
          <el-input v-model="form1.engineTypeValue" placeholder="产品型号" readonly size="small" />
        </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="计划数量" prop="planQuantity" style="display: inline-block">
          <el-input-number v-model="form1.planQuantity" :min="1" :step="1" placeholder="请输入计划数量" size="small"
            style="width: 200px;" />
        </el-form-item>
        <el-form-item label="计划开始时间" prop="startPlanTime" style="display: inline-block">
          <el-date-picker v-model="form1.startPlanTime" placeholder="选择开始时间" size="small" type="date"
            value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="计划结束时间" prop="endPlanTime" style="display: inline-block">
          <el-date-picker v-model="form1.endPlanTime" placeholder="选择结束时间" size="small" type="date"
            value-format="yyyy-MM-dd" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOff1()">取消</el-button>
        <el-button size="small" type="primary" @click="submitAdd1()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisible3" center style="min-height: 200px" title="订单导入" 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 :file-list="itemFile" :on-remove="handleRemove" action="" style="width: 220px" />
        </div>
        <div v-if="worksheet.length !== 0" style="margin: 3px 0 0 395px">
          <el-button icon="el-icon-upload2" size="small" type="primary" @click="basicPartsToSQL">导入到数据库
          </el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisible4" center style="min-height: 200px;" title="打印变速器条码" width="400px">
      <el-form ref="printForm" :model="printForm" :rules="printRules" label-position="right" label-width="110px">
        <el-form-item label="产品型号" prop="产品型号" style="display: inline-block">
          <el-input v-model="printForm.产品型号" placeholder="请输入产品型号" readonly size="small" />
        </el-form-item>
        <el-form-item label="总成号" prop="零件号" style="display: inline-block">
          <el-input v-model="printForm.零件号" placeholder="请输入总成号" readonly size="small" />
        </el-form-item>
        <el-form-item label="序列号" prop="起始号码" style="display: inline-block">
          <el-input v-model="printForm.起始号码" :disabled="printCountPlanIsShow" placeholder="请输入八位序列号" size="small"
            @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="打印日期" prop="打印日期" style="display: inline-block">
          <el-date-picker v-model="printForm.打印日期" :disabled="printCountPlanIsShow" placeholder="选择打印日期" size="small"
            type="date" value-format="yyyy-MM-dd" @change="getPrintDate" />
        </el-form-item>
        <el-form-item label="打印数量" prop="打印数量" style="display: inline-block">
          <el-input-number v-model="printForm.打印数量" :disabled="printCountPlanIsShow" :min="1" :step="1"
            placeholder="请输入打印数量" size="small" style="width: 200px;" />
        </el-form-item>
        <div v-if="printCountPlanIsShow" style="text-align: center;color: #3c9445;font-size: 20px">
          打印进度：{{ printCountPlan }} / {{ printForm.打印数量 }}
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOffPrint()">取消</el-button>
        <el-button :disabled="isAllowAddClike" size="small" type="primary" @click="submitAddPrint('printForm')">确定
        </el-button>
      </div>
    </el-dialog>
    <!--// 强制下线弹出框-->
    <el-dialog :append-to-body="true" :visible.sync="isForceOffLine" center style="text-align: center" title="强制下线记录"
      width="450px">
      <div style="text-align: center">
        <el-form ref="faultStartFormRef" :model="forceOffLineForm" label-position="right" label-width="130px"
          style="width: 100%;margin: auto">
          <el-form-item label="制造编号" prop="engineTypeValue" style="display: inline-block;width: 100%">
            <el-input v-model="forceOffLineForm.workCode" :rows="1" placeholder="制造编号" style="height: 42px;width: 220px"
              readonly type="textarea" />
          </el-form-item>
          <el-form-item label="单元号" prop="engineTypeValue" style="display: inline-block;width: 100%">
            <el-input v-model="forceOffLineForm.unitCode" :rows="1" readonly placeholder="单元号"
              style="height: 42px;width: 220px" type="textarea" />
          </el-form-item>
          <el-form-item label="下线类型" prop="engineTypeValue" style="display: inline-block;width: 100%">
            <el-select v-model="forceOffLineForm.type" placeholder="请选择下线类型" style="width:220px;" size="small">
              <el-option v-for="item in forceOffTypeList" :key="item" :label="item" :value="item" size="mini" />
            </el-select>
          </el-form-item>
          <el-form-item label="强制下线原因" prop="engineTypeValue" style="display: inline-block;width: 100%">
            <el-input v-model="forceOffLineForm.offLineTest" :rows="2" placeholder="请输入下线原因"
              style="height: 42px;width: 220px" type="textarea" />
          </el-form-item>
          <!--底部按钮-->
          <div style="text-align: center; margin-top: 20px">
            <el-button class="el-icon-check" type="primary" @click="forceOffLineSubmit()">确定</el-button>
            <el-button class="el-icon-close" style="margin-left: 50px" @click="isForceOffLine = false">关闭</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <!-- 调序对话框 -->
    <el-dialog :visible.sync="dialogFormVisibleSort" center title="修改订单排序" width="400px">
      <el-form ref="sortForm" :model="sortForm" :rules="sortRules" label-position="right" label-width="110px">
        <el-form-item label="订单号" style="display: inline-block">
          <el-input v-model="sortForm.订单号" readonly size="small" />
        </el-form-item>
        <el-form-item label="项目名称" style="display: inline-block">
          <el-input v-model="sortForm.项目名称" readonly size="small" />
        </el-form-item>
        <el-form-item label="当前排序" style="display: inline-block">
          <el-input v-model="sortForm.当前排序" readonly size="small" />
        </el-form-item>
        <el-form-item label="新排序号" prop="新排序号" style="display: inline-block">
          <el-input-number v-model="sortForm.新排序号" :min="1" :step="1" placeholder="请输入新的排序号" size="small"
            style="width: 200px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancelSort()">取消</el-button>
        <el-button size="small" type="primary" @click="submitSort()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-el-drag-dialog :visible.sync="dialogFormVisibleModifyOrder" center title="强制下线记录" width="63%">
      <el-table :data="tableDataVisibleModifyOrder" :header-cell-style="{ background: '#383E4B', color: 'white' }"
        highlight-current-row border stripe size="small" height="550px" style="width: 1171px">
        <el-table-column min-width="100px" label="工位号" align="center">
          <template slot-scope="scope">
            {{ scope.row.工位号 }}
          </template>
        </el-table-column>
        <el-table-column min-width="90px" label="操作者" align="center">
          <template slot-scope="scope">
            {{ scope.row.操作者 }}
          </template>
        </el-table-column>
        <el-table-column min-width="100px" label="间隔号" align="center">
          <template slot-scope="scope">
            {{ scope.row.间隔号 }}
          </template>
        </el-table-column>
        <el-table-column min-width="100px" label="单元号" align="center">
          <template slot-scope="scope">
            {{ scope.row.单元号 }}
          </template>
        </el-table-column>
        <el-table-column min-width="100px" label="装配类型" align="center">
          <template slot-scope="scope">
            {{ scope.row.间隔号 }}
          </template>
        </el-table-column>
        <el-table-column min-width="100px" label="下线原因" align="center">
          <template slot-scope="scope">
            {{ scope.row.原因 }}
          </template>
        </el-table-column>
        <el-table-column min-width="100px" label="下线类型" align="center">
          <template slot-scope="scope">
            {{ scope.row.下线类型 }}
          </template>
        </el-table-column>
        <el-table-column min-width="200px" label="操作时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.操作时间 }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import UploadExcelComponent from './UploadExcel.vue'
import { sleep } from '../../../utils/tool' // import { Mqtt } from '../../../utils/mqtt.js'
// 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'
      },
      tableDataFirst: [],
      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: '',
      workType:'',
      engineType: [],
      partCodeList: [],
      OKWarehouseValue: '',
      OKWarehouse: [],
      NGWarehouseValue: '',
      NGWarehouse: [],
      engineType_check: 0,
      printForm: { // 创建订单
        订单号: '',
        零件号: '',
        产品型号: '',
        产品型号代码: '',
        起始号码: '',
        打印日期: '',
        打印数量: 1
      },
      printRules: { // 打印条码验证
        零件号: [{ required: true, message: '请输入总成号', trigger: 'blur' }],
        订单号: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
        产品型号: [{ required: true, message: '请输入产品型号', trigger: 'blur' }],
        起始号码: [{ required: true, min: 8, message: '长度最少为八位', trigger: 'blur' }],
        打印日期: [{ required: true, message: '请选择打印日期', trigger: 'blur' }],
        打印数量: [{ required: true, message: '请输入打印数量', trigger: 'blur' }]
      },
      form: { // 创建订单
        orderCode: '', // 订单号
        engineType: '', // 机型
        productName: '', // 产品名称
        projectName: '', // 项目名称
        startPlanTime: '' // 计划开始时间
      },
      rules: { // 创建订单验证
        orderCode: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
        engineType: [{ required: true, message: '请输入机型', trigger: 'blur' }],
        productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
        projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        startPlanTime: [{ required: true, message: '请输入计划开始时间', trigger: 'blur' }]
      },
      form1: { // 修改订单
        workCode: '', // 制造编号
        projectName: '', // 项目名称
        splitCode: '', // 间隔号
        unidCode: '', // 单元号
        engineType: '', // 本体类型
        engineTypeModel: '', // 附件类型
        startPlanTime: '', // 开始时间
        endPlanTime: '' // 结束时间
      },
      rules1: { // 修改订单验证
        planQuantity: [{ required: true, message: '请输入计划数量', trigger: 'blur' }],
        orderNumber: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
        engineTypeValue: [{ required: true, message: '请选择机型', trigger: 'blur' }],
        partCode: [{ required: true, message: '请选择总成号', trigger: 'blur' }],
        startPlanTime: [{ required: true, message: '请选择计划开始时间', trigger: 'blur' }],
        endPlanTime: [{ required: true, message: '请选择计划结束时间', trigger: 'blur' }],
        quantityCompletion: [{ required: true, message: '请输入计划完成数量', trigger: 'blur' }]
      },
      form2: { // 订单下发
        planQuantity: '',
        orderNumber: '',
        engineTypeValue: '',
        MID: '',
        IssuedQuantity: 1
      },
      rules2: { // 订单下发验证
        planQuantity: [{ required: true, message: '请输入计划数量', trigger: 'blur' }],
        orderNumber: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
        engineTypeValue: [{ required: true, message: '请选择机型', trigger: 'blur' }],
        IssuedQuantity: [{ required: true, message: '请输入订单下发数量', trigger: 'blur' }]
      },
      form3: { // 订单下发
        planQuantity: '',
        orderNumber: '',
        engineTypeValue: '',
        MID: '',
        IssuedQuantity: 1
      },
      rules3: { // 订单下发验证
        planQuantity: [{ required: true, message: '请输入计划数量', trigger: 'blur' }],
        orderNumber: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
        engineTypeValue: [{ required: true, message: '请选择机型', trigger: 'blur' }],
        IssuedQuantity: [{ required: true, message: '请输入订单下发数量', trigger: 'blur' }]
      },
      isForceOffLine: false,
      forceOffLineForm: {
        opName: '',
        workCode: '',
        unitCode: '',
        engineID: '',
        type: '',
        offLineTest: '' // 下线原因
      },
      forceOffTypeList: ['工件下线处理', '重新上线加工'],
      // 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: [],
      tableDataWorkProcess: [], // 工序任务数据
      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,
      tableDataVisibleModifyOrder: [],
      dialogFormVisibleModifyOrder: false,
      numberModifyOrder: '',
      // 调序相关数据
      dialogFormVisibleSort: false,
      sortForm: {
        订单ID: '',
        订单号: '',
        项目名称: '',
        当前排序: '',
        新排序号: 1
      },
      sortRules: {
        新排序号: [{ required: true, message: '请输入新的排序号', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getOrderNumber()
    this.getEndStation()
    this.searchOrder()

    // 定时重新读取数据
    setInterval(() => {
      this.searchOrder()
    }, 1000 * 10)
  },
  mounted() {

  },
  beforeDestroy() {

  },
  methods: {
    viewModifyOrder() {
      this.dialogFormVisibleModifyOrder = true
      this.viewModifyOrderClick()
    },
    viewModifyOrderClick() {
      var param1 = []
      var Data1 = this.CreateData('11', 'MES_强制下线记录_查询', param1)
      this.ExecDatabase(Data1).then(response => {
        // this.numberModifyOrder = response.data.length
        this.tableDataVisibleModifyOrder = response.data
      })
    },
    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}`
    },
    renderHeader(h) {
      return (
        <div>
          <span>操作</span>
          <el-button
            type='primary'
            style='padding:2px 5px;margin-left: 10px'
            size='mini'
            onClick={() => this.addDetailsRow()}
          >
            +
          </el-button>
        </div>
      )
    },
    // 提交订单明细
    addDetailsRow() {
      if (!this.btn_makeOrder) {
        this.$message.warning('请先创建生产订单！')
        return
      }
      var param = []
      param[0] = ['订单号', this.form.orderNumber]
      param[1] = ['产品型号', '']
      param[2] = ['计划数量', 1]
      param[3] = ['加工方式代码', 1]
      var Data = this.CreateData(
        '12',
        'SY_MES_计划BOM_发动机预制订单_明细_创建',
        param
      )
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result === '1') {
          this.$message({
            message: '修改成功',
            type: 'success'
          })
          this.searchOrderFirstDetails(this.form.orderNumber)
        } else {
          this.$message.error('新增失败！')
        }
      })
    },
    searchOrderFirstDetails(orderNumber) {
      this.tableDataFirst = []
      var param = []
      param[0] = ['订单号', orderNumber]
      var Data = this.CreateData(
        '11',
        'SY_MES_计划BOM_发动机预制订单_明细查询',
        param
      )
      this.ExecDatabase(Data).then(response => {
        for (const responseElement of response.data) {
          responseElement['edit'] = false
          responseElement['加工方式代码_yuan'] =
            responseElement['加工方式代码']
          responseElement['加工方式代码_yuan'] =
            responseElement['加工方式代码']
          responseElement['产品型号_yuan'] = responseElement['产品型号']
          responseElement['计划数量_yuan'] = responseElement['计划数量']
        }
        this.tableDataFirst = response.data
      })
    },
    // 初始化获取产品型号
    getPartCodeList() {
      this.partCodeList = []
      this.form.engineTypeModel = ''
      var param = []
      param[0] = ['基本机型', this.form.engineType]
      var Data = this.CreateData('11', '北汽福田订单创建零件号_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length === 0) {
          this.$message({
            type: 'error',
            message: '该机型没有对应的零件号'
          })
          return false
        } else {
          for (let i = 0; i < response.data.length; i++) {
            this.partCodeList.push({
              label: response.data[i].零件号,
              value: response.data[i].零件号
            })
          }
        }
      })
    },
    // 初始化获取订单号
    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].订单号
          })
        }
      })
    },
    buttonIsDisabled(row) {
      let isDisabled = false
      if (row.订单状态 != 1) isDisabled = true
      return isDisabled
    },
    // 下移订单
    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',
              duration: 3000
            })
            this.pageCurrent = 1
            this.pageSize = 50
            this.searchOrder()
          } else {
            this.$message({
              message: response.data[0].msg,
              type: 'warning',
              duration: 3000
            })
          }
        })
      } else {
        this.$message.error('请选择订单！')
      }
    },
    // 上移订单
    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',
              duration: 3000
            })
            this.pageCurrent = 1
            this.pageSize = 50
            this.searchOrder()
          } else {
            this.$message({
              message: response.data[0].msg,
              type: 'warning',
              duration: 3000
            })
          }
        })
      } else {
        this.$message.error('请选择订单！')
      }
    },
    // 修改小线剩余上料数
    updateWorkOver(row) {
      this.$confirm(`是否强制该工件完工下线 <i style="color: red">  工件编号：` + row.工件编号 + `</i> `, '提示', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['工件编号', row.工件编号]
        var Data = this.CreateData('12', '生产计划_派工订单_工件追溯_强制完成', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            this.$message.success('强制下线成功！')
            this.selectPlan(row, this.expandsDetail)
          } else {
            this.$message.error('强制下线失败！')
          }
        })
      })
    },
    // 导出检查项
    uploadCheckDataExcel(row) {
      if (this.tableData.length !== 0) {
        var param = []
        param[0] = ['订单号', row.订单号]
        var Data = this.CreateData('2001', '电子看板_工序内容_记录表_订单号导出', param)
        this.exportExcel_NPOI(Data)
      } else {
        this.$message.warning('暂无数据')
      }
    },
    // 修改线首订单剩余上料数
    updateMainWorkCount(row) {
      // 弹窗输入数量弹窗 只能输入数字 不能负数
      this.$prompt('请输入修改后的线首订单剩余上料数量', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+$/,
        inputErrorMessage: '只能输入数字',
        inputValue: (row.计划数量 - row.总装上线)
      }).then(({ value }) => {
        if (value > row.计划数量) {
          this.$notify.error({
            title: '提示',
            message: '剩余数不可大于计划数量！',
            position: 'top-right',
            offset: 10
          })
          return
        }
        const param = []
        param[0] = ['订单号', row.订单号]
        param[1] = ['待上线数量', value]
        const Data = this.CreateData('12', '合力_总装线PLC_更新待上线数量', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            this.$notify.success({
              title: '提示',
              message: '修改成功！',
              position: 'bottom-right',
              offset: 170
            })
          } else {
            this.$message.error('修改失败')
          }
          this.searchOrder()
          // this.getTable1()
          // this.getTable2()
        })
      })
    },
    // 强制下线
    forceOffLine(row) {
      console.log(this.$store.state.user.id)
      this.isForceOffLine = true
      this.forceOffLineForm.engineID = row.工件编号
      this.forceOffLineForm.unitCode = row.单元号
      this.forceOffLineForm.workCode = row.制造编号
      this.forceOffLineForm.type = ''
      this.forceOffLineForm.offLineTest = ''
    },
    // 强制下线记录
    forceOffLineSubmit() {
      var param = []
      param[0] = ['工位号', '管理系统']
      param[1] = ['操作者', this.$store.state.user.id]
      param[2] = ['原因', this.forceOffLineForm.offLineTest]
      param[3] = ['工件编号', this.forceOffLineForm.engineID]
      param[4] = ['下线类型', this.forceOffLineForm.type]
      var Data = this.CreateData('12', 'MES_强制下线记录_增加', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result === '1') {
          this.searchOrder()
          this.$message({
            message: '强制完工提交成功',
            type: 'success'
          })
          this.isForceOffLine = false
        } else {
          this.$message({
            message: '强制完工提交失败',
            type: 'error'
          })
        }
      })
    },
    // 控制展开列
    selectPlan(row, expandedRows) {
      if (expandedRows.length) {
        if (row) {
          var param = []
          param[0] = ['工单号', row.订单号]
          var Data = this.CreateData('11', '生产计划_派工订单_打印_查询', param)
          this.ExecDatabase(Data).then(response => {
            this.expands = []
            console.log(response.data)
            if (response.data.length !== 0) {
              this.tableDataPrint = response.data
            } else {
              this.tableDataPrint = []
            }
            this.expands.push(row.订单号)
          })

          var Data2 = this.CreateData('11', '生产计划_派工订单_打印详细_查询', param)
          this.ExecDatabase(Data2).then(response => {
            this.expandsDetail = []
            if (response.data.length !== 0) {
              this.tableDataPrintDetail = response.data
            } else {
              this.tableDataPrintDetail = []
            }
            this.expandsDetail.push(row.订单号)
          })

          // 新增：查询工序任务计划数据
          var param3 = []
          param3[0] = ['工件编号', row.工件编号]
          var Data3 = this.CreateData('11', '生产计划_派工订单_工序任务_计划查询', param3)
          this.ExecDatabase(Data3).then(response => {
            if (response.data.length !== 0) {
              this.tableDataWorkProcess = response.data
            } else {
              this.tableDataWorkProcess = []
            }
          })
        }
      } else {
        this.expands = []
        this.expandsDetail = []
        this.tableDataWorkProcess = []
      }
    },
    // 获取展开列的工单号
    getRowKeys(row) {
      return row.订单号
    },
    // 查询订单
    searchOrder() {
      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] = ['生产类型', this.workType]
      param[9] = ['PageCurrent', this.pageCurrent]
      param[10] = ['PageSize', this.pageSize]
      param[11] = ['PageCount', '1111', 'int', '1']
      param[12] = ['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
          // 先获取当前选中订单号
          let OrderForm
          if (this.expandsDetail.length) {
            OrderForm = this.expandsDetail[0]
            for (const item of this.tableData) {
              if (item.订单号 == OrderForm) {
                this.selectPlan(item, this.expandsDetail)
              }
            }
          }
        } else {
          this.tableData = []
        }
        this.total = parseInt(response.data.output[0].ItemCount)
        this.loading = false
      })
    },
    // 创建订单
    creatOrder(formName) {
      // 重置表单
      this.form = {
        orderCode: '',
        engineType: '',
        productName: '',
        projectName: '',
        startPlanTime: ''
      }
      this.dialogFormVisible = true
    },
    // 提交新增订单
    submitAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var param = []
          param[0] = ['订单号', this.form.orderCode]
          param[1] = ['机型', this.form.engineType]
          param[2] = ['产品名称', this.form.productName]
          param[3] = ['项目名称', this.form.projectName]
          param[4] = ['计划开始时间', this.form.startPlanTime]
          var Data = this.CreateData('11', '生产计划_派工订单_增加', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === 1 || response.data[0].reuslt === 1) {
              this.$message({
                message: '订单创建成功',
                type: 'success'
              })
              this.pageCurrent = 1
              this.pageSize = 30
              this.searchOrder()
              this.dialogFormVisible = false
            } else if (response.data[0].result === 2) {
              this.$message.error(response.data[0].msg || '该订单号已被使用，请使用其他订单号')
            } else {
              this.$message.error('订单创建失败！')
            }
          })
        } 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: '开始打印变速器条码',
              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('打印变速器条码失败!')
          }
        })
      })
    },
    // 判断起始号是否重复打印
    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: '全部条码打印完成',
              type: 'success'
            })
            // 关闭进度条 关闭打印窗口
            this.printCountPlanIsShow = false
            this.dialogFormVisible4 = false
          }
        } else {
          this.$message.error('记录失败！')
        }
      })
    },
    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('此操作将永久删除该行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['订单号', row.订单号]
        var Data = this.CreateData('11', '订单计划_删除', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result == 1) {
            this.$message({
              message: response.data[0].msg,
              type: 'success'
            })
            this.pageCurrent = 1
            this.pageSize = 30
            this.searchOrder()
          } else {
            this.$message.error(response.data[0].msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 修改订单
    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
    },
    // 开始生产
    planIssue(row) {
      // 弹窗提示框是否下发订单 确认后修改订单是否下发字段
      this.$confirm(`确定下发订单吗？下发后进入生产队列开始生产，生产后不可取消下发与修改订单信息 <i style="color: red">  机型：` + row.产品型号 + '，订单号：' + row.订单号 + `</i> `, '提示', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 无滞留信息
        var param = []
        var Data = this.CreateData('11', 'MES_计划BOM_发动机订单计划_滞留判断', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === 1) {
            // 无滞留信息
            this.updateOrderStatus(row.MID, 1)
          } else if (response.data[0].result === 2) {
            this.$confirm('<i style="color: red">' + response.data[0].msg + '</i>', '提示', {
              dangerouslyUseHTMLString: true,
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              // 强制切换
              this.updateOrderStatus(row.MID, 1)
            })
          } else {
            this.$message.error('订单下发失败')
          }
        })
      })
    },
    // 继续生产
    continueIssue(row) {
      // 弹窗提示框是否下发订单 确认后修改订单是否下发字段
      this.$confirm(`是否继续该订单的生产,重下发后订单排序将排至最新 <i style="color: red">  制造编号：` + row.制造编号 + '，DS/ES编号：' + row.间隔号 + `</i> `, '提示', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 直接改，不判断滞留
        this.updateOrderStatus(row.MID, 3)
        // var param = []
        // var Data = this.CreateData('11', 'MES_计划BOM_发动机订单计划_滞留判断', param)
        // this.ExecDatabase(Data).then(response => {
        //   if (response.data[0].result === 1) {
        //     // 无滞留信息
        //     this.updateOrderStatus(row.MID, 3)
        //   } else if (response.data[0].result === 2) {
        //     this.$confirm('<i style="color: red">' + response.data[0].msg + '</i>', '提示', {
        //       dangerouslyUseHTMLString: true,
        //       confirmButtonText: '确定',
        //       cancelButtonText: '取消',
        //       type: 'warning'
        //     }).then(() => {
        //       // 强制切换
        //       this.updateOrderStatus(row.MID, 3)
        //     })
        //   } else {
        //     this.$message.error('订单下发失败')
        //   }
        // })
      })
    },
    // 修改订单状态
    updateOrderStatus(MID, type) {
      var param = []
      param[0] = ['MID', MID]
      param[1] = ['type', type]
      var Data = this.CreateData('11', 'MES_计划BOM_发动机订单计划_状态修改', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result === 1) {
          this.$message.success('订单状态操作成功！')
          this.pageCurrent = 1
          this.pageSize = 30
          this.searchOrder()
        } else {
          this.$message.error(response.data[0].msg)
        }
      })
    },
    // 暂停生产
    planIsStop(row) {
      // 弹窗提示框是否下发订单 确认后修改订单是否下发字段
      this.$confirm(`确定暂停此订单吗`, '提示', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 强制切换
        this.updateOrderStatus(row.MID, 2)
      })
    },
    // 提交修改订单
    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('11', '订单计划_修改', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === 1) {
              this.$message({
                message: '订单修改成功',
                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(`确定下达订单<p style="color: deepskyblue;display: inline-block"> ${row.订单号}</p> 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        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: '订单下发成功！',
              type: 'success'
            })
            this.pageCurrent = 1
            this.pageSize = 30
            this.searchOrder()
          } else {
            this.$message.error('订单下发失败！')
          }
        })
      })
    },
    // 取消下发
    ordersIssuedEditor1(row) {
      this.$confirm(`确定取消订单<p style="color: deepskyblue;display: inline-block"> ${row.订单号}</p> 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        var param = []
        param[0] = ['MID', row.MID]
        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.pageCurrent = 1
            this.pageSize = 30
            this.searchOrder()
          } else {
            this.$message.error(response.data[0].msg)
          }
        })
      })
    },
    // 查询
    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.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(`订单号不能为空`)
                break
              } else if (Number(numberPlan) <= 0) { // 数量不能为0
                this.$notify.error(`计划数量不能为空`)
                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(`请确认导入文件是否正确`)
                  return
                }
              }
            }
          }
          this.itemFile.splice(j, 1)
          this.worksheet.splice(j, 1)
          this.err === 0 ? this.$message.success(`导入完成`) : this.$message.error(`导入失败零件个数为${this.err}，请检查文件是否正确`)
        }
        this.loading = false
        this.searchOrder()
      } catch (e) {
        this.err++
        this.loading = false
        this.$notify.error(`导入数据错误,请检查导入文件是否正确`)
        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 (res.hasOwnProperty('output') === false) {
          if (res[0].result === '0') {
            this.$notify.error(`${orderNumber}导入失败`)
          }
        } else {
          if (res.result[0].result === '0') {
            this.$notify.error(`${numberPlan}导入失败`)
          }
          if (res.output[0].导入类型 === '2') {
            this.$notify.warning(`${numberPlan}存在重复数据`)
          }
        }
      } catch (e) {
        this.err++
        this.$message.error(`导入数据错误`)
        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]
        param[8] = ['生产类型', this.workType]
        var Data = this.CreateData('2001', 'MES_计划BOM_发动机订单计划_订单导出', param)
        this.exportExcel_NPOI(Data)
      } else {
        this.$message.warning('暂无数据')
      }
    },
    // 分页
    handleSizeChange(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.expands = []
      this.searchOrder()
    },
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.expands = []
      this.searchOrder()
    },
    // 修改订单排序
    modifyOrderSort(row) {
      this.sortForm.订单ID = row.订单ID
      this.sortForm.订单号 = row.订单号
      this.sortForm.项目名称 = row.项目名称
      this.sortForm.当前排序 = row.排序
      this.sortForm.新排序号 = row.排序
      this.dialogFormVisibleSort = true
    },
    // 提交排序修改
    submitSort() {
      this.$refs['sortForm'].validate((valid) => {
        if (valid) {
          this.$confirm(`确定将订单排序从 ${this.sortForm.当前排序} 调整为 ${this.sortForm.新排序号} 吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const param = []
            param[0] = ['订单ID', this.sortForm.订单ID]
            param[1] = ['新排序号', this.sortForm.新排序号]
            const Data = this.CreateData('11', '生产计划_派工订单_执行计划_排序调整', param)
            this.ExecDatabase(Data).then(response => {
              if (response.data[0].result === 1) {
                this.$message.success('排序调整成功！')
                this.dialogFormVisibleSort = false
                this.pageCurrent = 1
                this.pageSize = 30
                this.searchOrder()
              } else {
                this.$message.error(response.data[0].msg || '排序调整失败')
              }
            }).catch(error => {
              this.$message.error('排序调整失败：' + error.message)
            })
          })
        } else {
          return false
        }
      })
    },
    // 取消排序修改
    cancelSort() {
      this.dialogFormVisibleSort = false
      this.$refs['sortForm'].resetFields()
    },
    // 手动报工（开工/完工）
    handleManualJob(row, jobType) {
      // 从父级行获取订单号和工件编号
      const parentRow = this.tableData.find(item => {
        return this.expandsDetail.includes(item.订单号)
      })
      if (!parentRow) {
        this.$message.warning('请先展开订单查看工序任务')
        return
      }
      
      const isStart = jobType === 'start'
      const confirmTitle = isStart ? '开工报工确认' : '完工报工确认'
      
      this.$confirm('是否需要手动进行该工序报工？', confirmTitle, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const workStation = row.工序编号
        this.$webRequest(isStart ? 'OperAtion_JobStart' : 'OperAtion_JobFinished', {
          工位号: workStation,
          订单号: parentRow.订单号,
          工件编号: parentRow.工件编号,
        }).then(response => {
          console.log(response)
          const successMessage = isStart ? '开工报工成功' : '完工报工成功'
          const errorMessage = isStart ? '开工报工失败：' : '完工报工失败：'
          
          if (response.data && response.data.code === 200) {
            this.$message.success(successMessage)
            // 刷新工序任务数据
            this.selectPlan(parentRow, this.expandsDetail)
          } else {
            this.$message.error(errorMessage + (response.data.message|| '未知错误'))
          }
        }).catch(error => {
          const errorMessage = isStart ? '开工报工失败：' : '完工报工失败：'
          this.$message.error(errorMessage + error.message)
        })
      }).catch(() => {
        // 取消操作
      })
    },
  }
}
</script>

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

.topDiv {
  margin-bottom: 10px;
}

.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;
}
</style>


