<template>
    <div class="first-station">
      <el-row :gutter="0">
        <div style="color: white;height: 90px;text-align: center">
          <el-col :span="8">
            <div style="font-size: 1.5rem;padding-top: 25px">
            </div>
          </el-col>
          <el-col :span="8">
            <div style="text-align: center;font-size: 2.5rem;color: white;padding-top: 15px">
              {{station + stationName}}
            </div>
          </el-col>
          <el-col :span="8">
            <div style="font-size: 1.5rem;padding-top: 25px">
            </div>
          </el-col>
        </div>
      </el-row>
      <el-row :gutter="0">
        <div class="data-box1" style="left:35px; top:0;height: 910px;width: 1505px;">
          <span class="borderLeft1 boxBorder"></span>
          <span class="borderLeft2 boxBorder"></span>
          <span class="borderRight1 boxBorder"></span>
          <span class="borderRight2 boxBorder"></span>
<!--          <iframe :src=DTSRC style="width: 1500px;height: 905px;border: none"/>-->
          <div>1</div>
          <div style="position: absolute;left: 10px;top:10px">
            <el-tag color="#e6a23c" class="andonCallList" v-for="(item, index) in AndonCallList" :key="index">
              <div>{{ item.AndonName + '呼叫'}}</div>
              <div style="font-size: 16px">{{item.TriggerTime}}</div>
            </el-tag>
          </div>
        </div>
        <div class="data-box1" style="right:35px; top:0;height: 160px;width: 330px;">
          <span class="borderLeft1 boxBorder"></span>
          <span class="borderLeft2 boxBorder"></span>
          <span class="borderRight1 boxBorder"></span>
          <span class="borderRight2 boxBorder"></span>
          <el-col :span="12" style="padding-top: 15px">
            <div id="myChart6395AArrr1" style="width: 100%;height: 140px"/>
          </el-col>
          <el-col :span="12" style="padding-top: 15px"  >
            <div id="myChart6395dadadsAArrr1" style="width: 100%;height: 140px"/>
          </el-col>
        </div>
        <div class="data-box1" style="right:35px; top:180px;height: 240px;width: 330px;">
          <span class="borderLeft1 boxBorder"></span>
          <span class="borderLeft2 boxBorder"></span>
          <span class="borderRight1 boxBorder"></span>
          <span class="borderRight2 boxBorder"></span>
          <el-row style="text-align: center;font-size: 20px;">
            机床模式
          </el-row>
          <el-row>
            <el-col :span="12">
              <div style="margin-top: 15px;margin-left: 20px">
                <div class="leftTips">自动</div>
                <div>
                  <img v-if="lightStatus.auto === 1" src="../../assets/green.png"  class="lamp">
                  <img v-else=""  src="../../assets/gray.png" class="lamp" >
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div style="margin-top: 15px;">
                <div class="rightTips">手动</div>
                <div style="margin-left: 20px">
                  <img  v-if="lightStatus.manual === 1"  src="../../assets/purple.png" class="lamp">
                  <img v-else src="../../assets/gray.png" class="lamp">
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div style="margin-top: 13px;margin-left: 20px">
                <div class="leftTips">急停</div>
                <div>
                  <img v-if="lightStatus.emergency === 1"  src="../../assets/red.png" class="lamp">
                  <img v-else src="../../assets/gray.png" class="lamp">
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div style="margin-top: 13px">
                <div  class="rightTips">停机</div>
                <div style="margin-left: 20px">
                  <img v-if="lightStatus.shutdown === 1" src="../../assets/gray.png" class="lamp">
                  <img v-else src="../../assets/gray.png" class="lamp">
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-divider style="margin: 0"></el-divider>
          </el-row>
          <el-row style="text-align: center;font-size: 20px">
            机床状态
          </el-row>
          <el-row>
            <el-col :span="12">
              <div style="margin-top: 13px;margin-left: 20px">
                <div  class="rightTips">待机</div>
                <div>
                  <img v-if="lightStatus.ready === 1" src="../../assets/yellow.png" class="lamp">
                  <img v-else src="../../assets/gray.png" class="lamp">
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div style="margin-top: 13px">
                <div class="leftTips">加工</div>
                <div style="margin-left: 20px">
                  <img v-if="lightStatus.work === 1" src="../../assets/green.png" class="lamp">
                  <img v-else  src="../../assets/gray.png" class="lamp">
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div style="margin-top: 13px;margin-left: 20px">
                <div class="leftTips">离线</div>
                <div>
                  <img v-if="lightStatus.off === 1" src="../../assets/gray.png" class="lamp">
                  <img v-else src="../../assets/gray.png" class="lamp">
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div style="margin-top: 13px">
                <div class="rightTips">报警</div>
                <div style="margin-left: 20px">
                  <img v-if="lightStatus.alarm === 1" src="../../assets/red.png" class="lamp">
                  <img v-else src="../../assets/gray.png" class="lamp">
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="data-box1" style="right:35px; top:440px;height: 285px;width: 330px;">
          <span class="borderLeft1 boxBorder"></span>
          <span class="borderLeft2 boxBorder"></span>
          <span class="borderRight1 boxBorder"></span>
          <span class="borderRight2 boxBorder"></span>
          <table  border="1" cellspacing="0" style="border-color: #717171;margin: 2px 0 0 2px;color: white">
            <tr style="font-size: 18px;color: white;width: 80px;;height: 35px">
              <th style="width: 53px"></th>
              <th style="width: 85px">X</th>
              <th style="width: 85px">Y</th>
              <th style="width: 85px">Z</th>
            </tr>
            <tr style="color: white;text-align: center;font-size: 18px;height: 40px">
              <td style="font-size: 16px">相对(mm)</td>
              <td>{{machineInfo_position.relative[0]}}</td>
              <td>{{machineInfo_position.relative[1]}}</td>
              <td>{{machineInfo_position.relative[2]}}</td>
            </tr>
            <tr style="color: white;text-align: center;font-size: 18px;height: 40px">
              <td style="font-size: 16px">绝对(mm)</td>
              <td>{{machineInfo_position.absolute[0]}}</td>
              <td>{{machineInfo_position.absolute[1]}}</td>
              <td>{{machineInfo_position.absolute[2]}}</td>
            </tr>
            <tr style="color: white;text-align: center;font-size: 18px;height: 40px">
              <td style="font-size: 16px">机械(mm)</td>
              <td>{{machineInfo_position.machine[0]}}</td>
              <td>{{machineInfo_position.machine[1]}}</td>
              <td>{{machineInfo_position.machine[2]}}</td>
            </tr>
            <tr style="color: white;text-align: center;font-size: 18px;height: 40px">
              <td style="font-size: 16px">剩余(mm)</td>
              <td>{{machineInfo_position.distance[0]}}</td>
              <td>{{machineInfo_position.distance[1]}}</td>
              <td>{{machineInfo_position.distance[2]}}</td>
            </tr>
            <tr style="color: white;text-align: center;font-size: 18px;height: 40px">
              <td style="font-size: 16px">转速(r/s)</td>
              <td>{{machineInfo_position.spindleSpeedAxis[0]}}</td>
              <td>{{machineInfo_position.spindleSpeedAxis[1]}}</td>
              <td>{{machineInfo_position.spindleSpeedAxis[2]}}</td>
            </tr>
            <tr style="color: white;text-align: center;font-size: 18px;height: 40px">
              <td style="font-size: 16px">进给(mm/min)</td>
              <td>{{machineInfo_position.feedRateAxis[0]}}</td>
              <td>{{machineInfo_position.feedRateAxis[1]}}</td>
              <td>{{machineInfo_position.feedRateAxis[2]}}</td>
            </tr>
          </table>
        </div>
        <div class="data-box1" style="right:35px; top:740px;height: 170px;width: 330px;">
          <span class="borderLeft1 boxBorder"></span>
          <span class="borderLeft2 boxBorder"></span>
          <span class="borderRight1 boxBorder"></span>
          <span class="borderRight2 boxBorder"></span>
          <div style="margin: 2px 0 0 2px">
            <el-row>
              <el-col :span="9">
                <div class="orderNumberStyle">伺服负载</div>
              </el-col>
              <el-col :span="5">
                <div class="orderNumberStyle">{{ machineInfo_work.servoLoad[0] }}%</div>
              </el-col>
              <el-col :span="5">
                <div class="orderNumberStyle">{{ machineInfo_work.servoLoad[1] }}%</div>
              </el-col>
              <el-col :span="5">
                <div class="orderNumberStyle" style="margin-right: 1px;">{{ machineInfo_work.servoLoad[2] }}%</div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="9">
                <div class="orderNumberStyle">切削时间</div>
              </el-col>
              <el-col :span="15">
                <div class="orderNumberStyle" style="margin-right: 1px;">{{ machineInfo_time.cuttingTime }}</div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="9">
                <div class="orderNumberStyle">运行时间</div>
              </el-col>
              <el-col :span="15">
                <div class="orderNumberStyle" style="margin-right: 1px;">{{ machineInfo_time.workTime }}</div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="9">
                <div class="orderNumberStyle">循环时间</div>
              </el-col>
              <el-col :span="15">
                <div class="orderNumberStyle" style="margin-right: 1px;">{{ machineInfo_time.cyclingTime }}</div>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="data-box1" style="left:35px; top:920px;height: 50px;width: 1850px;">
          <span class="borderLeft1 boxBorder"></span>
          <span class="borderLeft2 boxBorder"></span>
          <span class="borderRight1 boxBorder"></span>
          <span class="borderRight2 boxBorder"></span>
          <div style="margin-top: 2px">
            <el-col :span="20">
              <div style="">
                <el-button type="primary" style="width: 150px;font-size: 18px" icon="el-icon-monitor" plain @click="showPage(1)">设备管理</el-button>
                <el-button type="primary" style="width: 150px;font-size: 18px" icon="el-icon-tickets" plain @click="showPage(2)">计划管理</el-button>
                <el-button type="primary" style="width: 150px;font-size: 18px" icon="el-icon-news" plain @click="showPage(3)">产品管理</el-button>
                <el-button type="primary" style="width: 150px;font-size: 18px" icon="el-icon-s-data" plain @click="showPage(4)">质量管理</el-button>
                <el-button type="primary" style="width: 150px;font-size: 18px" icon="el-icon-collection-tag" plain @click="showPage(5)">刀具管理</el-button>
                <el-button type="primary" style="width: 150px;font-size: 18px" icon="el-icon-pie-chart" plain @click="showPage(6)">Andon管理</el-button>
                <el-button type="primary" style="width: 150px;font-size: 18px" icon="el-icon-document-copy" plain @click="showPage(7)">工艺管理</el-button>
                <el-button type="primary" style="width: 150px;font-size: 18px" icon="el-icon-document-copy" plain @click="showPage(8)">能源管理</el-button>
                <el-button type="primary" style="width: 150px;font-size: 18px" icon="el-icon-edit" plain @click="showPage(9)">参数设定</el-button>
              </div>
            </el-col>
            <el-col :span="4">
              <el-button type="warning" style="width: 150px;font-size: 18px;float: right;margin-right: 20px" @click="closePage">退出系统</el-button>
            </el-col>
          </div>
        </div>
      </el-row>
      <div v-if="flag">
        <el-dialog :title="title" :visible.sync="dialogVisible" center width="1566px" top="5vh" :modal-append-to-body="false" append-to-body @close="flag=!flag">
          <deviceManagementPage v-if="pageType === 1" :opname="station" v-on:setBasicParamSuccess = "setBasicParamSuccess"/>
          <planeManagementPage v-else-if="pageType === 2" :opname="station"/>
          <orderManagementPage1 v-else-if="pageType === 3" :opname="station"/>
          <qualityAssurancePage1 v-else-if="pageType === 4" :opname="station"/>
          <toolManagementPage1 v-else-if="pageType === 5" :opname="station"/>
          <andonCallPage1 v-else-if="pageType === 6" :opname="station"/>
          <processManagementPage v-else-if="pageType === 7" :opname="station"/>
          <energyManagementPage v-else-if="pageType === 8" :opname="station"/>
        </el-dialog>
      </div>
    </div>
