<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-select v-model="searchForm.部件位置" clearable placeholder="请选择部件位置" size="small" style="width: 150px">
          <el-option v-for="item in partLocationList" :key="item" :label="item" :value="item" size="mini"/>
        </el-select>
        <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="distribution"
          @click="creatOrder('form')">创建订单
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        ref="multipleTable"
        :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">
        <el-table-column align="center" label="ID" width="80">
          <template slot-scope="scope">
            {{ scope.row.ID }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="制造编号">
          <template slot-scope="scope">
            {{ scope.row.制造编号 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="项目名称">
          <template slot-scope="scope">
            {{ scope.row.项目名称 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="部件位置">
          <template slot-scope="scope">
            {{ scope.row.部件位置 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="间隔编号">
          <template slot-scope="scope">
            {{ scope.row.间隔编号 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="计划开始时间">
          <template slot-scope="scope">
            {{ scope.row.计划开始时间 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单状态">
          <template slot-scope="scope">
            <el-tag v-if="!scope.row.完成时间" size="mini" type="warning">进行中</el-tag>
            <el-tag v-else size="mini" type="success">已完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="完成时间">
          <template slot-scope="scope">
            {{ scope.row.完成时间 ? formatDateTime(scope.row.完成时间) : '' }}
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="操作时间">
          <template slot-scope="scope">
            {{ scope.row.操作时间 ? formatDateTime(scope.row.操作时间) : '' }}
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="操作" min-width="250">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              size="mini"
              type="text"
              :disabled="scope.row.完成时间"
              @click="handleEdit(scope.row)">修改
            </el-button>
            <el-button
              icon="el-icon-delete"
              size="mini"
              style="color: red"
              type="text"
              :disabled="scope.row.完成时间"
              @click="deleteOrder(scope.row)">删除
            </el-button>
            <el-button
              icon="el-icon-check"
              size="mini"
              type="text"
              style="color: #67c23a"
              :disabled="scope.row.完成时间"
              @click="finishOrder(scope.row)">
              产品完工
            </el-button>
            <el-button
              icon="el-icon-printer"
              type="text"
              @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 style="min-height: 200px;" title="创建CT生产订单" 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"/>
        </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-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.部件位置" filterable placeholder="请选择部件位置" size="small">
            <el-option v-for="item in partLocationList" :key="item" :label="item" :value="item"/>
          </el-select>
        </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 style="min-height: 200px" title="编辑CT生产订单" width="700px">
      <el-form ref="form1" :model="form1" :rules="rules1" label-position="right" label-width="110px">
        <el-form-item label="ID" prop="ID" style="display: inline-block">
          <el-input v-model="form1.ID" placeholder="ID" readonly size="small"/>
        </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-input v-model="form1.项目名称" placeholder="请输入项目名称" size="small"/>
        </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.部件位置" filterable placeholder="请选择部件位置" size="small">
            <el-option v-for="item in partLocationList" :key="item" :label="item" :value="item"/>
          </el-select>
        </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: 'CTPlanManager',
  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: ''
      },
      partLocationList: ['CT上', 'CT下', 'CT左', 'CT右'],
      searchForm: {
        制造编号: '',
        项目名称: '',
        间隔编号: '',
        部件位置: '',
        计划开始时间: '',
        计划完成时间: ''
      },
      form: {
        制造编号: '',
        项目名称: '',
        部件位置: '',
        间隔编号: '',
        计划开始时间: ''
      },
      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: 'change' }]
      },
      form1: {
        ID: '',
        制造编号: '',
        项目名称: '',
        部件位置: '',
        间隔编号: '',
        计划开始时间: ''
      },
      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: 'change' }]
      },
      tableData: [],
      dialogFormVisible: false,
      dialogFormVisible1: false,
      total: 0,
      pageSize: 30,
      pageCurrent: 1,
      loading: false
    }
  },
  created() {
    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: {
    // 打印产品码（通过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('CT产品码打印请求已发送！')
      } catch (err) {
        console.error('printProduct error:', err)
        this.$message.error('CT产品码打印失败！')
      }
    },
    // 格式化日期时间
    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}`
    },
    // 查询订单
    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] = ['部件位置', this.searchForm.部件位置 || '']
      param[6] = ['PageCurrent', this.pageCurrent]
      param[7] = ['PageSize', this.pageSize]
      param[8] = ['PageCount', '1111', 'int', '1']
      param[9] = ['ItemCount', '1111', 'int', '1']
      const Data = this.CreateData('11', '生产计划_派工订单_CT_分页查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.result && response.data.result.length !== 0) {
          this.tableData = response.data.result
        } 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',
        项目名称: '',
        部件位置: '',
        间隔编号: '',
        计划开始时间: ''
      }
      this.dialogFormVisible = true
    },
    // 提交新增订单
    submitAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const param = []
          param[0] = ['制造编号', this.form.制造编号]
          param[1] = ['项目名称', this.form.项目名称]
          param[2] = ['部件位置', this.form.部件位置]
          param[3] = ['间隔编号', this.form.间隔编号]
          param[4] = ['计划开始时间', this.form.计划开始时间]
          const Data = this.CreateData('12', '生产计划_派工订单_CT_增加', 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] = ['ID', row.ID]
        const Data = this.CreateData('12', '生产计划_派工订单_CT_删除', 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: '已取消删除'
        })
      })
    },
    // 产品完工
    finishOrder(row) {
      this.$confirm(`确认产品完工？<br/><i style="color: #67c23a">制造编号：${row.制造编号}，间隔编号：${row.间隔编号}</i>`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const param = []
        param[0] = ['ID', row.ID]
        const Data = this.CreateData('11', '生产计划_派工订单_CT_产品完工', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === 1) {
            this.$message({
              message: '产品完工成功！',
              type: 'success'
            })
            this.searchOrder()
          } else {
            this.$message.error('产品完工失败！')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    // 修改订单
    handleEdit(row) {
      if (this.$refs['form1'] !== undefined) {
        this.$refs['form1'].resetFields()
      }
      this.form1.ID = row.ID
      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] = ['ID', this.form1.ID]
          param[1] = ['制造编号', this.form1.制造编号]
          param[2] = ['项目名称', this.form1.项目名称]
          param[3] = ['部件位置', this.form1.部件位置]
          param[4] = ['间隔编号', this.form1.间隔编号]
          param[5] = ['计划开始时间', this.form1.计划开始时间]
          const Data = this.CreateData('11', '生产计划_派工订单_CT_修改', 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>

