<template>
  <div style="overflow: hidden">
    <el-row>
      <div id="container" className="container" style="min-height: 100%" />
    </el-row>
    <!--点击设备显示信息-->
    <el-dialog
      id="dialogs"
      title="设备信息"
      class="newDialog"
      :visible.sync="dialogDeviceMsgVisible"
      width="22%"
      :top="tops"
      :show-close="false"
      :modal="false"
    >
      <el-table
        :data="arr"
        style="width: 100%"
        max-height="500px"
      >
        <el-table-column
          prop="name"
          label="监控项"
        />
        <el-table-column
          prop="value"
          label="当前值"
        />
      </el-table>
    </el-dialog>
    <!--弹窗设置设备与图标绑定与角度-->
    <el-dialog title="设备设置" :visible.sync="dialogFormVisible" width="35%">
      <el-form :model="form" size="small">
        <el-form-item label="设备编号" prop="device_code" label-width="80px">
          <el-input v-model="form.device_code" :disabled="true" />
        </el-form-item>

        <el-form-item label="设备状态" label-width="80px">
          <el-radio-group v-model="form.hasGoodStatus">
            <el-radio-button :label="0">无货</el-radio-button>
            <el-radio-button :label="1">有托盘</el-radio-button>
            <el-radio-button :label="2">有托盘有货</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogSave">确 定</el-button>
      </div>
    </el-dialog>

    <!--弹窗设置设备与图标绑定与角度-->
    <el-dialog title="设备设置" :visible.sync="dialogFormVisible3" width="35%">
      <el-form :model="form" size="small">
        <el-form-item label="设备编号" prop="device_code" label-width="80px">
          <el-input v-model="form.device_code" :disabled="true" />
        </el-form-item>
        <el-form-item label="设备状态" label-width="80px">
          <el-radio-group v-model="form.hasGoodStatus">
            <el-radio-button :label="0">无货</el-radio-button>
            <el-radio-button :label="1">空料斗</el-radio-button>
            <el-radio-button :label="2">满料斗</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="物料编码" prop="material_type" label-width="80px">
          <el-input v-model="form.material_type" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="dialogSave">确 定</el-button>
      </div>
    </el-dialog>

    <!--弹窗设置设备与图标绑定与角度-->
    <el-dialog title="设备设置" :visible.sync="dialogFormVisible4" width="35%">
      <el-form :model="form" size="small">
        <el-form-item label="设备编号" prop="device_code" label-width="120px">
          <el-input v-model="form.device_code" :disabled="true" />
        </el-form-item>
        <el-form-item label="禁用机械手" prop="is_disable" label-width="120px">
          <el-radio-group v-model="form.is_disable">
            <el-radio-button :label="0">正常</el-radio-button>
            <el-radio-button :label="1">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible4 = false">取 消</el-button>
        <el-button type="primary" @click="dialogSave">确 定</el-button>
      </div>
    </el-dialog>

    <!--弹窗设置设备与图标绑定与角度-->
    <el-dialog title="设备设置" :visible.sync="dialogFormVisible1" width="35%">
      <el-form :model="form" size="small">
        <el-form-item label="设备编号" prop="device_code" label-width="80px">
          <el-input v-model="form.device_code" :disabled="true" />
        </el-form-item>

        <el-form-item label="条码" label-width="80px">
          <el-input v-model="form.barcode" :disabled="false" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="saveBarcode">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crudStage from '@/api/logicflow/stage'
import paramCrud from '@/api/system/param'
import deviceCrud from '@/api/acs/device/device'
import { getDeviceByCodes } from '@/api/acs/device/deviceStageMonitor'
import '@logicflow/core/dist/style/index.css'
import '@logicflow/extension/lib/style/index.css'

import { LogicFlow } from '@logicflow/core'
import { registerCustomElement } from '@/views/system/logicflow/editor/components/node'