</template>
<script>
import { wsuri, opname, opnameBs, mqttIp, mqttPort } from '@/utils/request'
import mqtt from 'mqtt'
import { formatTime } from '@/utils/tool'
import orderManagementPage1 from '@/views/page/orderManagementPage1'
import qualityAssurancePage1 from '@/views/page/qualityAssurancePage1'
import toolManagementPage1 from '@/views/page/toolManagementPage1'
import planeManagementPage from '@/views/page/planeManagementPage'
import andonCallPage1 from '@/views/page/andonCallPage1'
import deviceManagementPage from '@/views/page/deviceManagementPage'
import processManagementPage from '@/views/page/processManagementPage'
import energyManagementPage from '@/views/page/energyManagementPage'
export default {
  components: {
    'orderManagementPage1': orderManagementPage1,
    'qualityAssurancePage1': qualityAssurancePage1,
    'toolManagementPage1': toolManagementPage1,
    'planeManagementPage': planeManagementPage,
    'andonCallPage1': andonCallPage1,
    'deviceManagementPage': deviceManagementPage,
    'processManagementPage': processManagementPage,
    'energyManagementPage': energyManagementPage
  },
  data() {
    return {
      IsAllowConnect: true,
      mqttClient: null,
      flag: false,
      currentBeat: 0,
      planBeat: 0,
      AndonCallList: [],
      FeedRate: 100,
      SpindleSpeed: 100,
      pageType: 0,
      dialogVisible: false,
      websock: null,
      DTSRC: '',
      test1: '',
      programeNumber: 'LG00125A', // 配方 名称
      ProductNumber: 'LG00125B', // 产品编号
      productTypeNumber: 'LG00125C', // 产品型号代码
      operator: '员工1',
      shift: '班次一',
      dailyOutput: '1000',
      stationName: '', // 工位名称
      scanner: '', // 扫描枪
      ProductType: '', // 产品型号
      lightStatus: {
        auto: 0, // 自动模式
        manual: 0, // 手动模式
        emergency: 0, // 急停模式
        shutdown: 0, // 停机模式
        work: 0, // 加工状态
        ready: 0, // 待机状态
        off: 1, // 关机状态
        alarm: 0 // 报警状态
      },
      communicationStatus: '',
      activeName: 'first1',
      title: '',
      loading: false,
      tableData: [],
      tableData1: [],
      ID: '',
      station: '',
      stationOutput: '',
      stationNumberID: '',
      partID: '',
      titleEdit: '',
      date: new Date(),
      month: '',
      day: '',
      minute: '',
      hour: '',
      year: '',
      second: '',
      week: '',
      machineInfo_position: {
        relative: [0, 0, 0],
        absolute: [0, 0, 0],
        machine: [0, 0, 0],
        distance: [0, 0, 0],
        feedRateAxis: [0, 0, 0],
        spindleSpeedAxis: [0, 0, 0]
      },
      machineInfo_tool: {
        toolNum: 0,
        toolLife: 1,
        surplus: 100,
        toolCount: 0,
        thresholdValue1: 0,
        thresholdValue2: 0,
        residue: 0
      },
      machineInfo_time: {
        startTime: '0 H 0 M 0 S',
        cuttingTime: '0 H 0 M 0 S',
        workTime: '0 H 0 M 0 S',
        cyclingTime: '0 H 0 M 0 S'
      },
      machineInfo_work: {
        partCount: '0',
        spindleSpeed: '0',
        feedRate: '0',
        currentToolNum: '0',
        servoLoad: [0, 0, 0],
        programNumber: '[0]  [0]'
      },
      processColor: '#16c1a0',
      timer: null,
      timerInit: null,
      notifyPromise: Promise.resolve()
    }
  },
  // 通过路由把index3中 点击的工位号 和 是否存在订单 值传进本页
  watch: {
    '$route': {
      handler(route) {
        this.station = this.$route.query.OP
        this.stationId = this.$route.query.工位号id
        this.DTSRC = 'http://127.0.0.1:8082/#/?' + this.station
        // this.DTSRC = 'http://192.168.63.15:8956/#/?' + this.station
      },
      immediate: true
    }
  },
  computed: {},
  mounted() {
    this.searchTableOpName()
    this.searchTablePartId()
    this.initWebsocket()
    // this.initMqtt()
    this.drawLine501()
    this.searchMachineStatus()
    this.searchMachineStatus_WorkMode()
    const _this = this // 声明一个变量指向Vue实例this，保证作用域一致
    this.timer = setInterval(() => {
      _this.date = new Date() // 修改数据date
      this.year = new Date().getFullYear() + 1 < 10 ? '0' + (new Date().getFullYear() + 1) : new Date().getFullYear()
      this.month = new Date().getMonth() + 1 < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1
      this.day = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate()
      this.hour = new Date().getHours() < 10 ? '0' + new Date().getHours() : new Date().getHours()
      this.minute = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
      this.second = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
      this.week = '日一二三四五六'.charAt(new Date().getDay())
    }, 1000)
    this.timer = setInterval(() => {
      this.init()
    }, 5000)
  },
  created() {
    this.searchTableAndon()
    this.searchBasicParams()
  },
  beforeDestroy() {
    this.websock.onclose(wsuri)
    clearInterval(this.timer)
    clearInterval(this.timerInit)
    this.mqttClient.end()
  },
  methods: {
    init() {
      this.searchTableAndon()
      this.searchTablePartId()
      this.searchCurrentTool()
      this.searchBasicParams()
      this.searchMachineStatus()
      this.searchMachineStatus_WorkMode()
      // this.solveAlarm(this.station, '设备光栅闯入！', '2022-06-12 23:23:56')
    },
    format(percentage) {
      return `剩余${percentage}%`
    },
    initWebsocket() { // 初始化websocket
      this.websock = new WebSocket(wsuri)// 这里面的this都指向vue
      this.websock.onopen = this.websocketopen
      this.websock.onmessage = this.websocketonmessage
      this.websock.onclose = this.websocketclose
      this.websock.onerror = this.websocketerror
    },
    websocketopen() { // 打开
      this.$message.success('连接成功!')
      this.websock.send('{<' + opname + '>}')
      setTimeout(() => {
        this.websockeSendMessage('B_C_DT_WebLoaded', this.station)
      }, 2000)
    },
    websocketonmessage(msg) { // 数据接收
      this.msg = msg
      try {
        // 返回的数据msg.data，包含了协议中的4部分9
        // TOBS??SCADADetailed?MES|Current|opName|电流^电压
        var arrays_signal = msg.data.split('|')
        var interFaceType = arrays_signal[0]
        var m_Opname = arrays_signal[1]
        var dataType = arrays_signal[2]
        var m_data = arrays_signal[3]
        if (m_Opname.includes('OP130-1'))m_Opname = 'OP130'
        if (this.station === m_Opname) {
          switch (interFaceType) {
            case 'MES':
              switch (dataType) {
                case 'C_B_MoveInfo':
                  {
                    const J_data = JSON.parse(m_data)
                    this.machineInfo_position.absolute = J_data.absolute
                    this.machineInfo_position.distance = J_data.distance
                    this.machineInfo_position.machine = J_data.machine
                    this.machineInfo_position.Relative = J_data.relative
                    this.machineInfo_position.spindleSpeedAxis = J_data.spindleSpeedAxis
                    this.machineInfo_position.feedRateAxis = J_data.feedRateAxis
                  }
                  break
                case 'C_B_TimeInfo':
                  {
                    const T_data = JSON.parse(m_data)
                    this.machineInfo_time.workTime = formatTime(T_data.workTime)
                    this.machineInfo_time.cyclingTime = formatTime(T_data.cyclingTime)
                    this.machineInfo_time.cuttingTime = formatTime(T_data.cuttingTime)
                    this.machineInfo_time.startTime = formatTime(T_data.startTime)
                  }
                  break
                case 'C_B_WorkInfo':
                  {
                    const W_data = JSON.parse(m_data)
                    this.machineInfo_work.servoLoad = W_data.servoLoad
                    this.machineInfo_work.spindleSpeed = W_data.spindleSpeed
                    this.machineInfo_work.feedRate = W_data.feedRate
                    this.machineInfo_work.partCount = W_data.partCount
                    this.machineInfo_work.programNumber = W_data.programNumber
                    if (parseInt(this.machineInfo_work.currentToolNum) !== parseInt(W_data.currentToolNum)) {
                      this.machineInfo_work.currentToolNum = W_data.currentToolNum
                      this.searchCurrentTool(W_data.currentToolNum)
                    }
                    this.drawLine501()
                  }
                  break
                // case 'C_B_StatusInfo':
                //   {
                //     const S_data = JSON.parse(m_data)
                //     if (S_data.off !== 1) {
                //       this.lightStatus.alarm = parseInt(S_data.Alarm)
                //       this.lightStatus.ready = 1
                //       this.lightStatus.work = parseInt(S_data.RunStatus) === 1 ? 1 : 0
                //       this.lightStatus.off = parseInt(S_data.off)
                //
                //       this.lightStatus.shutdown = parseInt(S_data.WorkMode) === 4 ? 1 : 0
                //       this.lightStatus.emergency = parseInt(S_data.Emergency)
                //       this.lightStatus.auto = parseInt(S_data.WorkMode) === 1 ? 1 : 0
                //       this.lightStatus.debug = parseInt(S_data.Edit)
                //     } else {
                //       this.lightStatus.alarm = 0
                //       this.lightStatus.ready = 0
                //       this.lightStatus.work = 0
                //       this.lightStatus.off = 1
                //
                //       this.lightStatus.shutdown = 0
                //       this.lightStatus.emergency = 0
                //       this.lightStatus.auto = 0
                //       this.lightStatus.debug = 0
                //     }
                //   }
                //   break
              }
              break
          }
        }
      } catch (exception) {
        var error = exception.toString()
        console.log(error)
      }
    },
    websocketclose() { // 关闭
      this.$message.error('WebSocket断开连接!重新连接')
      setTimeout(() => {
        this.initWebsocket()
      }, 2000)
    },
    websocketerror() { // 失败
      console.log('WebSocket连接失败')
    },
    websockeSendMessage(dataType, data) {
      this.websock.send(opnameBs + dataType + '|' + data)
    },
    searchTableOpName() {
      var param = []
      param[0] = ['stationNumber', this.stationId]
      var Data1 = this.CreateData('11', 'AAA临工看板_工位信息_查询数据', param)
      this.ExecDatabase(Data1).then(response => {
        this.stationName = response.data[0].工位名称
        this.station = response.data[0].工位号
      })
    },
    initMqtt() {
      const scope = this
      const connection = {
        host: mqttIp,
        port: mqttPort,
        endpoint: '/mqtt',
        clean: true, // 保留会话
        connectTimeout: 4000, // 超时时间
        reconnectPeriod: 4000, // 重连时间间隔
        // 认证信息
        clientId: 'mqttjs_3be2c321' + new Date().getTime(), // 同一个ID 无法二次连接
        username: '',
        password: ''
      }
      const subscription = {
        topic: opname,
        qos: 0
      }
      const { host, port, endpoint, ...options } = connection
      const connectUrl = `ws://${host}:${port}${endpoint}`
      try {
        this.mqttClient = mqtt.connect(connectUrl, options)
      } catch (error) {
        console.log('MQTT connect error', error)
      }

      this.mqttClient.on('connect', () => {
        this.$message.success('加载完成，连接MQTT服务器成功！')
        console.log('MQTT Connection succeeded!')
        const { topic, qos } = subscription
        this.mqttClient.subscribe(topic, { qos }, (error, res) => {
          if (error) {
            console.log('Subscribe to topics error', error)
          }
        })
      })
      this.mqttClient.on('error', error => {
        console.log('MQTT Connection failed', error)
        try {
          scope.$message.error('MQTT服务器连接失败')
          if (scope.IsAllowConnect) {
            // 显示一下
            scope.$message.warning('重新连接MQTT服务器')
            console.log('重新连接MQTT服务器')
            // 重新连接,打开计时器
            setTimeout(function() {
              scope.initMqtt()
            }, 5000)
          }
        } catch (exception) {
          const error = exception.toString()
          scope.$message.error('MQTT服务器出现错误,关闭连接' + error)
        }
      })
      // 接收消息
      this.mqttClient.on('message', (topic, message) => {
        try {
          scope.websocketonmessage({ data: message.toString() })
        } catch (exception) {
          console.log(exception.toString())
        }
      })
    },
    // 查询机床状态
    searchMachineStatus() {
      var param = []
      param[0] = ['opName', this.station]
      var Data = this.CreateData('11', 'LG_临工看板_设备管理_查询当前状态', param)
      this.ExecDatabase(Data).then(res => {
        if (res.data.length > 0) {
          const datum = res.data[0]
          if (datum.StatusCode === 5) {
            this.lightStatus.alarm = 0
            this.lightStatus.ready = 0
            this.lightStatus.work = 0
            this.lightStatus.off = 1
          } else {
            this.lightStatus.alarm = 0
            this.lightStatus.ready = 1
            this.lightStatus.work = 0
            this.lightStatus.off = 0
            if (datum.StatusCode === 1) {
              this.lightStatus.alarm = 0
              this.lightStatus.work = 1
            } else if (datum.StatusCode === 2) {
              this.lightStatus.alarm = 1
              this.lightStatus.work = 0
            }
          }
        }
      })
    },
    // 查询机床工作模式
    searchMachineStatus_WorkMode() {
      var param = []
      param[0] = ['opName', this.station]
      var Data = this.CreateData('11', 'LG_临工看板_设备管理_查询当前状态_工作模式', param)
      this.ExecDatabase(Data).then(res => {
        if (res.data.length > 0) {
          const datum = res.data[0]
          this.lightStatus.shutdown = datum.shutdown
          this.lightStatus.emergency = datum.emergency
          this.lightStatus.auto = datum.auto
          this.lightStatus.manual = datum.manual
        } else {
          this.lightStatus.shutdown = 0
          this.lightStatus.emergency = 0
          this.lightStatus.auto = 0
          this.lightStatus.manual = 0
        }
      })
    },
    searchTablePartId() {
      var param = []
      param[0] = ['stationNumber', this.stationId]
      var Data1 = this.CreateData('3', 'select top 1 * from [dbo].[LG_工位扫描信息视图] where opName = ' + `'OP70'` + 'AND [type] = 1 order by scanTime desc', param)
      this.ExecDatabase(Data1).then(response => {
        this.ProductNumber = response.data[0].partId
      })
    },
    searchCurrentTool(toolNum) {
      var param = []
      param[0] = ['所在工位号', this.station]
      param[1] = ['刀具号', toolNum]
      var Data1 = this.CreateData('11', 'LG_临工看板_刀具管理_当前刀具信息查询', param)
      this.ExecDatabase(Data1).then(response => {
        if (response.data.length > 0) {
          this.machineInfo_tool.thresholdValue1 = response.data[0].预警值1
          this.machineInfo_tool.thresholdValue2 = response.data[0].预警值2
          this.machineInfo_tool.toolLife = response.data[0].刀具额定寿命
          this.machineInfo_tool.toolNum = response.data[0].刀具代码
          this.machineInfo_tool.toolCount = response.data[0].已用寿命
          this.machineInfo_tool.surplus = Math.floor((1 - this.machineInfo_tool.toolCount / this.machineInfo_tool.toolLife) * 100 * 100) / 100
        }
      })
    },
    toolInfoColor() {
      const info = this.machineInfo_tool
      const toolLife = info.toolLife
      if (parseInt(toolLife) === 0) {
        this.processColor = '#16c1a0'
      } else {
        const toolCount = info.toolCount
        const thresholdValue1 = info.thresholdValue1
        const thresholdValue2 = info.thresholdValue2
        const used = toolCount / toolLife * 100
        console.log(used)
        if (used <= thresholdValue1) {
          this.processColor = '#16c1a0'
        }
        if (used > thresholdValue1 && used <= thresholdValue2) {
          this.processColor = '#efa52e'
        }
        if (used > thresholdValue2) {
          this.processColor = '#a30015'
        }
      }
    },
    showPage(type) {
      this.title = ''
      this.flag = true
      this.dialogVisible = true
      this.pageType = type
      switch (type) {
        case 1:
          this.title = '设备管理'
          break
        case 2:
          this.title = '计划管理'
          break
        case 3:
          this.title = '产品管理'
          break
        case 4:
          this.title = '质量管理'
          break
        case 5:
          this.title = '刀具管理'
          break
        case 6:
          this.title = 'Andon管理'
          break
        case 7:
          this.title = '工艺管理'
          break
        case 8:
          this.title = '能源管理'
          break
        case 9:
          this.title = '基础参数管理'
          break
        default:
          break
      }
    },
    // OEE图形
    drawLine501() {
      const myChart6395AArrr1 = this.$echarts.init(document.getElementById('myChart6395AArrr1'))
      myChart6395AArrr1.setOption(
        {
          tooltip: {
            formatter: '{a} <br/>{c} {b}'
          },
          series: [
            {
              name: '进给倍率',
              type: 'gauge',
              min: 0,
              max: 150,
              startAngle: 200,
              endAngle: -20,
              splitNumber: 6,
              radius: '100%',
              axisLine: { // 坐标轴线
                lineStyle: { // 属性lineStyle控制线条样式
                  color: [[0.20, '#ff4500'], [0.80, '#27d500'], [1, '#ff4500']],
                  width: 3
                }
              },
              axisLabel: { // 坐标轴小标记
                textStyle: { // 属性lineStyle控制线条样式
                  fontWeight: 'bolder',
                  color: '#fff',
                  shadowColor: '#fff', // 默认透明
                  shadowBlur: 1
                }
              },
              axisTick: { // 坐标轴小标记
                length: 5, // 属性length控制线长
                lineStyle: { // 属性lineStyle控制线条样式
                  color: 'auto',
                  shadowColor: '#fff', // 默认透���
                  shadowBlur: 1
                }
              },
              splitLine: { // 分隔线
                length: 10, // 属性length控制线长
                lineStyle: { // 属性lineStyle（详见lineStyle）控制线条样式
                  width: 1,
                  color: '#fff',
                  shadowColor: '#fff', // 默认透明
                  shadowBlur: 1
                }
              },
              title: {
                textStyle: { // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                  fontWeight: 'bolder',
                  fontSize: 14,
                  color: '#fff',
                  shadowColor: '#fff', // 默认透明
                  shadowBlur: 5
                },
                offsetCenter: [0, '40%']
              },
              detail: {
                formatter: this.machineInfo_work.feedRate + '%',
                shadowBlur: 3,
                offsetCenter: [0, '70%'], // x, y，单位px
                textStyle: { // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                  fontWeight: 'bolder',
                  color: '#fff',
                  fontSize: 16
                }
              },
              data: [{ name: '进给倍率', value: this.machineInfo_work.feedRate }]
            }
          ]
        }
      )
      const myChart6395dadadsAArrr1 = this.$echarts.init(document.getElementById('myChart6395dadadsAArrr1'))
      myChart6395dadadsAArrr1.setOption(
        {
          tooltip: {
            formatter: '{a} <br/>{c} {b}%'
          },
          series: [
            {
              name: '主轴倍率',
              type: 'gauge',
              min: 0,
              max: 150,
              startAngle: 200,
              endAngle: -20,
              splitNumber: 6,
              radius: '100%',
              axisLine: { // 坐标轴线
                lineStyle: { // 属性lineStyle控制线条样式
                  color: [[0.20, '#ff4500'], [0.80, '#27d500'], [1, '#ff4500']],
                  width: 3
                }
              },
              axisLabel: { // 坐标轴小标记
                textStyle: { // 属性lineStyle控制线条样式
                  fontWeight: 'bolder',
                  color: '#fff',
                  shadowColor: '#fff', // 默认透明
                  shadowBlur: 1
                }
              },
              axisTick: { // 坐标轴小标记
                length: 5, // 属性length控制线长
                lineStyle: { // 属性lineStyle控制线条样式
                  color: 'auto',
                  shadowColor: '#fff', // 默认透���
                  shadowBlur: 1
                }
              },
              splitLine: { // 分隔线
                length: 10, // 属性length控制线长
                lineStyle: { // 属性lineStyle（详见lineStyle）控制线条样式
                  width: 1,
                  color: '#fff',
                  shadowColor: '#fff', // 默认透明
                  shadowBlur: 1
                }
              },
              title: {
                textStyle: { // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                  fontWeight: 'bolder',
                  fontSize: 14,
                  color: '#fff',
                  shadowColor: '#fff', // 默认透明
                  shadowBlur: 5
                },
                offsetCenter: [0, '40%']
              },
              detail: {
                formatter: this.machineInfo_work.spindleSpeed + '%',
                shadowBlur: 3,
                offsetCenter: [0, '70%'], // x, y，单位px
                textStyle: { // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                  fontWeight: 'bolder',
                  color: '#fff',
                  fontSize: 16
                }
              },
              data: [{ name: '主轴倍率', value: this.machineInfo_work.spindleSpeed }]
            }
          ]
        }
      )
    },
    // 获取Andon实时表
    searchTableAndon() {
      var param = []
      param[0] = ['opname', this.station]
      var Data = this.CreateData('11', 'LG_临工看板_Andon管理_当前Andon', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          for (const info of response.data) {
            this.solveAndonList(this.station, info.AndonName + '呼叫', info.TriggerTime)
          }
        }
      })
    },
    // 接收andon
    solveAndonList(opName, AndonName, TriggerTime) {
      const _this = this
      this.notifyPromise = this.notifyPromise.then(this.$nextTick).then(function() {
        _this.$notify({
          title: opName + '-' + AndonName,
          dangerouslyUseHTMLString: true,
          type: 'warning',
          duration: 3000,
          position: 'bottom-right',
          message: `
<div>
  <span style="font-size: 16px">内容：</span>
  <span style="font-size: 16px">${AndonName}</span>
</div>
<div>
  <span style="font-size: 16px">时间：</span>
  <span style="font-size: 16px">${TriggerTime}</span>
</div>
`
        })
      })
    },
    // 接收报警 展示
    solveAlarm(opName, content, time) {
      this.$notify({
        title: opName + '-设备报警',
        dangerouslyUseHTMLString: true,
        type: 'danger',
        duration: 3000,
        position: 'bottom-right',
        message: `
<div>
  <span style="font-size: 16px">内容：</span>
  <span style="font-size: 16px">${content}</span>
</div>
<div>
  <span style="font-size: 16px">时间：</span>
  <span style="font-size: 16px">${time}</span>
</div>
`
      })
    },
    // 查询基础参数 计划时间
    searchBasicParams() {
      this.planBeat = 0
      var param = []
      param[0] = ['opname', this.station]
      var Data = this.CreateData('11', 'LG_临工看板_设备管理_基础参数时间查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length !== 0) {
          this.planBeat = response.data[0].产品额定时间
        }
      })
    },
    // 监听基础参数设定成功后 查询
    setBasicParamSuccess() {
      this.searchBasicParams()
    },
    closePage() {
      window.location.href = 'about:blank'
      window.close()
    }
  }
}
</script>
<style scoped>
  .is-selected {
    color: #1989FA;
  }
  .first-station{
    /*background-size: 100% 100%;*/

    width:1920px;
    height: 1080px;
    color: white;
    background-size: 100%;
    /*background: #00065b url(../../img/bg.jpg) no-repeat 0 0;*/
    /*color: white;*/
  }
  /*警示灯提示文字*/
  .leftTips{
    float: right;
    font-size: 1.2rem;
    font-weight: bolder;
    margin-right: 30px;
    color: white;
    margin-top: -3px
  }
  .rightTips{
    float: right;
    margin-right: 30px;
    font-size: 1.2rem;
    font-weight: bolder;
    color: white;
    margin-top: -3px
  }
  /*警示灯*/
  .lamp{
    width: 20px;
    height: 20px
  }
  .data-box1 {
    color: white;
    position: absolute;
    -webkit-box-shadow: rgb(24, 78, 135) 0 0 10px;
    -moz-box-shadow: rgb(24, 78, 135) 0 0 10px;
    box-shadow: inset 0 0 30px rgb(24, 78, 135);
  }
  .boxBorder{
    position:absolute;
    padding:10px;
    border-style: solid;
    border-color: rgb(71, 209, 226);
  }
  .borderLeft1{border-width: 2px 0 0 2px;top:-2px;left:-2px;}
  .borderLeft2{border-width: 2px 2px 0 0;top:-2px;right:-2px;}
  .borderRight1{border-width: 0 0 2px 2px;bottom:-2px;left:-2px;}
  .borderRight2{border-width: 0 2px 2px 0;bottom:-2px;right:-2px;}
  .indicatorBlock {
    float: left;
    margin: 12px 0 0 30px;
    width: 15px;
    height: 26px;
    background-color: #016eea
  }
  .indicatorText {
    margin: 16px 0 0 20px;
    float: left;
    font-size:20px
  }
