<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="margin-left: 10px">间隔编号：</span>
        <el-input
          v-model="searchForm.间隔编号"
          clearable
          placeholder="请输入间隔编号"
          size="small"
          style="width: 150px"
        />
        <span style="margin-left: 10px">间隔图号：</span>
        <el-input
          v-model="searchForm.间隔图号"
          clearable
          placeholder="请输入间隔图号"
          size="small"
          style="width: 150px"
        />
        <span style="margin-left: 10px">部件位置：</span>
        <el-input
          v-model="searchForm.部件位置"
          clearable
          placeholder="请输入部件位置"
          size="small"
          style="width: 150px"
        />
        <span style="margin-left: 10px">开始日期：</span>
        <el-date-picker
          v-model="searchForm.计划开始时间"
          placeholder="选择开始日期"
          size="small"
          type="date"
          value-format="yyyy-MM-dd"
        />
        <span style="margin-left: 10px">结束日期：</span>
        <el-date-picker
          v-model="searchForm.计划完成时间"
          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="success" @click="creatOrder('form')">
          创建生产订单
        </el-button>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        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-row-keys="expandRowKeys"
        row-key="MID"
        @expand-change="handleExpandChange"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <div style="padding: 10px 50px">
              <el-table :data="props.row.workStationList" border size="mini" style="width: 100%">
                <el-table-column align="center" label="工位号" width="120">
                  <template slot-scope="scope">
                    {{ scope.row.工位号 }}
                  </template>
                </el-table-column>
                <el-table-column align="center" label="执行状态" width="100">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.执行状态 === 0" size="mini" type="warning">未开始</el-tag>
                    <el-tag v-else-if="scope.row.执行状态 === 1" size="mini" type="primary">进行中</el-tag>
                    <el-tag v-else-if="scope.row.执行状态 === 2" size="mini" type="success">已完成</el-tag>
                    <el-tag v-else size="mini" type="info">{{ scope.row.执行状态 }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="开始时间" width="180">
                  <template slot-scope="scope">
                    {{ scope.row.开始时间 ? formatDateTime(scope.row.开始时间) : '-' }}
                  </template>
                </el-table-column>
                <el-table-column align="center" label="结束时间" width="180">
                  <template slot-scope="scope">
                    {{ scope.row.结束时间 ? formatDateTime(scope.row.结束时间) : '-' }}
                  </template>
                </el-table-column>
                <el-table-column align="center" label="持续时间(分钟)" width="130">
                  <template slot-scope="scope">
                    {{
                      scope.row.持续时间 !== null && scope.row.持续时间 !== undefined
                        ? formatDuration(scope.row.持续时间)
                        : '-'
                    }}
                  </template>
                </el-table-column>
                <el-table-column align="center" label="操作时间" width="180">
                  <template slot-scope="scope">
                    {{ scope.row.操作时间 ? formatDateTime(scope.row.操作时间) : '-' }}
                  </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="120">
                  <template slot-scope="scope">
                    <el-button
                      v-if="scope.row.执行状态 === 0"
                      icon="el-icon-video-play"
                      size="mini"
                      type="text"
                      style="color: #409eff"
                      @click="handleWorkStationStart(props.row, scope.row)"
                      >手动开工
                    </el-button>
                    <el-button
                      v-else-if="scope.row.执行状态 === 1"
                      icon="el-icon-circle-check"
                      size="mini"
                      type="text"
                      style="color: #67c23a"
                      @click="handleWorkStationFinish(props.row, scope.row)"
                      >手动完工
                    </el-button>
                    <el-button
                      v-else-if="scope.row.执行状态 === 2"
                      icon="el-icon-refresh-left"
                      size="mini"
                      type="text"
                      style="color: #e6a23c"
                      @click="handleWorkStationReset(props.row, scope.row)"
                      >重置状态
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="MID" width="80">
          <template slot-scope="scope">
            {{ scope.row.MID }}
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="制造编号" width="120">
          <template slot-scope="scope">
            {{ scope.row.制造编号 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="项目名称" width="150">
          <template slot-scope="scope">
            {{ scope.row.项目名称 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="间隔图号" width="150">
          <template slot-scope="scope">
            {{ scope.row.间隔图号 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="间隔编号" width="100">
          <template slot-scope="scope">
            {{ scope.row.间隔编号 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="部件位置" width="100">
          <template slot-scope="scope">
            {{ scope.row.部件位置 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="OP010" width="70">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.OP10状态 === 0" size="mini" type="info">未开始</el-tag>
            <el-tag v-else-if="scope.row.OP10状态 === 1" size="mini" type="warning">进行中</el-tag>
            <el-tag v-else-if="scope.row.OP10状态 === 2" size="mini" type="success">已完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="OP020" width="70">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.OP20状态 === 0" size="mini" type="info">未开始</el-tag>
            <el-tag v-else-if="scope.row.OP20状态 === 1" size="mini" type="warning">进行中</el-tag>
            <el-tag v-else-if="scope.row.OP20状态 === 2" size="mini" type="success">已完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="OP030" width="70">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.OP30状态 === 0" size="mini" type="info">未开始</el-tag>
            <el-tag v-else-if="scope.row.OP30状态 === 1" size="mini" type="warning">进行中</el-tag>
            <el-tag v-else-if="scope.row.OP30状态 === 2" size="mini" type="success">已完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="OP040" width="70">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.OP40状态 === 0" size="mini" type="info">未开始</el-tag>
            <el-tag v-else-if="scope.row.OP40状态 === 1" size="mini" type="warning">进行中</el-tag>
            <el-tag v-else-if="scope.row.OP40状态 === 2" size="mini" type="success">已完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="OP050" width="70">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.OP50状态 === 0" size="mini" type="info">未开始</el-tag>
            <el-tag v-else-if="scope.row.OP50状态 === 1" size="mini" type="warning">进行中</el-tag>
            <el-tag v-else-if="scope.row.OP50状态 === 2" size="mini" type="success">已完成</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="计划开始时间" width="180">
          <template slot-scope="scope">
            {{ scope.row.计划开始时间 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单状态" width="90">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.订单状态 === 0" size="mini" type="info">未下发</el-tag>
            <el-tag v-else-if="scope.row.订单状态 === 1" size="mini" type="warning">已下发</el-tag>
            <el-tag v-else-if="scope.row.订单状态 === 2" size="mini" type="primary">进行中</el-tag>
            <el-tag v-else size="mini" type="success">已完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" min-width="250" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.订单状态 === 0"
              icon="el-icon-s-promotion"
              size="mini"
              type="text"
              style="color: #409eff"
              @click="releaseOrder(scope.row)"
              >下发计划
            </el-button>
            <el-button
              v-if="scope.row.订单状态 === 1"
              icon="el-icon-refresh-left"
              size="mini"
              type="text"
              style="color: #e6a23c"
              @click="cancelReleaseOrder(scope.row)"
              >取消下发
            </el-button>
            <el-button
              icon="el-icon-edit"
              size="mini"
              type="text"
              :disabled="scope.row.订单状态 !== 0"
              @click="handleEdit(scope.row)"
              >修改
            </el-button>
            <el-button
              icon="el-icon-delete"
              size="mini"
              style="color: red"
              type="text"
              :disabled="scope.row.订单状态 !== 0"
              @click="deleteOrder(scope.row)"
              >删除
            </el-button>
            <el-button
              icon="el-icon-printer"
              size="mini"
              type="text"
              style="color: #67c23a"
              @click="printProduct(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 title="创建生产订单" width="700px">
      <el-form ref="form" :model="form" :rules="rules" label-position="right" label-width="110px">
        <el-form-item label="制造编号" prop="制造编号" style="display: inline-block">
          <el-input
            v-model="form.制造编号"
            clearable
            placeholder="请输入制造编号(仅支持英文/数字)"
            size="small"
            @input="validateEngNum('制造编号', 'form')"
          />
        </el-form-item>
        <el-form-item label="项目名称" prop="项目名称" style="display: inline-block">
          <el-input v-model="form.项目名称" clearable placeholder="请输入项目名称" size="small" />
        </el-form-item>
        <el-form-item label="间隔图号" prop="间隔图号" style="display: inline-block">
          <el-select
            v-model="form.间隔图号"
            clearable
            filterable
            placeholder="请选择间隔图号"
            size="small"
            @change="handleProductChange"
          >
            <el-option
              v-for="item in productTypeList"
              :key="item.产品型号代码"
              :label="item.产品型号"
              :value="item.产品型号"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="间隔编号" prop="间隔编号" style="display: inline-block">
          <el-input
            v-model="form.间隔编号"
            clearable
            placeholder="请输入间隔编号(仅支持英文/数字)"
            size="small"
            @input="validateEngNum('间隔编号', 'form')"
          />
        </el-form-item>
        <el-form-item label="部件位置" prop="部件位置" style="display: inline-block">
          <el-input
            v-model="form.部件位置"
            clearable
            placeholder="输入框的内容，固定为GCB"
            size="small"
            readonly
            value="GCB"
          />
        </el-form-item>
        <el-form-item label="计划开始时间" prop="计划开始时间" style="display: inline-block">
          <el-date-picker
            v-model="form.计划开始时间"
            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 title="修改生产订单" width="700px">
      <el-form ref="form1" :model="form1" :rules="rules1" label-position="right" label-width="110px">
        <el-form-item label="MID" prop="MID" style="display: inline-block">
          <el-input v-model="form1.MID" placeholder="MID" readonly size="small" />
        </el-form-item>
        <el-form-item label="制造编号" prop="制造编号" style="display: inline-block">
          <el-input
            v-model="form1.制造编号"
            placeholder="请输入制造编号(仅支持英文/数字)"
            size="small"
            @input="validateEngNum('制造编号', 'form1')"
          />
        </el-form-item>
        <el-form-item label="项目名称" prop="项目名称" style="display: inline-block">
          <el-input v-model="form1.项目名称" placeholder="请输入项目名称" size="small" />
        </el-form-item>
        <el-form-item label="间隔图号" prop="间隔图号" style="display: inline-block">
          <el-select
            v-model="form1.间隔图号"
            clearable
            filterable
            placeholder="请选择间隔图号"
            size="small"
            @change="handleProductChange1"
          >
            <el-option
              v-for="item in productTypeList"
              :key="item.产品型号代码"
              :label="item.产品型号"
              :value="item.产品型号"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="间隔编号" prop="间隔编号" style="display: inline-block">
          <el-input
            v-model="form1.间隔编号"
            placeholder="请输入间隔编号(仅支持英文/数字)"
            size="small"
            @input="validateEngNum('间隔编号', 'form1')"
          />
        </el-form-item>
        <el-form-item label="部件位置" prop="部件位置" style="display: inline-block">
          <el-input v-model="form1.部件位置" placeholder="请输入部件位置" readonly value="GCB" size="small" />
        </el-form-item>
        <el-form-item label="计划开始时间" prop="计划开始时间" style="display: inline-block">
          <el-date-picker
            v-model="form1.计划开始时间"
            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>
  </div>
</template>

<script>
import { Mqtt } from '../../../utils/mqtt.js'

export default {
  name: 'ProductionPlanManager',
  data() {
    return {
      mqttClient: null,
      mqttConnection: {
        host: window.g.mqttIP,
        port: window.g.mqttPortNumber,
        endpoint: '/mqtt',
        clean: true,
        connectTimeout: 4000,
        reconnectPeriod: 4000,
        clientId: '',
        username: 'MES_Manager',
        password: '123456'
      },
      publication: {
        topic: '',
        qos: 0,
        payload: ''
      },
      productTypeList: [], // 产品型号列表（用于间隔图号下拉选择）
      searchForm: {
        间隔编号: '',
        间隔图号: '',
        部件位置: '',
        计划开始时间: '',
        计划完成时间: ''
      },
      form: {
        制造编号: '',
        项目名称: '',
        间隔图号: '',
        间隔编号: '',
        部件位置: 'GCB',
        产品型号代码: null,
        计划开始时间: ''
      },
      rules: {
        制造编号: [{ required: true, message: '请输入制造编号', trigger: 'blur' }],
        项目名称: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        间隔图号: [{ required: true, message: '请选择间隔图号', trigger: 'change' }],
        间隔编号: [{ required: true, message: '请输入间隔编号', trigger: 'blur' }],
        部件位置: [{ required: true, message: '请输入部件位置', trigger: 'blur' }],
        计划开始时间: [{ required: true, message: '请选择计划开始时间', trigger: 'change' }]
      },
      form1: {
        MID: '',
        制造编号: '',
        项目名称: '',
        间隔图号: '',
        间隔编号: '',
        部件位置: '',
        产品型号代码: null,
        计划开始时间: ''
      },
      rules1: {
        制造编号: [{ required: true, message: '请输入制造编号', trigger: 'blur' }],
        项目名称: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        间隔图号: [{ required: true, message: '请选择间隔图号', trigger: 'change' }],
        间隔编号: [{ required: true, message: '请输入间隔编号', trigger: 'blur' }],
        部件位置: [{ required: true, message: '请输入部件位置', trigger: 'blur' }],
        计划开始时间: [{ required: true, message: '请选择计划开始时间', trigger: 'change' }]
      },
      tableData: [],
      expandRowKeys: [], // 展开的行的key列表
      dialogFormVisible: false,
      dialogFormVisible1: false,
      total: 0,
      pageSize: 30,
      pageCurrent: 1,
      loading: false
    }
  },
  created() {
    this.getProductTypeList()
    this.searchOrder()
    // 定时重新读取数据
    setInterval(() => {
      this.searchOrder()
    }, 1000 * 10)
  },
  mounted() {
    if (window.g.mqttClient) {
      window.g.mqttClient.destroyConnection()
    }
    window.g.mqttClient = new Mqtt(this.mqttConnection)
    window.g.mqttClient.createConnection()
    window.g.mqttClient.client.on('connect', () => {
      console.log('MQTT Connection succeeded!')
    })
    window.g.mqttClient.client.on('error', error => {
      console.log('MQTT Connection failed', error)
    })
    window.g.mqttClient.client.on('message', (topic, message) => {
      console.log('Received message:', topic, message.toString())
    })
  },
  beforeDestroy() {
    if (window.g.mqttClient && window.g.mqttClient.client.connected) {
      const destroyConnection = window.g.mqttClient.destroyConnection()
      if (destroyConnection) {
        console.log('MQTT disconnected!')
      } else {
        console.log('MQTT disconnect failed!')
      }
    }
  },
  methods: {
    // 处理展开行变化
    handleExpandChange(row, expandedRows) {
      // 当前行是否展开
      const isExpanded = expandedRows.some(item => item.MID === row.MID)

      if (isExpanded && (!row.workStationList || row.workStationList.length === 0)) {
        // 如果展开且还没有加载工位数据，则去加载
        this.loadWorkStationData(row)
      }
    },
    // 加载工位状态数据
    loadWorkStationData(row) {
      const param = []
      param[0] = ['MID', row.MID]
      const Data = this.CreateData('11', '生产计划_派工订单_工位状态_查询', param)
      this.ExecDatabase(Data)
        .then(response => {
          if (response.data && response.data.length > 0) {
            // 将工位数据赋值给当前行
            this.$set(row, 'workStationList', response.data)
          } else {
            this.$set(row, 'workStationList', [])
            this.$message.info('该订单暂无工位状态数据')
          }
        })
        .catch(() => {
          this.$set(row, 'workStationList', [])
          this.$message.error('加载工位状态数据失败')
        })
    },
    // 手动开工
    handleWorkStationStart(orderRow, workStationRow) {
      this.$confirm(`确认开工操作？<br/><i style="color: #409EFF">工位：${workStationRow.工位号}</i>`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      })
        .then(() => {
          const param = []
          param[0] = ['制造编号', orderRow.制造编号]
          param[1] = ['间隔编号', orderRow.间隔编号]
          param[2] = ['工位号', workStationRow.工位号]
          param[3] = ['Type', 1]
          const Data = this.CreateData('11', '生产计划_派工订单_工位状态_开完工', param)
          this.ExecDatabase(Data)
            .then(response => {
              if (response.data[0].result === 1) {
                this.$message.success(response.data[0].msg || '开工成功！')
                const currentMID = orderRow.MID
                // 先刷新主表，等主表数据更新后再刷新子表
                this.searchOrder()
                // 延迟刷新工位数据，确保主表刷新完成，并重新找到当前行
                setTimeout(() => {
                  const targetRow = this.tableData.find(row => row.MID === currentMID)
                  if (targetRow) {
                    this.loadWorkStationData(targetRow)
                  }
                }, 500)
              } else {
                this.$message.error(response.data[0].msg || '开工失败！')
              }
            })
            .catch(() => {
              this.$message.error('开工操作失败！')
            })
        })
        .catch(() => {
          this.$message.info('已取消操作')
        })
    },
    // 手动完工
    handleWorkStationFinish(orderRow, workStationRow) {
      this.$confirm(`确认完工操作？<br/><i style="color: #67C23A">工位：${workStationRow.工位号}</i>`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      })
        .then(() => {
          const param = []
          param[0] = ['制造编号', orderRow.制造编号]
          param[1] = ['间隔编号', orderRow.间隔编号]
          param[2] = ['工位号', workStationRow.工位号]
          param[3] = ['Type', 2]
          const Data = this.CreateData('11', '生产计划_派工订单_工位状态_开完工', param)
          this.ExecDatabase(Data)
            .then(response => {
              if (response.data[0].result === 1) {
                this.$message.success(response.data[0].msg || '完工成功！')
                const currentMID = orderRow.MID
                // 先刷新主表，等主表数据更新后再刷新子表
                this.searchOrder()
                setTimeout(() => {
                  const targetRow = this.tableData.find(row => row.MID === currentMID)
                  if (targetRow) {
                    this.loadWorkStationData(targetRow)
                  }
                }, 1000)
              } else {
                this.$message.error(response.data[0].msg || '完工失败！')
              }
            })
            .catch(() => {
              this.$message.error('完工操作失败！')
            })
        })
        .catch(() => {
          this.$message.info('已取消操作')
        })
    },
    // 重置状态
    handleWorkStationReset(orderRow, workStationRow) {
      this.$confirm(
        `确认重置工位状态？<br/><i style="color: #E6A23C">工位：${workStationRow.工位号}<br/>将清空开始时间、结束时间、持续时间，恢复为未开始状态</i>`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      )
        .then(() => {
          const param = []
          param[0] = ['制造编号', orderRow.制造编号]
          param[1] = ['间隔编号', orderRow.间隔编号]
          param[2] = ['工位号', workStationRow.工位号]
          param[3] = ['Type', 3]
          const Data = this.CreateData('11', '生产计划_派工订单_工位状态_开完工', param)
          this.ExecDatabase(Data)
            .then(response => {
              if (response.data[0].result === 1) {
                this.$message.success(response.data[0].msg || '重置成功！')
                const currentMID = orderRow.MID
                // 先刷新主表，等主表数据更新后再刷新子表
                this.searchOrder()
                setTimeout(() => {
                  const targetRow = this.tableData.find(row => row.MID === currentMID)
                  if (targetRow) {
                    this.loadWorkStationData(targetRow)
                  }
                }, 1000)
              } else {
                this.$message.error(response.data[0].msg || '重置失败！')
              }
            })
            .catch(() => {
              this.$message.error('重置操作失败！')
            })
        })
        .catch(() => {
          this.$message.info('已取消操作')
        })
    },
    // 打印产品条码（通过MQTT下发打印指令）
    printProduct(row) {
      try {
        if (!window.g.mqttClient || !window.g.mqttClient.client) {
          this.$message.error('MQTT未连接，无法发送打印请求')
          return
        }

        const projectName = row.项目名称 || ''
        const partLocation = row.部件位置 || ''
        const splitCode = row.间隔编号 || ''

        // Code0 内容是 项目名称&间隔编号&部件位置
        const qrCodeValue = `${projectName}&${splitCode}&${partLocation}`

        // 按规则：OP010~1~模板名|QR_Code^Code0^...|TEXT^TEXT2^...|TEXT^TEXT1^...|TEXT^TEXT0^...
        const deviceCode = 'OP010'
        const templateName = window.g.printTemplate
        this.publication.topic = window.g.mqttPublishTopic
        this.publication.payload = `${deviceCode}~1~${templateName}|QR_Code^Code0^${qrCodeValue}|TEXT^TEXT2^部件位置：${partLocation}|TEXT^TEXT1^间隔编号：${splitCode}|TEXT^TEXT0^项目名称：${projectName}`
        const result = window.g.mqttClient.doPublish(this.publication)
        console.log('print product ->', result, this.publication.payload)
        this.$message.success('产品条码打印请求已发送！')
      } catch (err) {
        console.error('printProduct error:', err)
        this.$message.error('产品条码打印失败！')
      }
    },
    // 获取产品型号列表（用于间隔图号下拉）
    getProductTypeList() {
      const param = []
      const Data = this.CreateData('11', 'MES_基本变量_机型代码_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0) {
          this.productTypeList = response.data
        }
      })
    },
    // 间隔图号变更（新增表单）- 同步产品型号代码
    handleProductChange(value) {
      const selectedProduct = this.productTypeList.find(item => item.产品型号 === value)
      if (selectedProduct) {
        this.form.产品型号代码 = selectedProduct.产品型号代码
      } else {
        this.form.产品型号代码 = null
      }
    },
    // 间隔图号变更（修改表单）- 同步产品型号代码
    handleProductChange1(value) {
      const selectedProduct = this.productTypeList.find(item => item.产品型号 === value)
      if (selectedProduct) {
        this.form1.产品型号代码 = selectedProduct.产品型号代码
      } else {
        this.form1.产品型号代码 = null
      }
    },
    // 格式化日期时间
    formatDateTime(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    // 格式化持续时间（秒转分钟）
    formatDuration(seconds) {
      if (seconds === null || seconds === undefined || seconds === 0) return '0'
      // 将秒转换为分钟，保留2位小数
      const minutes = Math.abs(seconds / 60)
      return minutes.toFixed(2)
    },
    // 验证仅允许英文和数字
    validateEngNum(fieldName, formName) {
      // 移除中文字符，只保留英文、数字和常见符号
      const value = this[formName][fieldName]
      if (value) {
        // 正则：只保留英文字母、数字、横线、下划线
        // eslint-disable-next-line no-control-regex
        const filtered = value.replace(/[^\x00-\xff]/g, '')
        if (filtered !== value) {
          this[formName][fieldName] = filtered
          this.$message.warning('制造编号和间隔编号仅支持英文和数字')
        }
      }
    },
    // 查询订单
    searchOrder() {
      this.loading = true
      const param = []
      param[0] = ['计划开始时间', this.searchForm.计划开始时间 || '']
      param[1] = ['计划完成时间', this.searchForm.计划完成时间 || '']
      param[2] = ['间隔编号', this.searchForm.间隔编号 || '']
      param[3] = ['间隔图号', this.searchForm.间隔图号 || '']
      param[4] = ['部件位置', this.searchForm.部件位置 || '']
      param[5] = ['PageCurrent', this.pageCurrent]
      param[6] = ['PageSize', this.pageSize]
      param[7] = ['PageCount', '1111', 'int', '1']
      param[8] = ['ItemCount', '1111', 'int', '1']
      const Data = this.CreateData('11', 'MES_计划BOM_发动机订单计划_查询分页', param)
      this.ExecDatabase(Data)
        .then(response => {
          if (response.data.result && response.data.result.length !== 0) {
            // 保存旧数据中已加载的工位状态列表
            const oldWorkStationMap = {}
            this.tableData.forEach(row => {
              if (row.workStationList && row.workStationList.length > 0) {
                oldWorkStationMap[row.MID] = row.workStationList
              }
            })

            // 更新表格数据
            this.tableData = response.data.result

            // 恢复已加载的工位状态数据
            this.tableData.forEach(row => {
              if (oldWorkStationMap[row.MID]) {
                this.$set(row, 'workStationList', oldWorkStationMap[row.MID])
              }
            })
          } else {
            this.tableData = []
          }
          if (response.data.output && response.data.output.length > 0) {
            this.total = parseInt(response.data.output[0].ItemCount)
          } else {
            this.total = 0
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 创建订单
    creatOrder(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
      this.form = {
        制造编号: '',
        项目名称: '',
        间隔图号: '',
        间隔编号: 'OB',
        部件位置: 'GCB',
        产品型号代码: null,
        计划开始时间: ''
      }
      this.dialogFormVisible = true
    },
    // 提交新增订单
    submitAdd(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 处理间隔编号，如果是纯数字，前面加OB
          let finalIntervalNumber = this.form.间隔编号
          if (finalIntervalNumber && !finalIntervalNumber.startsWith('OB')) {
            finalIntervalNumber = 'OB' + finalIntervalNumber
          }

          const param = []
          param[0] = ['制造编号', this.form.制造编号]
          param[1] = ['项目名称', this.form.项目名称]
          param[2] = ['间隔编号', finalIntervalNumber]
          param[3] = ['间隔图号', this.form.间隔图号]
          param[4] = ['部件位置', this.form.部件位置]
          param[5] = ['产品型号代码', this.form.产品型号代码]
          param[6] = ['计划开始时间', this.form.计划开始时间]
          const Data = this.CreateData('12', '生产计划_派工订单_增加', 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()
              this.dialogFormVisible = false
            } else {
              this.$message.error(response.data[0].msg || '订单创建失败！')
            }
          })
        } else {
          return false
        }
      })
    },
    // 取消新增订单
    callOff(formName) {
      this.dialogFormVisible = false
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    },
    // 删除订单
    deleteOrder(row) {
      this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const param = []
          param[0] = ['MID', row.MID]
          const Data = this.CreateData('12', '生产计划_派工订单_删除', param)
          this.ExecDatabase(Data)
            .then(() => {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.pageCurrent = 1
              this.pageSize = 30
              this.searchOrder()
            })
            .catch(() => {
              this.$message.error('删除失败')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 下发计划
    releaseOrder(row) {
      this.$confirm(
        `确认下发生产计划？<br/><i style="color: #409EFF">制造编号：${row.制造编号}，间隔编号：${row.间隔编号}</i>`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      )
        .then(() => {
          const param = []
          param[0] = ['MID', row.MID]
          const Data = this.CreateData('12', '生产计划_派工订单_计划下发', param)
          this.ExecDatabase(Data)
            .then(() => {
              this.$message({
                message: '计划下发成功！',
                type: 'success'
              })
              this.searchOrder()
            })
            .catch(() => {
              this.$message.error('计划下发失败！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    // 取消下发计划
    cancelReleaseOrder(row) {
      this.$confirm(
        `确认取消下发生产计划？<br/><i style="color: #E6A23C">制造编号：${row.制造编号}，间隔编号：${row.间隔编号}</i>`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      )
        .then(() => {
          const param = []
          param[0] = ['MID', row.MID]
          const Data = this.CreateData('12', '生产计划_派工订单_计划取消下发', param)
          this.ExecDatabase(Data)
            .then(() => {
              this.$message({
                message: '取消下发成功！',
                type: 'success'
              })
              this.searchOrder()
            })
            .catch(() => {
              this.$message.error('取消下发失败！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    // 修改订单
    handleEdit(row) {
      if (this.$refs['form1'] !== undefined) {
        this.$refs['form1'].resetFields()
      }
      this.form1.MID = row.MID
      this.form1.制造编号 = row.制造编号
      this.form1.项目名称 = row.项目名称
      this.form1.间隔图号 = row.间隔图号
      this.form1.间隔编号 = row.间隔编号
      this.form1.部件位置 = row.部件位置
      this.form1.产品型号代码 = row.产品型号代码
      this.form1.计划开始时间 = row.计划开始时间
      this.dialogFormVisible1 = true
    },
    // 提交修改订单
    submitAdd1() {
      this.$refs['form1'].validate(valid => {
        if (valid) {
          const param = []
          param[0] = ['MID', this.form1.MID]
          param[1] = ['制造编号', this.form1.制造编号]
          param[2] = ['项目名称', this.form1.项目名称]
          param[3] = ['间隔编号', this.form1.间隔编号]
          param[4] = ['间隔图号', this.form1.间隔图号]
          param[5] = ['部件位置', this.form1.部件位置]
          param[6] = ['产品型号代码', this.form1.产品型号代码]
          param[7] = ['计划开始时间', this.form1.计划开始时间]
          const Data = this.CreateData('12', '生产计划_派工订单_修改', 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()
              this.dialogFormVisible1 = false
            } else {
              this.$message.error(response.data[0].msg || '订单修改失败')
            }
          })
        } else {
          return false
        }
      })
    },
    // 取消修改订单
    callOff1() {
      this.dialogFormVisible1 = false
      if (this.$refs['form1'] !== undefined) {
        this.$refs['form1'].resetFields()
      }
    },
    // 分页
    handleSizeChange(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchOrder()
    },
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.searchOrder()
    }
  }
}
</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>