let data = {}
let lf = ''
export default {
  name: 'MonitorDevice',
  data() {
    return {
      stageParam: 'stage_code', // 舞台参数
      dialogDeviceMsgVisible: false, // 显示设备信息的dialog
      device_code: null,
      tops: '20vh', // 初始top
      stage_code: '',
      stageSelectList: [],
      arr: [], // 显示数组
      dialogFormVisible: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      dialogFormVisible4: false,
      form: {
        device_code: '',
        hasGoodStatus: null,
        barcode: '',
        suspended: null,
        material_type: '',
        requireSucess: '',
        fullrequireSucess: '',
        is_disable: ''
      },
      allDeviceMsg: [],
      msgTop: '200px',
      msgLeft: '200px'
    }
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    // js提供的clearInterval方法用来清除定时器
    console.log('定时器销毁')
    clearInterval(this.timer)
  },
  methods: {
    // 流程图初始化
    init() {
      // 初始化配置
      lf = new LogicFlow({
        overlapMode: 1,
        container: document.querySelector('#container'), // 容器
        // 画布配置
        // width: window.innerWidth, // 宽度
        height: window.innerHeight, // 高度
        grid: { // 不用格子直接显示，使用背景
          visible: false,
          type: 'mesh',
          size: 5
        },
        background: {
          backgroundImage: 'url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PHBhdHRlcm4gaWQ9ImdyaWQiIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgcGF0dGVyblVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+PHBhdGggZD0iTSAwIDEwIEwgNDAgMTAgTSAxMCAwIEwgMTAgNDAgTSAwIDIwIEwgNDAgMjAgTSAyMCAwIEwgMjAgNDAgTSAwIDMwIEwgNDAgMzAgTSAzMCAwIEwgMzAgNDAiIGZpbGw9Im5vbmUiIHN0cm9rZT0iI2QwZDBkMCIgb3BhY2l0eT0iMC4yIiBzdHJva2Utd2lkdGg9IjEiLz48cGF0aCBkPSJNIDQwIDAgTCAwIDAgMCA0MCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjZDBkMGQwIiBzdHJva2Utd2lkdGg9IjEiLz48L3BhdHRlcm4+PC9kZWZzPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9InVybCgjZ3JpZCkiLz48L3N2Zz4=")',
          backgroundRepeat: 'repeat'
        },
        isSilentMode: true,
        adjustEdge: false,
        adjustEdgeMiddle: false,
        adjustEdgeStartAndEnd: false,
        adjustNodePosition: false,
        hideAnchors: true,
        nodeTextEdit: false,
        edgeTextEdit: false
      })
      lf.setTheme(
        {
          baseEdge: { strokeWidth: 1 },
          baseNode: { strokeWidth: 1 },
          nodeText: { overflowMode: 'autoWrap', lineHeight: 1.5 },
          edgeText: { overflowMode: 'autoWrap', lineHeight: 1.5 }
        }
      )
      // 注册自定义元素
      registerCustomElement(lf)
      // 删除默认的右键菜单
      lf.extension.menu.setMenuConfig({
        nodeMenu: false
      })
      lf.on('node:click', (data, e) => { // 鼠标点击节点
        console.log('data: ', data)
        // 展开显示设备信息
        if (data.data.type !== 'pro-rect' && data.data.type !== 'pro-circle' && data.data.type !== 'triangle' && data.data.type !== 'rect-radius') {
          if (data.data.properties.device) {
            this.moveShow(data.data) // 传递节点数据，用来获取id做比对
            this.dialogDeviceMsgVisible = true
            this.device_code = data.data.properties.device
            this.tops = data.e.y + 'px'
            document.getElementsByClassName('el-dialog')[0].style.marginLeft = data.e.x + 'px'
          }
        }
      })
      lf.on('node:contextmenu', (data, e, position) => { // 右键编辑
        if (data.data.type !== 'pro-rect' && data.data.type !== 'pro-circle' && data.data.type !== 'triangle' && data.data.type !== 'rect-radius') {
          if (data.data.properties.device) {
            this.editDevice(data.data.id) // 编辑
          }
        }
      })
      // 开始渲染
      lf.render(data)
      this.initStageData()
    },
    initStageData() {
      // 获取舞台编码
      paramCrud.getValueByCode(this.stageParam).then(res => {
        // console.log(res)
        if (res.value) {
          crudStage.getNewStageDataByCode(res.value).then(res => { // 通过舞台编码获取舞台数据并且赋值到lf对象
            data = JSON.parse(res.stage_data)
            lf.render(data)
            this.initStatus() // 初始化状态
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: '请设置参数!'
          })
        }
      })
      this.timer = setInterval(() => { // 定时刷新设备的状态信息
        console.log('定时器启动')
        this.initStatus()
      }, 2000)
    },
    editDevice(id) {
      let item = ''
      for (const i in this.allDeviceMsg) { // 查找点击节点的id
        if (id === this.allDeviceMsg[i].id) {
          item = this.allDeviceMsg[i]
          break // 匹对完退出
        }
      }
      const clickObj = item
      console.log('clickObj.data', clickObj.data)
      if (!item.data) {
        return
      }
      if (!clickObj.data.is_click) {
        return
      }
      if (clickObj.data.device_type === 'scanner') { // 扫码器
        this.dialogFormVisible1 = true
      } else {
        if (clickObj.data.driver_type === 'standard_ordinary_site') {
          this.dialogFormVisible3 = true
        } else if (clickObj.data.driver_type === 'hailiang_packer_station') {
          this.dialogFormVisible4 = true
        } else if (clickObj.data.driver_type === 'hailiang_xj_plc_test') {
          this.$refs.child1.setForm(clickObj)
        } else if (clickObj.data.driver_type === 'slit_two_manipulator') {
          this.dialogFormVisible4 = true
        } else {
          this.dialogFormVisible = true
        }
      }
      this.form.angle = clickObj.angle
      this.form.index = clickObj.index
      this.form.device_code = clickObj.device_code
      this.form.hasGoodStatus = clickObj.data.hasGoods
      this.form.material_type = clickObj.data.material_type
      this.form.requireSucess = clickObj.data.requireSucess
      this.form.fullrequireSucess = clickObj.data.fullrequireSucess
      this.form.is_disable = clickObj.data.is_disable1
    },
    moveShow(nodeData) { // 点击之后显示出来的数据----只需要设备信息
      let item = ''
      for (const i in this.allDeviceMsg) { // 查找点击节点的id
        if (nodeData.id === this.allDeviceMsg[i].id) {
          item = this.allDeviceMsg[i]
          break // 匹对完退出
        }
      }
      this.arr = [] // 清空
      if (item.device_code && item.data) {
        // console.log('item', item)
        this.arr = [
          { name: '设备编号', value: item.device_code },
          { name: '设备名称', value: item.device_name }
        ]
        const data = item.data
        for (const val in data) {
          if (val === 'isOnline' || val === 'isError' || val === 'hasGoods') {
            continue
          }
          if (val === 'message' && data.isError === true) {
            const obj = { name: '设备信息', value: data[val] }
            this.arr.push(obj)
          }

          if (val === 'message' && data.isError === 'false') {
            const obj = { name: '异常信息', value: data[val] }
            this.arr.push(obj)
          }

          if (val === 'move') {
            const obj = { name: '光电信号', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'mode') {
            const obj = { name: '模式', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'error') {
            const obj = { name: '报警', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'ip') {
            const obj = { name: 'IP地址', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'number') {
            const obj = { name: '托盘数量', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'instruction_message') {
            const obj = { name: '指令信息', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'last_instruction_message') {
            const obj = { name: '上次指令信息', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'container') {
            const obj = { name: '载具号', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'last_container') {
            const obj = { name: '上次载具号', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'instruction_code') {
            const obj = { name: '指令号', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'last_instruction_code') {
            const obj = { name: '上次指令号', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'action') {
            const obj = { name: '动作信号', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'io_action') {
            const obj = { name: '允许进出信号', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'material') {
            const obj = { name: '物料', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'batch') {
            const obj = { name: '批次', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'requestSucess') {
            const obj = { name: '是否请求任务', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'applySucess') {
            const obj = { name: '是否申请指令', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'message') {
            const obj = { name: '说明', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'status') {
            const obj = { name: '设备状态', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'open_time') {
            const obj = { name: '开机时间', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'close_time') {
            const obj = { name: '关机时间', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'standby_time') {
            const obj = { name: '待机时间', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'production_time') {
            const obj = { name: '生产时间', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'error_time') {
            const obj = { name: '故障时间', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'weight') {
            const obj = { name: '生产重量', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'order_No') {
            const obj = { name: '工单号', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'mix_num') {
            const obj = { name: '碾次', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'barcode') {
            const obj = { name: '条码', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'qualified') {
            const obj = { name: '合格数量', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'unqualified') {
            const obj = { name: '不合格数量', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'put_station') {
            const obj = { name: '当前码盘工位', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'encoder_qty') {
            const obj = { name: '码盘数量', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'outKiln_move') {
            const obj = { name: '出窑光电', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'outKiln_barcode') {
            const obj = { name: '出窑条码', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'outKiln_device') {
            const obj = { name: '出窑设备', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'car_sum') {
            const obj = { name: '窑车总数', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'nullCar_qty') {
            const obj = { name: '空窑车数', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'burning_car_qty') {
            const obj = { name: '在烧窑车数', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'container_qty') {
            const obj = { name: '托盘数', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'tray_crib_qty') {
            const obj = { name: '托盘垛数', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'total_container') {
            const obj = { name: '托盘总数量', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'total_split') {
            const obj = { name: '累计拆垛数量', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'getStation') {
            const obj = { name: '当前抓取工位', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'putStation') {
            const obj = { name: '当前码盘工位', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'move_1') {
            const obj = { name: '前工位光电信号', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'move_2') {
            const obj = { name: '后工位光电信号', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'action_1') {
            const obj = { name: '前工位动作信号', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'action_2') {
            const obj = { name: '后工位动作信号', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'walk_y') {
            const obj = { name: '行走列', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'task1') {
            const obj = { name: '前工位任务号', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'task2') {
            const obj = { name: '后工位任务号', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'labeling_qty') {
            const obj = { name: '贴标数量', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'container_type') {
            const obj = { name: '托盘类型', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'specifications') {
            const obj = { name: '规格', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'onoff_status') {
            const obj = { name: '开关机状态', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'task_qty') {
            const obj = { name: '当前任务数量', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'finishTask_qty') {
            const obj = { name: '完成任务数量', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'AlongSide') {
            const obj = { name: 'A长边', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'BshortSide') {
            const obj = { name: 'B短边', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'Htrapezoidal') {
            const obj = { name: 'H梯形高', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'Wthickness') {
            const obj = { name: 'W厚度', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'is_disable') {
            const obj = { name: '是否禁用', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'notCreateTaskMessage') {
            const obj = { name: '任务创建失败原因', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'notCreateInstMessage') {
            const obj = { name: '指令创建失败原因', value: data[val] }
            this.arr.push(obj)
          } else if (val === 'feedMessage') {
            const obj = { name: '未反馈电气信号原因', value: data[val] }
            this.arr.push(obj)
          }
        }
      }
      // console.log('arr:', this.arr)
    },
    initStatus() { // 初始化所有节点的设备信息，通过节点id对应设备编号
      let resion = {}
      resion = lf.getGraphData().nodes.map(item => ({ id: item.id, device_code: item.properties.device }))
      getDeviceByCodes(resion).then(res => {
        console.log(res)
        this.allDeviceMsg = res // 拿到所有节点的设备数据
        // console.log('initStatus-res', res)
        // 实时设置状态信息
        for (var item of res) { // 循环并且设置属性值
          if (item.data !== undefined) {
            if (item.data.isOnline !== undefined) {
              lf.setProperties(item.id, {
                isOnline: item.data.isOnline
              })
            }
            if (item.data.hasGoods !== undefined) {
              lf.setProperties(item.id, {
                hasGoods: item.data.hasGoods
              })
            }
            if (item.data.isError !== undefined) {
              lf.setProperties(item.id, {
                isError: item.data.isError
              })
            }
          }
        }
        // 设置动态实时显示设备信息
        const { nodes } = lf.getSelectElements() // 获取选中的节点
        // console.log(nodes)
        if (nodes.length === 1) { // 因为是定时器，没有选中则不用实时更新显示数据
          this.moveShow(nodes[0]) // 监控模式下不可能托选，因此就只有一个数据
        }
      })
    },
    dialogSave() {
      deviceCrud.changeDeviceStatus(this.form).then(res => {
        this.$notify({ title: '操作成功', message: '', type: 'success' })
        this.dialogFormVisible = false
        this.dialogFormVisible3 = false
        this.dialogFormVisible4 = false
        this.initStageData()
      }).catch(err => {
        this.dialogFormVisible = false
        this.dialogFormVisible3 = false
        this.dialogFormVisible4 = false
        console.log(err.response.data.message)
      })
    },
    saveBarcode() {
      deviceCrud.saveBarcode(this.form).then(res => {
        this.notify('操作成功', 'success')
        this.dialogFormVisible1 = false
        this.initStageData()
      }).catch(err => {
        this.dialogFormVisible1 = false
        console.log(err.response.data.message)
      })
    }
  }
}
</script>

<style>
html, body {
  height: 100%;
}

body {
  padding: 0;
  margin: 0;
}
</style>
<style scoped>
.container {
  background-color: #f8f9fa;
  height: 100%;
}

.newDialog /deep/ .el-dialog__header {
  padding: 1vh 1vw 0 1vw;
}

.newDialog /deep/ .el-dialog__body {
  padding: 1vh 1vw;
}

.toolbar-sty {
  position: absolute;
  margin-top: 5px;
  top: 0;
  padding: 5px;
  left: 30px;
  height: 45px;
  /*width: 310px;*/
  display: flex;
  align-items: center;
  border-bottom: 1px solid #e5e5e5;
  z-index: 10;
  background: #e5e5e5;
}
</style>