</style>
<style scoped lang="scss">
  /*去掉导航栏*/
  /*::v-deep .el-tabs__nav-scroll{*/
  /*  display: none;*/
  /*}*/
  /*导航栏边框样式*/
  /*::v-deep[data-v-44dbd77e] .el-tabs--card>.el-tabs__header .el-tabs__item {*/
  /*  border: 2px solid white;*/
  /*}*/
  ::v-deep .yellowLight {background-color:yellow;width: 20px;height: 20px;border-radius: 15px;text-align: center;height: 20px;width: 20px;margin: 0px 0px 0px 10px}
  ::v-deep .greyLight {
    background-color:white;
    width: 20px;height: 20px;border-radius: 15px;text-align: center;height: 20px;width: 20px;margin: 0px 0px 0px 10px
  }
  ::v-deep .greenLight {background:green;width: 20px;height: 20px;border-radius: 15px;text-align: center;height: 20px;width: 20px;margin: 0px 0px 0px 10px }
  ::v-deep .redLight {background:red;width: 20px;height: 20px;border-radius: 15px;text-align: center;height: 20px;width: 20px;margin: 0px 0px 0px 10px}

  /*::v-deep .el-tabs__item.is-active{*/
  /*  background: white;*/
  /*}*/
  /*::v-deep .el-tabs__header{*/
  /*  border: 0px solid #E4E7ED;*/
  /*  margin: 0px;*/
  /*}*/
  /*::v-deep .el-tabs--card>.el-tabs__header .el-tabs__nav{*/
  /*  border: 0px solid #E4E7ED;*/
  /*}*/
  /*::v-deep .el-tabs--card>.el-tabs__header .el-tabs__item{*/
  /*  border: 1px solid #E4E7ED;*/
  /*  text-align: center;*/
  /*}*/
  /*::v-deep .el-tabs__item{*/
  /*  font-size: 28px;*/
  /*  width: 260px;*/
  /*  height: 45px;*/
  /*  border-radius: 5px;*/
  /*}*/
  ::v-deep .el-divider--horizontal{
     margin: 5px 0;
   }
  ::v-deep .el-dialog__title {
    font-size: 26px;
  }
  ::v-deep .el-form-item__label{
    color: #000000;
  }
  .andonCallList {
    width: 200px;
    height: 80px;
    font-size: 20px;
    text-align: center;
    margin-left: 5px;
    line-height: 2;
    color: #fff
  }
  .alarmInfo{
    font-size: 20px;
  }
