<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="margin-left: 10px">订单号：</span>
        <el-input v-model="orderNumberValue" clearable placeholder="请输入订单号" size="small" style="width: 150px" />
        <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-select v-model="workType" clearable placeholder="请选择生产类型" size="small" style="width: 150px">
          <el-option label="MAIN" value="MAIN" />
          <el-option label="FES" value="FES" />
        </el-select>
        <span style="margin-left: 10px">执行状态：</span>
        <el-select v-model="executeStatusValue" clearable placeholder="请选择执行状态" size="small" style="width: 130px">
          <el-option label="未开始" :value="0" />
          <el-option label="进行中" :value="1" />
          <el-option label="已完成" :value="2" />
        </el-select>
        <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="pageCurrent = 1; searchOrder()">
          查询订单
        </el-button>
        <el-button icon="el-icon-circle-plus" size="small" type="distribution" @click="creatOrder('form')">
          创建订单
        </el-button>
      </div>

      <el-table :data="tableData" :expand-row-keys="expandsDetail"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }" :row-key="getRowKeys" border class="main"
        height="800px" size="mini" style="width: 100%;max-height: 700px"
        tooltip-effect="dark" @expand-change="selectPlan">
        <el-table-column align="center" label="排序" prop="排序" width="60" />
        <el-table-column align="center" fixed label="" type="expand" width="35">
          <template slot-scope="props">
            <div :key="props.row && props.row.订单号" style="margin: 5px 10px;width: 1400px;z-index: 99;">
              <h4 style="margin: 5px 0; color: #606266;">工序任务进度</h4>
              <el-table :key="props.row && props.row.订单号" :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>
          </template>
        </el-table-column>
        <el-table-column align="center" label="项目名称" prop="项目名称" show-overflow-tooltip width="220" />
        <el-table-column align="center" label="工件编号" prop="工件编号" width="220" />
        <el-table-column align="center" label="产品型号" prop="产品型号" width="170" />
        <el-table-column align="center" label="产品名称" prop="产品名称" show-overflow-tooltip min-width="200" />
        <el-table-column align="center" label="生产类型" prop="生产类型" width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.生产类型 === 'MAIN'" size="mini" type="primary">MAIN</el-tag>
            <el-tag v-else-if="scope.row.生产类型" size="mini" type="warning">{{ scope.row.生产类型 }}</el-tag>
          </template>
        </el-table-column>
        <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="155" />
        <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="90" fixed="right">
          <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="操作" width="200" 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.订单状态) == 2" icon="el-icon-edit" size="mini" type="text"
              @click="handleEdit(scope.row)">
              修改
            </el-button>
            <el-button :disabled="parseInt(scope.row.订单状态) == 2" icon="el-icon-delete" size="mini" style="color: red"
              type="text" @click="deleteOrder(scope.row)">
              删除
            </el-button>
            <el-button :disabled="scope.row.执行状态 == 2" icon="el-icon-sort" size="mini" style="color: #409EFF"
              type="text" @click="modifyOrderSort(scope.row)">
              调序
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block" style="margin-top: 10px;">
        <el-pagination :current-page="pageCurrent" :page-size="pageSize" :page-sizes="[50, 100, 200, 500]"
          :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"
            @input="val => form.orderCode = val.replace(/[\u4e00-\u9fa5]/g, '')" />
        </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="productionType" style="display: inline-block">
          <el-select v-model="form.productionType" placeholder="请选择生产类型" size="small" style="width: 200px">
            <el-option label="MAIN" value="MAIN" />
            <el-option label="FES" value="FES" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划开始时间" prop="startPlanTime" style="display: inline-block">
          <el-date-picker v-model="form.startPlanTime" placeholder="选择计划开始时间" size="small" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" />
        </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="700px">
      <el-form ref="form1" :model="form1" :rules="rules1" label-position="right" label-width="110px"
        class="edit-order-form">
        <el-form-item label="订单号" prop="orderNumber">
          <el-input v-model="form1.orderNumber" placeholder="请输入订单号" readonly size="small" />
        </el-form-item>
        <el-form-item label="产品型号" prop="engineTypeValue">
          <el-select v-model="form1.engineTypeValue" placeholder="产品型号" size="small" style="width: 100%">
            <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">
          <el-input v-model="form1.productName" placeholder="请输入产品名称" size="small" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form1.projectName" placeholder="请输入项目名称" size="small" />
        </el-form-item>
        <el-form-item label="生产类型" prop="productionType">
          <el-select v-model="form1.productionType" placeholder="请选择生产类型" size="small" style="width: 100%">
            <el-option label="MAIN" value="MAIN" />
            <el-option label="FES" value="FES" />
          </el-select>
        </el-form-item>
        <el-form-item label="执行状态" prop="executeStatus">
          <el-select v-model="form1.executeStatus" placeholder="请选择执行状态" size="small" style="width: 100%">
            <el-option label="未开始" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已完成" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划开始时间" prop="startPlanTime" class="edit-order-form__full">
          <el-date-picker v-model="form1.startPlanTime" placeholder="选择计划开始时间" size="small" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" />
        </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="submitEdit('form1')">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogFormVisibleSort" center title="调序（修改计划开始时间）" width="500px">
      <el-form ref="sortForm" :model="sortForm" :rules="sortRules" label-position="right" label-width="110px">
        <el-form-item label="订单号">
          <el-input v-model="sortForm.订单号" readonly size="small" />
        </el-form-item>
        <el-form-item label="项目名称">
          <el-input v-model="sortForm.项目名称" readonly size="small" />
        </el-form-item>
        <el-form-item label="计划开始时间" prop="计划开始时间">
          <el-date-picker v-model="sortForm.计划开始时间" placeholder="选择计划开始时间" size="small" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" />
        </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>
  </div>
