<template>
  <div style="width: 60px; height: 100%;background-color: #d7dee6;">
    <div style="display: flex;flex-direction: column;align-items: center;height: 100%;width: 100%;margin-top: -5px;">
      <!-- <div style="width:100%;font-size: 1rem;text-align: center;border-radius: 5px;background-color: #13227a;padding: 2px;">
        <div style="color: #ffffff;font-size: 0.8rem;display: flex;flex-direction: column;">
          <div style="display: flex;justify-content: space-around;width: 100%"><span>生</span><span>产</span></div>
          <div style="display: flex;justify-content: space-around;width: 100%"><span>计</span><span>时</span></div>
        </div>
        <div style="color: #ffffff;font-weight: bolder;margin-top: 2px;font-size: 0.9rem">
          {{opBeatInfo.累计时间}}
        </div>
      </div> -->
      <div class="plc-status">
        <div v-for="(item, index) in statusBarInformation" :id="item.id" :key="index" class="content">
          <div :id="item.id + 'status'" class="station" />
          <div class="station-label">{{ item.label }}</div>
        </div>
      </div>
      <div
        style="width:100%; display: flex;flex-direction: column;justify-content: flex-start;align-content: center;height: 240px;">
        <div v-if="showTightButton" class="functionButton" @click="showTightGuide">
          <img :src="require('@/assets/image/TighteningInstructions.png')" width="26px" />
          <div style="">
            <div>拧紧</div>
            <div>指导</div>
          </div>
        </div>
        <el-popover placement="left" width="200" trigger="click" popper-class="my-popper-class"
          style="background-color: #d7dee6;">
          <el-input v-model="barcodeValue" type="textarea" :rows="3" class="myCodeInput" placeholder="请输入物料条码"
            style="width: 99%;" />
          <el-button icon="el-icon-full-screen"
            style="color:#fff;font-size: 1rem;width: 99%;padding: 5px 0;background-color: #13227a;margin: 2px 0 0 0;"
            @click="scanBarcode()">
            扫描条码
          </el-button>
          <div class="functionButton" slot="reference">
            <img :src="require('@/assets/image/barCode.png')" width="26px" />
            <div style="">
              <div>手动</div>
              <div>扫码</div>
            </div>
          </div>
        </el-popover>
        <!-- 完工放行按钮 -->
        <!--        <el-popover placement="left" width="150" trigger="click" popper-class="my-popper-class"-->
        <!--          style="background-color: #d7dee6;">-->
        <!--          <div style="display: flex; flex-direction: column; align-items: center;">-->
        <!--            &lt;!&ndash; 合格放行按钮 &ndash;&gt;-->
        <!--            <div class="releaseButton" @click="qualifiedReleaseByDrawer"-->
        <!--              style="background-color: #00893d; width: 100%; margin-bottom: 10px;">-->
        <!--              <div style="margin-left: 10px;">-->
        <!--                <div style="font-size: 16px; font-weight: bold;">合格放行</div>-->
        <!--              </div>-->
        <!--            </div>-->
        <!--            &lt;!&ndash; 不合格放行按钮 &ndash;&gt;-->
        <!--            <div class="releaseButton" @click="unqualifiedReleaseDrawer"-->
        <!--              style="background-color: #ff4444; width: 100%;">-->
        <!--              <div style="margin-left: 10px;">-->
        <!--                <div style="font-size: 16px; font-weight: bold;">不合格放行</div>-->
        <!--              </div>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--          <div class="functionButton" slot="reference" v-show="showButtonIds.indexOf('MES_Select_OKNGGo') !== -1">-->
        <!--            <img :src="require('@/assets/image/passOK.png')" width="26px" />-->
        <!--            <div style="">-->
        <!--              <div>完工</div>-->
        <!--              <div>放行</div>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--        </el-popover>-->
        <div class="functionButton" slot="reference" v-show="showButtonIds.indexOf('MES_ReplaceBarCode') !== -1"
          @click="replaceBarCode">
          <img :src="require('@/assets/image/barCode.png')" width="26px" />
          <div style="">
            <div>补打</div>
            <div>条码</div>
          </div>
        </div>
        <div class="functionButton" slot="reference" v-show="showButtonIds.indexOf('MES_VisionOK') !== -1"
          @click="VisionOKNG('OK')">
          <img :src="require('@/assets/image/OperationGuide.png')" width="26px" />
          <div style="">
            <div>强制视</div>
            <div>觉OK</div>
          </div>
        </div>
        <div class="functionButton" slot="reference" v-show="showButtonIds.indexOf('MES_VisionNG') !== -1"
          @click="VisionOKNG('NG')">
          <img :src="require('@/assets/image/OperationGuide.png')" width="26px" />
          <div style="">
            <div>强制视</div>
            <div>觉NG</div>
          </div>
        </div>
        <div class="functionButton" slot="reference" v-show="showButtonIds.indexOf('MES_WeldOK') !== -1"
          @click="WeldResult">
          <img :src="require('@/assets/image/OperationGuide.png')" width="26px" />
          <div style="">
            <div>焊接</div>
            <div>结果</div>
          </div>
        </div>
        <div class="functionButton" slot="reference" v-show="showButtonIds.indexOf('MES_GetEngineIDModel') !== -1"
          :style="{ backgroundColor: autoApplyBarcode === 1 ? '#00893d' : '#ff0600' }" @click="toggleBarcodeApplyMode">
          <img :src="require('@/assets/image/barCode.png')" width="26px" />
          <div style="">
            <div>上线</div>
            <div>模式</div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog :append-to-body="true" :visible.sync="dialogFormVisible_tighten" :top="top" center
      style="text-align: center" title="手动拧紧指导" width="840px">
      <div style="width: 100%; height: 100%;color: #303030;">
        <el-row style="display: flex;align-items: center;justify-content: center">
          <img :src="tighteningGuidePic" width="817px" height="460px" />
          <div v-for="(item, index) in tighteningPosition" :key="index" :class="changBP(item)"
            :style="{ left: item.测量位置X + 'px', top: item.测量位置Y + 'px', height: item.控件高度 + 'px', width: item.控件宽度 + 'px', lineHeight: item.控件高度 + 'px' }">
            {{ index + 1 }}
          </div>
        </el-row>
        <el-row style="margin: 5px 0 0 0;height: 145px">
          <el-col :span="13" style="height: 100%;background-color: #fff;border-radius: 5px;">
            <el-col :span="12" style="border-right: 1px solid #d7dee6;">
              <div style="display: flex;text-align: center;background-color: #f9fbfe;color: #0b4db0;">
                <div style="flex: 0.5;">序号</div>
                <div style="flex: 1">扭矩</div>
                <div style="flex: 1">角度</div>
              </div>
              <div style="overflow: auto;height: 140px;">
                <div v-for="(item, index) in qualityDataNew" :key="index" :style="setQualityListRowStyle(item)"
                  style="display: flex;text-align: center;border-bottom: 1px solid #d7dee6;">
                  <div style="flex: 0.5">{{ item.序号 }}</div>
                  <div style="flex: 1">{{ item.扭矩 }}</div>
                  <div style="flex: 1">{{ item.转角 }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="12" style="">
              <div style="display: flex;text-align: center;background-color: #f9fbfe;color: #0b4db0;">
                <div style="flex: 0.5">序号</div>
                <div style="flex: 1">扭矩</div>
                <div style="flex: 1">角度</div>
              </div>
              <div v-if="qualityDataNew1.length > 0" style="overflow: auto;height: 140px;">
                <div v-for="(item, index) in qualityDataNew1" :key="index" :style="setQualityListRowStyle(item)"
                  style="display: flex;text-align: center;border-bottom: 1px solid #d7dee6;">
                  <div style="flex: 0.5">{{ item.序号 }}</div>
                  <div style="flex: 1">{{ item.扭矩 }}</div>
                  <div style="flex: 1">{{ item.转角 }}</div>
                </div>
              </div>
            </el-col>
          </el-col>
          <el-col :span="11" style="height: 100%;">
            <div style="margin-left: 5px;height: 100%;display: flex;flex-direction: column;">
              <div style="font-size: 1rem;font-weight: bolder;">
                <div>套筒选择</div>
              </div>
              <div style="display: flex;flex-wrap: wrap;">
                <div v-for="(item, index) in greenBoltInformation" :key="index"
                  style=" position: relative;width: 48px;height: 68px;margin: 0 1px">
                  <div class="bolt" />
                  <div class="green_bolt" :style="{ display: item.display }" />
                  <div v-if="item.display === 'none'" class="bolt-div">{{ index + 1 }}</div>
                  <div v-else class="bolt-div-active">{{ index + 1 }}</div>
                </div>
              </div>
              <div style="">
                <div style="font-size: 1rem;font-weight: bolder;">
                  <div>功能按钮</div>
                </div>
                <el-button v-if="showFalseGo" size="mini" type="danger" icon="el-icon-error"
                  @click="unqualifiedRelease">不合格放行</el-button>
                <el-button class="el-icon-close" type="info" size="mini"
                  @click="dialogFormVisible_tighten = false">关闭界面</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
    <el-dialog :append-to-body="true" :visible.sync="weldDialogVisible" title="焊接点合格状态" width="460px">
      <div class="weld-grid">
        <!-- @click="openWeldDetail(p)"  暂时不显示详细数据-->
        <div v-for="(p, idx) in weldPoints" :key="idx" class="weld-item">
          <div :class="['weld-dot', p.TagValue === 0 ? 'ok' : 'ng']"></div>
          <div class="weld-label">{{ p.name }}</div>
        </div>
      </div>
    </el-dialog>

    <el-dialog :append-to-body="true" :visible.sync="weldDetailDialogVisible" :title="'焊点详细数据 - ' + weldDetailTitle"
      width="820px">
      <el-table class="weld-detail-table" :data="weldDetailPagedList" border>
        <el-table-column align="center" header-align="center" prop="测量位置" label="测量位置" min-width="180" />
        <el-table-column align="center" header-align="center" prop="TagValue" label="值" min-width="80" />
        <el-table-column align="center" header-align="center" prop="合格标志" label="合格标志" min-width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row['合格标志'] === 1 ? 'success' : 'danger'" disable-transitions>
              {{ scope.row['合格标志'] === 1 ? '合格' : '不合格' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" header-align="center" prop="理论值" label="理论值" min-width="80" />
        <el-table-column align="center" header-align="center" prop="上限值" label="上限" min-width="80" />
        <el-table-column align="center" header-align="center" prop="下限值" label="下限" min-width="80" />
        <el-table-column align="center" header-align="center" prop="测量单位" label="单位" min-width="80" />
      </el-table>
      <div style="background-color: #f8f9fa; border-radius: 6px; border: 1px solid #e9ecef;text-align: center;">
        <el-button style="height: 40px; padding: 0 20px; font-size: 16px; font-weight: bold; min-width: 100px;"
          type="primary" icon="el-icon-arrow-left" :disabled="weldDetailPage <= 1"
          @click="changeWeldDetailPage(-1)">上一页</el-button>
        <div
          style="font-size: 15px; font-weight: 500; color: #495057; text-align: center; flex: 1; margin: 0 15px; display: inline-block;">
          第 {{ weldDetailPage }} / {{ weldDetailTotalPages }} 页</div>
        <el-button style="height: 40px; padding: 0 20px; font-size: 16px; font-weight: bold; min-width: 100px;"
          type="primary" icon="el-icon-arrow-right" :disabled="weldDetailPage >= weldDetailTotalPages"
          @click="changeWeldDetailPage(1)">下一页</el-button>
      </div>
    </el-dialog>
    <!-- 权限验证组件 -->
    <permission-verify ref="permissionVerify" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { stationIsWorking } from '@/utils/tool'
import PermissionVerify from '@/views/components/PermissionVerify.vue'

export default {
  name: 'LeftSidebar',
  components: {
    PermissionVerify
  },
  computed: {
    ...mapGetters([
      'greenBoltInformation',
      'tighteningPosition'
    ]),
    weldDetailTotalPages() {
      if (!this.weldDetailList || this.weldDetailList.length === 0) return 1
      return Math.max(1, Math.ceil(this.weldDetailList.length / this.weldDetailPageSize))
    },
    weldDetailPagedList() {
      const start = (this.weldDetailPage - 1) * this.weldDetailPageSize
      const end = start + this.weldDetailPageSize
      return (this.weldDetailList || []).slice(start, end)
    }
  },
  props: {
    outputBeatInformation: {
      type: Object,
      default: function () {
        return {}
      }
    },
    statusBarInformation: {
      type: Array,
      default: function () {
        return []
      }
    },
    qualityData: {
      type: Array,
      default: function () {
        return []
      }
    },
    qualityDataHeader: {
      type: Object,
      default: function () {
        return {}
      }
    },
    onlineStatus: {
      type: Boolean,
      default: function () {
        return true
      }
    },
    onlineStatus_PLC: {
      type: Boolean,
      default: function () {
        return false
      }
    }
  },
  data() {
    return {
      top: '0vh',
      showTightButton: false,
      opBeatInfo: {
        剩余时间1: '0:0',
        剩余时间: 0,
        标准时间1: '0:0',
        标准时间: 0,
        累计时间1: '0:0',
        累计时间: 0
      },
      opRepairOnLineInfo: {
        剩余时间1: '0:0',
        剩余时间: 0,
        标准时间1: '0:0',
        标准时间: 0,
        累计时间1: '0:0',
        累计时间: 0
      },
      cycleTimer: null,
      cycleTimer_RepairOnLine: null,
      cycleTimerStop: false,
      cycleTimerStop_RepairOnLine: false,
      qualityDataLast: [],
      qualityDataNew: [],
      qualityDataNew1: [],
      tighteningGuidePic: null,
      form: {
        measureData1: 0,
        measureData1_unit: 'N·m',
        measureData2: 0,
        measureData2_unit: '°',
        isOk: 0
      },
      showFalseGo: true,
      dialogFormVisible_tighten: false,
      onLine: true,
      cycleStart: true,
      barcodeValue: '',
      publication: {
        topic: '',
        qos: 0,
        payload: ''
      },
      textarea: '',
      timer: null,
      year: '',
      month: '',
      day: '',
      minute: '',
      hour: '',
      second: '',
      week: '',
      statisticsData: {
        planCount: 280,
        nowCount: 318,
        planBeat: 85,
        nowBeat: 69
      },
      showButtonIds: [],
      // 焊接结果弹窗
      weldDialogVisible: false,
      weldPoints: [],
      weldIdTagCF: null,
      // 焊点详细数据弹窗
      weldDetailDialogVisible: false,
      weldDetailTitle: '',
      weldDetailList: [],
      // 触摸屏分页（每页6条）
      weldDetailPage: 1,
      weldDetailPageSize: 6,
      // 条码申请模式
      autoApplyBarcode: 0 // 0: 非自动模式, 1: 自动模式
    }
  },
  watch: {
    statusBarInformation: {
      handler(newValue, oldName) {
        this.changeColor(newValue)
      },
      immediate: true,
      deep: true
    },
    'statusBarInformation.5.status': {
      handler(newValue, oldName) {
        // this.getNowCountData()
      },
      immediate: true,
      deep: true
    },
    qualityData: {
      handler(newValue, oldName) {
        if (this.qualityData.length > 1) {
          this.qualityDataNew = []
          this.qualityDataNew1 = []
          // this.qualityDataLast = this.qualityData.slice(-2)
          for (let i = 0; i < this.qualityData.length; i++) {
            if (i % 2 === 0) {
              this.qualityDataNew.push({
                序号: i / 2 + 1,
                扭矩: this.qualityData[i]['测量值'],
                转角: this.qualityData[i + 1]['测量值'],
                合格标志: parseInt(this.qualityData[i + 1]['合格标志'])
              })
            }
          }
          this.qualityDataNew1 = this.qualityDataNew.filter((_, index) => index % 2 === 1)
          this.qualityDataNew = this.qualityDataNew.filter((_, index) => index % 2 === 0)
          console.log(this.qualityDataNew)
          console.log(this.qualityDataNew1)
        } else {
          this.qualityDataNew = []
          this.qualityDataNew1 = []
        }
        this.showFalseGo = false
        for (let i = 0; i < this.qualityData.length; i++) {
          if (this.qualityData[i]['合格标志'] === '2') {
            this.showFalseGo = true
          }
        }
      }
    }
  },
  created() {

  },
  mounted() {
    this.getShowTightButton()
    this.getShowButtonIds()
    this.getTable()
    // this.timer = setInterval(() => {
    //   if (!this.cycleTimerStop) {
    //     if (stationIsWorking(this.$store.state)) {
    //       scope.CorrectiveTiming(this.$store.state.station.engineValue.EngineTypeID, this.$store.state.station.engineValue.EngineID)
    //     }
    //   }
    // //  if (stationIsWorking(this.$store.state)) {
    // //     if (this.$store.state.station.engineValue.EngineID !== '') {
    // //       scope.CorrectiveTiming_RepairOnLine(this.$store.state.station.engineValue.EngineTypeID, this.$store.state.station.engineValue.EngineID)
    // //     }
    // //   }
    // }, 10000)
    this.$eventBus.$on('ShaftPosition', msg => {
      console.log('ShaftPosition', msg)
      if (msg === '1') {
        this.dialogFormVisible_tighten = true
        this.getTable()
      } else {
        this.dialogFormVisible_tighten = false
      }
    })
    // 监听焊接结果弹窗事件
    this.$eventBus.$on('Show_OP170_WeldOKBox', () => { this.WeldResult() })
    window.addEventListener('resize', this.adjustTableHeight)
  },
  destroyed() {
    clearInterval(this.timer)
    clearInterval(this.cycleTimer)
  },
  methods: {
    adjustTableHeight() {
      this.$nextTick(() => {
        if (window.innerHeight < 760) {
          this.top = '0vh'
        } else {
          this.top = '5vh'
        }
      })
    },
    setQualityListRowStyle(row) {
      if (row['合格标志'] === 1) {
        return {
          backgroundColor: '#00893d', // 正在进行的
          color: '#fff'
        }
      }
      if (row['合格标志'] === 2) {
        return {
          backgroundColor: '#ff0000', // 完成的
          color: '#fff'
        }
      }
      // 未进行的
      return {}
    },
    WeldResult() {
      const EngineID = this.$store.state.station.engineValue && this.$store.state.station.engineValue.EngineID
      if (!EngineID) {
        this.$message({ type: 'warning', message: '请先扫码产品编号！' })
        return
      }

      const param = []
      param[0] = ['产品编号', EngineID]

      const Data = this.CreateData('11', 'MES_焊接点合格状态_工位查询', param)
      this.ExecDatabase(Data).then(response => {
        const list = response.data || []
        if (!list.length) {
          this.$message({ type: 'warning', message: '未查询到焊接点数据！' })
          return
        }

        // 保存 Id_tagCF
        this.weldIdTagCF = list[0]['Id_tagCF']

        // 解析名称与合格状态
        this.weldPoints = list.map(r => {
          const rawName = r['测量项目'] || ''
          const name = rawName.replace('_是否合格', '')
          const value = Number(r['TagValue']) === 1 ? 1 : 0
          return { name, TagValue: value, raw: r }
        })

        this.weldDialogVisible = true
      })
    },
    openWeldDetail(point) {
      const EngineID = this.$store.state.station.engineValue && this.$store.state.station.engineValue.EngineID
      if (!EngineID) {
        this.$message({ type: 'warning', message: '请先扫码产品编号！' })
        return
      }
      if (!this.weldIdTagCF) {
        this.$message({ type: 'warning', message: '缺少Id_TagCf，请先查询焊接点状态！' })
        return
      }

      const param = []
      param[0] = ['产品编号', EngineID]
      param[1] = ['Id_TagCf', this.weldIdTagCF]
      param[2] = ['Name', point.name]

      const Data = this.CreateData('11', 'MES_焊接点详细数据_工位查询', param)
      this.ExecDatabase(Data).then(response => {
        this.weldDetailTitle = point.name
        this.weldDetailList = response.data || []
        this.weldDetailPage = 1
        this.weldDetailDialogVisible = true
      })
    },
    changeWeldDetailPage(step) {
      const next = this.weldDetailPage + step
      if (next < 1) return
      if (next > this.weldDetailTotalPages) return
      this.weldDetailPage = next
    },
    showTightGuide() {
      if (!stationIsWorking(this.$store.state)) {
        this.$message.error('工位未在工作!')
        return
      }
      this.dialogFormVisible_tighten = true
    },
    getNowCountData() {
      const param = []
      param[0] = ['工位号', this.$store.state.station.stationNumber]
      const Data = this.CreateData('11', '工位产量节拍统计_查询', param)
      this.ExecDatabase(Data).then(response => {
        const data = response.data[0]
        this.statisticsData.planCount = data['计划产量']
        this.statisticsData.planBeat = data['计划节拍']
        this.statisticsData.nowCount = data['在线产量']
        this.statisticsData.nowBeat = data['在线节拍']
      })
    },
    getShowButtonIds() {
      this.showButtonIds = []
      const param = []
      param[0] = ['工位号', this.$store.state.station.stationNumber]
      const Data = this.CreateData('11', 'MES界面显示_功能按钮_查询', param)
      this.ExecDatabase(Data).then(response => {
        for (const item of response.data) {
          this.showButtonIds.push(item.按钮ID)
        }
        // 如果有条码申请模式按钮，则读取当前模式
        if (this.showButtonIds.indexOf('MES_GetEngineIDModel') !== -1) {
          this.getBarcodeApplyMode()
        }
      })
    },
    // 读取条码申请模式
    getBarcodeApplyMode() {
      const param = []
      param[0] = ['工位号', this.$store.state.station.stationNumber]
      param[1] = ['名称', '自动申请条码']
      const Data = this.CreateData('11', 'MES_持久化变量_读取', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0) {
          this.autoApplyBarcode = parseInt(response.data[0].值) || 0
        } else {
          this.autoApplyBarcode = 0
        }
      }).catch(() => {
        this.autoApplyBarcode = 0
      })
    },
    // 切换条码申请模式
    toggleBarcodeApplyMode() {
      const newMode = this.autoApplyBarcode === 1 ? 0 : 1
      const param = []
      param[0] = ['工位号', this.$store.state.station.stationNumber]
      param[1] = ['名称', '自动申请条码']
      param[2] = ['值', String(newMode)]
      const Data = this.CreateData('12', 'MES_持久化变量_写入', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result === '1') {
          this.publication.topic = window.g.mqttPublishTopic
          // 写入成功后重新从数据库读取状态
          this.getBarcodeApplyMode()
          if (newMode === 1) {
            this.$notify.success({
              title: '提示',
              message: '已切换为自动上线模式',
              position: 'bottom-right',
              duration: 2000,
              offset: 170
            })
            this.publication.payload = 'WEB|UpLinModelQut|' + this.$store.state.station.stationNumber + '|' + '0'
          } else {
            this.$notify.warning({
              title: '提示',
              message: '已切换为非自动上线模式',
              position: 'bottom-right',
              duration: 2000,
              offset: 170
            })
            this.publication.payload = 'WEB|UpLinModelQut|' + this.$store.state.station.stationNumber + '|' + '1'
          }
          window.g.mqttClient.doPublish(this.publication)
        } else {
          this.$notify.error({
            title: '提示',
            message: '模式切换失败！',
            position: 'bottom-right',
            duration: 2000,
            offset: 170
          })
        }
      }).catch(() => {
        this.$notify.error({
          title: '提示',
          message: '模式切换失败！',
          position: 'bottom-right',
          duration: 2000,
          offset: 170
        })
      })
    },
    tableRowClassName({ row }) {
      if (row.合格标志 === '1') {
        return 'green'
      } else {
        return 'red'
      }
    },
    scanBarcode() {
      if (this.barcodeValue) {
        this.publication.topic = window.g.mqttPublishTopic
        this.publication.payload = 'WEB|Barcode|' + this.$store.state.station.stationNumber + '|' + this.barcodeValue
        const result = window.g.mqttClient.doPublish(this.publication)
        if (result === true) {
          this.$notify.success({
            title: '提示',
            message: '条码发送成功！',
            position: 'bottom-right',
            duration: 2000,
            offset: 170
          })
          this.barcodeValue = ''
        } else {
          this.$notify.error({
            title: '提示',
            message: '条码发送失败！',
            position: 'bottom-right',
            duration: 2000,
            offset: 170
          })
        }
      } else {
        this.$notify.error({
          title: '提示',
          message: '请填写条码再发送！',
          position: 'bottom-right',
          duration: 2000,
          offset: 170
        })
      }
    },
    async replaceBarCode() {
      if (!stationIsWorking(this.$store.state)) {
        this.$message.error('工位未在工作!')
        return
      }
      // 权限验证
      const result = await this.$refs.permissionVerify.show({
        title: '补打条码',
        promptText: '请刷卡进行权限校验',
        permissionLevel: '操作工'
      })
      // 权限校验通过
      if (result.success) {
        this.publication.topic = window.g.mqttPublishTopic
        this.publication.payload = 'WEB|PrintCode|' + this.$store.state.station.stationNumber + '|' + this.$store.state.station.engineValue.EngineID
        const publishResult = window.g.mqttClient.doPublish(this.publication)
        if (publishResult === true) {
          this.$notify.success({
            title: '提示',
            message: '补打条码发送成功！',
            position: 'bottom-right',
            duration: 2000,
            offset: 170
          })
          this.barcodeValue = ''
        } else {
          this.$notify.error({
            title: '提示',
            message: '补打条码发送失败！',
            position: 'bottom-right',
            duration: 2000,
            offset: 170
          })
        }
      }
    },
    VisionOKNG(typeStr) {
      if (!stationIsWorking(this.$store.state)) {
        this.$message.error('工位未在工作!')
        return
      }
      // 二次确认
      this.$confirm(`确定强制视觉检测${typeStr}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.publication.topic = window.g.mqttPublishTopic
        this.publication.payload = `WEB|Vision${typeStr}|${this.$store.state.station.stationNumber}|${this.$store.state.station.engineValue.EngineID}`
        const result = window.g.mqttClient.doPublish(this.publication)
        if (result === true) {
          this.$notify.success({
            title: '提示',
            message: `视觉${typeStr}发送成功！`,
            position: 'bottom-right',
            duration: 2000,
            offset: 170
          })
        } else {
          this.$notify.error({
            title: '提示',
            message: `视觉${typeStr}发送失败！`,
            position: 'bottom-right',
            duration: 2000,
            offset: 170
          })
        }
      })
    },
    changeColor(newValue) {
      setTimeout(() => {
        for (let i = 0; i < newValue.length; i++) {
          const newValueStatus = Number(newValue[i].status)
          if (newValueStatus === 1) {
            document.getElementById(newValue[i].id + 'status').style.background = 'green'
          } else if (newValueStatus === 2) {
            document.getElementById(newValue[i].id + 'status').style.background = 'red'
          } else {
            document.getElementById(newValue[i].id + 'status').style.background = '#F0FFFF'
          }
        }
      }, (100))
    },
    getTable() {
      const param = []
      param[0] = ['工位号', this.$store.state.station.stationNumber]
      param[1] = ['产品型号代码', this.$store.state.station.engineValue.EngineTypeID]
      const Data = this.CreateData('11', '电子看板_工位机型_质量数据测量位置_图片_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          this.tighteningGuidePic = 'data:image/jpeg;base64,' + (response.data[0]['产品图片'].toString()).replace('"', '')
        }
      })
    },
    getShowTightButton() {
      this.showTightButton = false
      const param = []
      param[0] = ['工位号', this.$store.state.station.stationNumber]
      const Data = this.CreateData('11', 'MES界面显示_拧紧功能按钮_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          this.showTightButton = true
        }
      })
    },
    changBP(item) {
      if (item.nowStateCode === 1) {
        return 'tighten-green'// 绿色圆点
      } else if (item.nowStateCode === 2) {
        return 'tighten-blue'// 蓝色圆点
      } else if (item.nowStateCode === 0) {
        return 'tighten-red'// 红色圆点
      } else if (item.nowStateCode === 10) {
        return 'tighten-redRectangle' // 红色矩形
      } else if (item.nowStateCode === 11) {
        return 'tighten-greenRectangle'// 绿色矩形
      } else if (item.nowStateCode === 12) {
        return 'tighten-blueRectangle'// 蓝色矩形
      } else if (item.nowStateCode === 4) {
        return 'tighten-StartWorkCircle'// 黄色gif圆圈
      } else if (item.nowStateCode === 14) {
        return 'tighten-blinkRectangle'// 黄色gif矩形
      }
    },
    // 不合格放行
    unqualifiedRelease() {
      this.publication.topic = window.g.mqttPublishTopic
      this.publication.payload = 'WEB|NgGO|' + this.$store.state.station.stationNumber + '|1'
      const result = window.g.mqttClient.doPublish(this.publication)
      if (result === true) {
        this.$notify.success({
          title: '提示',
          message: '不合格放行成功！',
          position: 'bottom-right',
          duration: 2000,
          offset: 170
        })
        this.workAgainDialogVisible = false
      } else {
        this.$notify.error({
          title: '提示',
          message: '不合格放行失败！',
          position: 'bottom-right',
          duration: 2000,
          offset: 170
        })
      }
    },
    // 合格放行
    qualifiedRelease() {
      this.publication.topic = window.g.mqttPublishTopic
      this.publication.payload = 'WEB|OkGO|' + this.$store.state.station.stationNumber + '|1'
      const result = window.g.mqttClient.doPublish(this.publication)
      if (result === true) {
        this.$notify.success({
          title: '提示',
          message: '合格放行成功！',
          position: 'bottom-right',
          duration: 2000,
          offset: 170
        })
      } else {
        this.$notify.error({
          title: '提示',
          message: '合格放行失败！',
          position: 'bottom-right',
          duration: 2000,
          offset: 170
        })
      }
    },
    // 合格放行（从侧边弹窗调用）
    qualifiedReleaseByDrawer() {
      if (!stationIsWorking(this.$store.state)) {
        this.$message.error('工位未在工作!')
        return
      }
      this.publication.topic = window.g.mqttPublishTopic
      this.publication.payload = 'WEB|selectOkGo|' + this.$store.state.station.stationNumber + '|1'
      const result = window.g.mqttClient.doPublish(this.publication)
      if (result === true) {
        this.$notify.success({
          title: '提示',
          message: '合格放行成功！',
          position: 'bottom-right',
          duration: 2000,
          offset: 170
        })
      } else {
        this.$notify.error({
          title: '提示',
          message: '合格放行失败！',
          position: 'bottom-right',
          duration: 2000,
          offset: 170
        })
      }
    },
    // 不合格放行（从侧边弹窗调用）
    unqualifiedReleaseDrawer() {
      if (!stationIsWorking(this.$store.state)) {
        this.$message.error('工位未在工作!')
        return
      }
      this.publication.topic = window.g.mqttPublishTopic
      this.publication.payload = 'WEB|selectFalseGo|' + this.$store.state.station.stationNumber + '|1'
      const result = window.g.mqttClient.doPublish(this.publication)
      if (result === true) {
        this.$notify.success({
          title: '提示',
          message: '不合格放行成功！',
          position: 'bottom-right',
          duration: 2000,
          offset: 170
        })
      } else {
        this.$notify.error({
          title: '提示',
          message: '不合格放行失败！',
          position: 'bottom-right',
          duration: 2000,
          offset: 170
        })
      }
    },
    // region 新方法
    /**
     * 校准计时
     * @param EngineTypeID
     * @param EngineID
     * @constructor
     */
    CorrectiveTiming(EngineTypeID, EngineID) {
      var param = []
      param[0] = ['工位号', this.$store.state.station.stationNumber]
      param[1] = ['产品型号代码', EngineTypeID]
      param[2] = ['发动机号', EngineID]
      var Data = this.CreateData('11', '测量数据工位_监控系统_工位节拍_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          this.opBeatInfo.剩余时间 = response.data[0]['剩余时间']
          this.opBeatInfo.剩余时间1 = this.changeSecondToMinute(response.data[0]['剩余时间'], 0)
          this.opBeatInfo.标准时间 = response.data[0]['标准时间']
          this.opBeatInfo.标准时间1 = this.changeSecondToMinute(response.data[0]['标准时间'], 0)
          this.opBeatInfo.累计时间 = response.data[0]['累计时间']
          this.opBeatInfo.累计时间1 = this.changeSecondToMinute(response.data[0]['累计时间'], 0)
          this.judgeCycleTimer()
        }
      })
    },
    judgeCycleTimer() {
      const scope = this
      if (this.cycleTimer) clearInterval(this.cycleTimer)
      if (this.cycleTimerStop) return
      if (this.opBeatInfo.标准时间 === 0) return
      this.cycleTimer = setInterval(() => {
        if (scope.opBeatInfo.剩余时间 > 0) {
          scope.opBeatInfo.剩余时间 -= 1
          scope.opBeatInfo.累计时间 += 1
        } else {
          scope.opBeatInfo.剩余时间 = 0
          scope.opBeatInfo.累计时间 += 1
        }
        scope.opBeatInfo.剩余时间1 = scope.changeSecondToMinute(scope.opBeatInfo.剩余时间, 0)
        scope.opBeatInfo.累计时间1 = scope.changeSecondToMinute(scope.opBeatInfo.累计时间, 0)
        if (!stationIsWorking(this.$store.state)) {
          this.clearCycleTimer()
          this.clearCycleTimer_RepairOnLine()
        }
      }, 1000)
    },
    clearCycleTimer() {
      if (this.cycleTimer) clearInterval(this.cycleTimer)
      this.opBeatInfo.剩余时间 = 0
      this.opBeatInfo.累计时间 = 0
      this.opBeatInfo.标准时间 = 0
      this.opBeatInfo.剩余时间1 = this.changeSecondToMinute(this.opBeatInfo.剩余时间, 0)
      this.opBeatInfo.累计时间1 = this.changeSecondToMinute(this.opBeatInfo.累计时间, 0)
      this.opBeatInfo.标准时间1 = this.changeSecondToMinute(this.opBeatInfo.标准时间, 0)
    },
    stopCycleTimer() {
      if (this.cycleTimer) clearInterval(this.cycleTimer)
    },
    clearCycleTimer_RepairOnLine() {
      if (this.cycleTimer_RepairOnLine) clearInterval(this.cycleTimer_RepairOnLine)
      this.opRepairOnLineInfo.剩余时间 = 0
      this.opRepairOnLineInfo.累计时间 = 0
      this.opRepairOnLineInfo.标准时间 = 0
    },
    stopCycleTimer_RepairOnLine() {
      if (this.cycleTimer_RepairOnLine) clearInterval(this.cycleTimer_RepairOnLine)
    },
    changeSecondToMinute(totalSeconds, addSecond) {
      totalSeconds = totalSeconds + addSecond
      const minutes = Math.floor(totalSeconds / 60)
      const seconds = totalSeconds % 60
      if (minutes === 0 && seconds === 0) {
        return `0`
      }
      return `${minutes}:${seconds}`
    }
  }
}
</script>

<style scoped lang="scss">
.plc-status {
  margin-top: 5px;
  border-radius: 5px;
  background-color: #ffffff;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-evenly;
  align-content: center;
  padding-bottom: 2px;

  .content {
    float: left;
    width: 22px;
    height: 75px;
    margin: 2px 0 0 0;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    border-radius: 3px;

    .station {
      width: 14px;
      height: 14px;
      border-radius: 50%;
      border: 2px solid #d9e0e8;
    }

    .station-label {
      margin-top: 2px;
      font-size: 0.76rem;
      font-weight: 600;
      writing-mode: vertical-lr;
      color: #13227a;
      letter-spacing: 2px;
    }
  }
}

::v-deep.el-table .green {
  background: rgba(0, 128, 0, 0.7) !important;
}

::v-deep.el-table .red {
  background: rgba(255, 0, 0, 0.7) !important;
}

::v-deep.el-table--mini .el-table__cell {
  padding: 0;
}

::v-deep.el-table .cell {
  padding: 0;
}

::v-deep.datacs {
  border: 1px solid #d7dee6;
  height: 97%;
  width: 152px;
  margin-top: 2px;
  background-color: #d7dee6;
  margin-left: 3px;
  text-align: center;
  line-height: 30px;
  font-size: 22px;
}

::v-deep.el-table th.el-table__cell>.cell {
  font-size: 1rem;
  color: #0b4db0;
  padding: 0;
}

.functionButton {
  width: 100%;
  border-radius: 5px;
  margin: 5px 0 0 0;
  padding: 5px 0;
  user-select: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  background-color: #13227a;
  border: 1px solid #13227a;
  color: #fff;
  font-size: 1rem;

  img {
    margin: 0;
  }
}

.functionButton:hover {
  background-color: #2a3a9b;
  border: 1px solid #fff;
  color: #fff;
}

.bolt {
  z-index: 1;
  /* 下层 */
  width: 48px;
  height: 48px;
  background-size: 100% 100%;
  background-image: url("../../../assets/image/boltSignal.png");
  border-radius: 5px 5px 0 0;
}

.green_bolt {
  z-index: 2;
  /* 上层 */
  position: absolute;
  top: 20%;
  left: 20%;
  width: 30px;
  height: 30px;
  background-size: 100% 100%;
  background-image: url("../../../assets/image/green_bolt.gif")
}

.bolt-div {
  width: 48px;
  height: 20px;
  font-size: 0.8rem;
  text-align: center;
  font-weight: bolder;
  background-color: #ffffff;
  border: 1px solid #a5a5a5;
  line-height: 1.3;
  border-radius: 0 0 5px 5px;
}

.bolt-div-active {
  width: 48px;
  height: 20px;
  font-size: 0.8rem;
  text-align: center;
  font-weight: bolder;
  background-color: #13227a;
  color: #fff;
  border: 1px solid #a5a5a5;
  line-height: 1.3;
  border-radius: 0 0 5px 5px;
}

.tighten-blue {
  font-weight: bolder;
  color: #fff;
  text-align: center;
  position: absolute;
  width: 45px;
  height: 45px;
  background-image: url("../../../assets/image/bule.png");
  background-size: 100% 100%;
}

.tighten-blueRectangle {
  font-weight: bolder;
  color: #fff;
  text-align: center;
  position: absolute;
  width: 45px;
  height: 45px;
  background-image: url("../../../assets/image/bluerectangle.png");
  background-size: 100% 100%;
}

.tighten-red {
  font-weight: bolder;
  color: #fff;
  text-align: center;
  position: absolute;
  width: 45px;
  height: 45px;
  background-image: url("../../../assets/image/red.png");
  background-size: 100% 100%;
}

.tighten-redRectangle {
  font-weight: bolder;
  color: #fff;
  text-align: center;
  position: absolute;
  width: 45px;
  height: 45px;
  background-image: url("../../../assets/image/redrectangle.png");
  background-size: 100% 100%;
}

.tighten-green {
  font-weight: bolder;
  color: #fff;
  text-align: center;
  position: absolute;
  width: 45px;
  height: 45px;
  background-image: url("../../../assets/image/green.png");
  background-size: 100% 100%;
}

.tighten-greenRectangle {
  font-weight: bolder;
  color: #fff;
  text-align: center;
  position: absolute;
  width: 45px;
  height: 45px;
  background-image: url("../../../assets/image/greenrectangle.png");
  background-size: 100% 100%;
}

.tighten-StartWorkCircle {
  font-weight: bolder;
  color: #000000;
  text-align: center;
  position: absolute;
  width: 45px;
  height: 45px;
  background-size: 100% 100%;
  background-image: url("../../../assets/image/StartWorkCircle.gif");
}

.tighten-blinkRectangle {
  font-weight: bolder;
  color: #fff;
  text-align: center;
  position: absolute;
  width: 45px;
  height: 45px;
  background-image: url("../../../assets/image/blinkrectangle.gif");
  background-size: 100% 100%;
  background-color: #81e2ff;
}

.releaseButton {
  width: 100px;
  padding: 10px;
  border-radius: 10px;
  text-align: center;
  justify-content: center;
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #fff;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.releaseButton:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

/* 焊接点状态样式 */
.weld-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-column-gap: 12px;
  grid-row-gap: 12px;
}

.weld-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  user-select: none;
}

.weld-dot {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background: #F56C6C;
  border: 2px solid #d9e0e8;
}

.weld-dot.ok {
  background: #67C23A;
}

.weld-label {
  margin-top: 6px;
  font-size: 12px;
  color: #333;
}

.weld-page-controls {
  margin-top: 15px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid #e9ecef;
}

.weld-page-btn {
  height: 48px;
  padding: 0 20px;
  font-size: 16px;
  font-weight: bold;
  min-width: 100px;
}

.weld-page-info {
  font-size: 15px;
  font-weight: 500;
  color: #495057;
  text-align: center;
  flex: 1;
  margin: 0 15px;
}
</style>