</style>
<style>
  /*右下角设备加工信息样式*/
  HTML{
    overflow: auto;
  }
  body{
    margin:0;
    padding:0;
    position: relative;
    /*background: #012a61;*/
    background-size: 100% 100%;
    width: 100%;
    height: 100%;
    background: #012a61 url(../../img/bg.jpg) no-repeat 0 0;
    background-size: 100%;
    color: white;
    /*background: rgba(0, 0, 0, 0.2);*/
  }
  /*css主要部分的样式*/
  /*定义滚动条宽高及背景，宽高分别对应横竖滚动条的尺寸*/
  ::-webkit-scrollbar {
    width: 5px; /*对垂直流动条有效*/
    height: 5px; /*对水平流动条有效*/
  }

  /*定义滚动条的轨道颜色、内阴影及圆角*/
  ::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
    background-color: #dedede;
    /*background-color: #ffffff;*/
    border-radius: 2px;
  }

  /*定义滑块颜色、内阴影及圆角*/
  ::-webkit-scrollbar-thumb {
    border-radius: 5px;
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
    background-color: #b1b1b1;
  }

  /*定义两端按钮的样式*/
  ::-webkit-scrollbar-button {
    display: none;
  }

  /*定义右下角汇合处的样式*/
  ::-webkit-scrollbar-corner {
    background: #dedede;
  }
</style>