</template>

<script>
export default {
  name: 'ReleaseOfProductionPlan',
  data() {
    return {
      refreshTimer: null,
      tableDataSnapshot: '',
      expandsDetail: [],
      tableData: [],
      tableDataWorkProcess: [],
      orderNumberValue: '',
      OrderNumber_check: 0,
      engineType: [],
      engineTypeValue: '',
      engineType_check: 0,
      workType: '',
      executeStatusValue: '',
      startPlanTime: '',
      startPlanTime_check: 0,
      endPlanTime: '',
      endPlanTime_check: 0,
      total: 0,
      pageSize: 100,
      pageCurrent: 1,
      dialogFormVisible: false,
      dialogFormVisible1: false,
      form: {
        orderCode: '',
        engineType: '',
        productName: '',
        projectName: '',
        productionType: 'MAIN',
        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' }],
        productionType: [{ required: true, message: '请选择生产类型', trigger: 'change' }],
        startPlanTime: [{ required: true, message: '请输入计划开始时间', trigger: 'blur' }]
      },
      form1: {
        orderNumber: '',
        engineTypeValue: '',
        productName: '',
        projectName: '',
        productionType: 'MAIN',
        executeStatus: 0,
        startPlanTime: ''
      },
      rules1: {
        orderNumber: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
        engineTypeValue: [{ required: true, message: '请选择机型', trigger: 'blur' }],
        productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
        projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        productionType: [{ required: true, message: '请选择生产类型', trigger: 'change' }],
        executeStatus: [{ required: true, message: '请选择执行状态', trigger: 'change' }],
        startPlanTime: [{ required: true, message: '请选择计划开始时间', trigger: 'blur' }]
      },
      dialogFormVisibleSort: false,
      sortForm: {
        ID: null,
        订单号: '',
        项目名称: '',
        计划开始时间: ''
      },
      sortRules: {
        计划开始时间: [{ required: true, message: '请选择计划开始时间', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getEndStation()
    this.searchOrder()
    this.refreshTimer = setInterval(() => {
      this.searchOrder({ silent: true })
    }, 10000)
  },
  beforeDestroy() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
      this.refreshTimer = null
    }
  },
  methods: {
    getEndStation() {
      this.engineType = []
      const param = []
      const Data = this.CreateData('11', 'MES_基本变量_机型代码_产品型号查询', param)
      this.ExecDatabase(Data).then(response => {
        const list = Array.isArray(response.data) ? response.data : []
        this.engineType = list.map(item => ({
          label: item.产品型号,
          value: item.产品型号
        }))
      })
    },
    searchOrder(options = {}) {
      const { silent = false } = options
      this.startPlanTime_check = this.startPlanTime ? 1 : 0
      this.endPlanTime_check = this.endPlanTime ? 1 : 0
      this.OrderNumber_check = this.orderNumberValue ? 1 : 0
      this.engineType_check = this.engineTypeValue ? 1 : 0
      if (this.startPlanTime === null) {
        this.startPlanTime = ''
      }
      if (this.endPlanTime === null) {
        this.endPlanTime = ''
      }
      const executeStatusVal = (this.executeStatusValue === '' || this.executeStatusValue === null || this.executeStatusValue === undefined) ? -1 : this.executeStatusValue
      const 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] = ['执行状态', executeStatusVal]
      param[10] = ['PageCurrent', this.pageCurrent]
      param[11] = ['PageSize', this.pageSize]
      param[12] = ['PageCount', '1111', 'int', '1']
      param[13] = ['ItemCount', '1111', 'int', '1']
      const Data = this.CreateData('11', 'MES_计划BOM_发动机订单计划_查询分页', param)
      this.ExecDatabase(Data).then(response => {
        const responseData = response.data || {}
        const result = responseData.result || []
        const nextSnapshot = JSON.stringify(result)
        const dataChanged = nextSnapshot !== this.tableDataSnapshot
        if (dataChanged) {
          this.tableData = result
          this.tableDataSnapshot = nextSnapshot
          if (this.expandsDetail.length) {
            const expandedOrder = this.expandsDetail[0]
            const matchedRow = this.tableData.find(item => item.订单号 === expandedOrder)
            if (matchedRow) {
              this.selectPlan(matchedRow, [matchedRow])
            } else {
              this.expandsDetail = []
              this.tableDataWorkProcess = []
            }
          }
        }
        if (responseData.output && responseData.output[0] && responseData.output[0].ItemCount !== undefined) {
          this.total = parseInt(responseData.output[0].ItemCount, 10)
        } else {
          this.total = 0
        }
      }).catch(error => {
        console.error('订单查询失败', error)
        if (!silent) {
          this.tableData = []
          this.tableDataSnapshot = ''
          this.tableDataWorkProcess = []
          this.total = 0
        }
      })
    },
    selectPlan(row, expandedRows) {
      if (!expandedRows || !expandedRows.length || !row) {
        this.expandsDetail = []
        this.tableDataWorkProcess = []
        return
      }
      const param = []
      param[0] = ['工件编号', row.工件编号]
      const Data = this.CreateData('11', '生产计划_派工订单_工序任务_计划查询', param)
      this.ExecDatabase(Data).then(response => {
        this.tableDataWorkProcess = response.data
        this.expandsDetail = [row.订单号]
        console.log('工序任务数据:', this.tableDataWorkProcess)
      }).catch(error => {
        console.error('工序任务查询失败', error)
        this.tableDataWorkProcess = []
      })
    },
    getRowKeys(row) {
      return row.订单号
    },
    creatOrder(formName) {
      this.dialogFormVisible = true
      const now = new Date()
      const y = now.getFullYear()
      const m = String(now.getMonth() + 1).padStart(2, '0')
      const d = String(now.getDate()).padStart(2, '0')
      const h = String(now.getHours()).padStart(2, '0')
      this.form = {
        orderCode: '',
        engineType: '',
        productName: '',
        projectName: '',
        productionType: 'MAIN',
        startPlanTime: `${y}-${m}-${d} ${h}:00:00`
      }
      this.$nextTick(() => {
        if (formName && this.$refs[formName]) {
          this.$refs[formName].resetFields()
        }
      })
    },
    submitAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false
        }
        const 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]
        param[5] = ['生产类型', this.form.productionType]
        const Data = this.CreateData('11', '生产计划_派工订单_增加', param)
        this.ExecDatabase(Data).then(response => {
          const result = response.data && response.data[0] ? response.data[0] : {}
          if (result.result === 1) {
            this.$message({
              message: '订单创建成功',
              type: 'success'
            })
            this.pageCurrent = 1
            this.searchOrder()
            this.dialogFormVisible = false
          } else if (result.result === 2) {
            this.$message.error(result.msg || '该订单号已被使用，请使用其他订单号')
          } else {
            this.$message.error('订单创建失败！')
          }
        })
      })
    },
    callOff(formName) {
      this.dialogFormVisible = false
      if (formName && this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
    },
    handleEdit(row) {
      this.form1.orderNumber = row.订单号
      this.form1.engineTypeValue = row.产品型号
      this.form1.productName = row.产品名称
      this.form1.projectName = row.项目名称
      this.form1.productionType = row.生产类型 || ''
      this.form1.executeStatus = row.执行状态 !== undefined ? parseInt(row.执行状态) : 0
      // 处理时间格式：优先读取“计划开始时间”，兼容带时分秒与ISO格式
      const rawPlanTime = row.计划开始时间 || row.生产开始时间
      if (rawPlanTime) {
        const str = String(rawPlanTime)
        this.form1.startPlanTime = str.includes('T') ? str.replace('T', ' ').substring(0, 19) : str
      } else {
        this.form1.startPlanTime = ''
      }
      this.dialogFormVisible1 = true
    },
    submitEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false
        }
        const param = []
        param[0] = ['订单号', this.form1.orderNumber]
        param[1] = ['机型', this.form1.engineTypeValue]
        param[2] = ['产品名称', this.form1.productName]
        param[3] = ['项目名称', this.form1.projectName]
        param[4] = ['计划开始时间', this.form1.startPlanTime]
        param[5] = ['生产类型', this.form1.productionType]
        param[6] = ['执行状态', this.form1.executeStatus]
        const Data = this.CreateData('11', '生产计划_派工订单_修改', param)
        this.ExecDatabase(Data).then(response => {
          const result = response.data && response.data[0] ? response.data[0] : {}
          if (result.result === 1) {
            this.$message({
              message: '订单修改成功',
              type: 'success'
            })
            this.pageCurrent = 1
            this.searchOrder()
            this.dialogFormVisible1 = false
          } else {
            this.$message.error(result.msg || '订单修改失败！')
          }
        })
      })
    },
    callOff1() {
      this.dialogFormVisible1 = false
      if (this.$refs['form1']) {
        this.$refs['form1'].resetFields()
      }
    },
    planIssue(row) {
      this.$confirm(`确定下发订单吗？下发后进入生产队列开始生产，生产后不可取消下发与修改订单信息 <i style="color: red">  机型：${row.产品型号}，订单号：${row.订单号}</i> `, '提示', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = []
        const Data = this.CreateData('11', 'MES_计划BOM_发动机订单计划_滞留判断', param)
        this.ExecDatabase(Data).then(response => {
          const result = response.data && response.data[0] ? response.data[0] : {}
          if (result.result === 1) {
            this.updateOrderStatus(row.MID, 1)
          } else if (result.result === 2) {
            this.$confirm(`<i style="color: red">${result.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)
      })
    },
    planIsStop(row) {
      this.$confirm('确定暂停此订单吗', '提示', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateOrderStatus(row.MID, 2)
      })
    },
    updateOrderStatus(MID, type) {
      const param = []
      param[0] = ['MID', MID]
      param[1] = ['type', type]
      const Data = this.CreateData('11', 'MES_计划BOM_发动机订单计划_状态修改', param)
      this.ExecDatabase(Data).then(response => {
        const result = response.data && response.data[0] ? response.data[0] : {}
        if (result.result === 1) {
          this.$message.success('订单状态操作成功！')
          this.pageCurrent = 1
          this.searchOrder()
        } else {
          this.$message.error(result.msg || '订单状态操作失败')
        }
      })
    },
    deleteOrder(row) {
      this.$confirm('此操作将永久删除该行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = []
        param[0] = ['订单号', row.订单号]
        const Data = this.CreateData('11', '订单计划_删除', param)
        this.ExecDatabase(Data).then(response => {
          const result = response.data && response.data[0] ? response.data[0] : {}
          if (result.result === 1) {
            this.$message({
              message: result.msg,
              type: 'success'
            })
            this.pageCurrent = 1
            this.searchOrder()
          } else {
            this.$message.error(result.msg || '删除失败')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.expandsDetail = []
      this.searchOrder()
    },
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.expandsDetail = []
      this.searchOrder()
    },
    modifyOrderSort(row) {
      this.sortForm.ID = row.ID
      this.sortForm.订单号 = row.订单号
      this.sortForm.项目名称 = row.项目名称
      const rawPlanTime = row.计划开始时间
      if (rawPlanTime) {
        const str = String(rawPlanTime)
        this.sortForm.计划开始时间 = str.includes('T') ? str.replace('T', ' ').substring(0, 19) : str
      } else {
        this.sortForm.计划开始时间 = ''
      }
      this.dialogFormVisibleSort = true
    },
    submitSort() {
      this.$refs.sortForm.validate((valid) => {
        if (!valid) {
          return false
        }
        if (this.sortForm.ID === null || this.sortForm.ID === undefined || this.sortForm.ID === '') {
          this.$message.error('缺少订单主键ID，无法调整')
          return
        }
        const param = []
        param[0] = ['ID', this.sortForm.ID]
        param[1] = ['计划开始时间', this.sortForm.计划开始时间]
        const Data = this.CreateData('11', '生产计划_派工订单_执行计划_计划开始时间修改', param)
        this.ExecDatabase(Data).then(response => {
          const result = response.data && response.data[0] ? response.data[0] : {}
          if (result.result === 1) {
            this.$message.success(result.msg || '修改成功！')
            this.dialogFormVisibleSort = false
            this.searchOrder()
          } else {
            this.$message.error(result.msg || '修改失败')
          }
        }).catch(error => {
          this.$message.error('修改失败：' + error.message)
        })
      })
    },
    cancelSort() {
      this.dialogFormVisibleSort = false
      this.sortForm.ID = null
      if (this.$refs.sortForm) {
        this.$refs.sortForm.resetFields()
      }
    },
    handleManualJob(row, jobType) {
      const parentRow = this.tableData.find(item => 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 => {
          const successMessage = isStart ? '开工报工成功' : '完工报工成功'
          const errorMessage = isStart ? '开工报工失败：' : '完工报工失败：'
          if (response.data && response.data.code === 200) {
            this.$message.success(successMessage)
            this.selectPlan(parentRow, [parentRow])
          } else {
            this.$message.error(errorMessage + (response.data && response.data.message ? response.data.message : '未知错误'))
          }
        }).catch(error => {
          const errorMessage = isStart ? '开工报工失败：' : '完工报工失败：'
          this.$message.error(errorMessage + error.message)
        })
      })
    }
  }
}
</script>

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

.topDiv {
  margin-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.topDiv>* {
  margin-top: 5px;
}

.el-select {
  width: 200px;
}

.el-input {
  width: 200px;
}

.edit-order-form {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0 20px;
}

.edit-order-form__full {
  grid-column: 1 / -1;
}
</style>
