<template>
  <div>
    <el-tabs type="border-card" v-model="activeTab">
      <el-tab-pane v-for="item in channelList" :key="item" :name="item.stationId">
        <template #label>
          <span class="card-title">通道{{ item.stationId }} </span>
        </template>
        <el-card style="height: calc(100vh - 227.75px)">
          <template #header>
            <span class="card-title">实时出入库数据</span>
            <el-button round style="float: right;" type="primary" @click="showChannelSetting">通道配置</el-button>
            <el-button round style="float: right;margin-right: 10px;" type="warning" @click="clearData">清空数据</el-button>
            <el-button round type="success" @click="changeType(item)" v-show="item.type" style="float: right;">{{ item.type == 'IN' ? '入库模式' : item.type == 'OUT' ? '出库模式': '' }}</el-button>
          </template>
          <el-row :gutter="20">
            <el-col :span="18">
              <el-table :header-cell-style="{backgroundColor: '#f5f7fa',color: '#000',fontSize: '18px',fontWeight: '600'}"
                :row-class-name="tableRowClassName" :data="item.logData" size="large" border style="width: 100%;" max-height="660">
              <el-table-column type="index" label="序号" width="70" align="center"/>
              <el-table-column prop="stationType" label="作业类型" align="center">
                <template #default="scope">
                  {{ scope.row.stationType == 'IN' ? '入库' : '出库' }}
                </template>
              </el-table-column>
              <el-table-column prop="goodsCode" label="品名代码" align="center"/>
              <el-table-column prop="goodsName" label="品名" align="center"/>
              <el-table-column prop="modelName" label="号型" align="center"/>
              <el-table-column prop="amount" label="箱内数量" align="center"/>
              <el-table-column prop="xhNo" label="箱号" align="center"/>
              </el-table>
            </el-col>
            <el-col :span="6">
              <el-card class="box-card">
                <template #header>
                  <div style="text-align: center;">
                    <span class="card-title">识别总箱数</span>
                  </div>
                </template>
                <div class="text">{{ item.logData.length }}箱</div>
              </el-card>
              <el-divider />
              <el-card class="box-card">
                <template #header>
                  <div style="text-align: center;cursor: pointer;">
                    <span @click="changeErr"  class="card-title">异常次数 {{ item.errNum }}次</span>
                  </div>
                </template>
                <div style="height: 280px;overflow: auto" v-if="showErr">
                  <div v-for="item in errList" :key="item.time">
                    <p style="text-align: center;">-----------------{{item.time}}-----------------</p>
                    <p style="text-align: center;">{{item.content}}</p>
                  </div>
                </div>
                <div style="height: 120px;overflow: auto" v-if="!showErr">

                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <el-dialog v-model="visible" width="45%" >
      <template #header>
        <div style="text-align: center;font-size: 18px;font-family: Microsoft YaHei;font-weight: bold;color: #303133;">{{title}}</div>
      </template>
      <el-form size="large" :model="formData">
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <template #title>
              <p class="title">&nbsp;读写器配置</p>
            </template>
            <el-card style="margin: 25px 35px 0 35px;">
            <el-row :gutter="40">
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="formData.readerIp" placeholder="请输入读写器的IP">
                    <template #prefix>
                      <el-icon class="el-input__icon" style="color: #1296db"><Monitor /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="formData.readerPort" placeholder="请输入读写器的端口">
                    <template #prefix>
                      <el-icon class="el-input__icon" style="color: #1296db"><Help /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            </el-card>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template #title>
              <p class="title">&nbsp;天线功率</p>
            </template>
            <el-card style="margin: 25px 35px 0 35px;">
              <el-row :gutter="40">
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="power1" placeholder="请输入1号天线功率" :max="30" :min="0">
                    <template #prefix>
                      <img src="../assets/1.svg" width="16" height="16"/>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="power2" placeholder="请输入2号天线功率">
                    <template #prefix>
                      <img src="../assets/2.svg" width="16" height="16"/>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              </el-row>
              <el-row :gutter="40" style="margin-top: 15px;">
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="power3" placeholder="请输入3号天线功率">
                    <template #prefix>
                      <img src="../assets/3.svg" width="16" height="16"/>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="power4" placeholder="请输入4号天线功率">
                    <template #prefix>
                      <img src="../assets/4.svg" width="16" height="16"/>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              </el-row>
              <el-row :gutter="40" v-if="readerType == 8" style="margin-top: 15px;">
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="power5" placeholder="请输入5号天线功率">
                    <template #prefix>
                      <img src="../assets/5.svg" width="16" height="16"/>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="power6" placeholder="请输入6号天线功率">
                    <template #prefix>
                      <img src="../assets/6.svg" width="16" height="16"/>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              </el-row>
              <el-row :gutter="40" v-if="readerType == 8" style="margin-top: 15px;">
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="power7" placeholder="请输入7号天线功率">
                    <template #prefix>
                      <img src="../assets/7.svg" width="16" height="16"/>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="power8" placeholder="请输入8号天线功率">
                    <template #prefix>
                      <img src="../assets/8.svg" width="16" height="16"/>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              </el-row>
            </el-card>
          </el-collapse-item>
          <el-collapse-item name="3">
            <template #title>
              <p class="title">&nbsp;GPIO配置</p>
            </template>
            <el-card style="margin: 25px 35px 0 35px;">
            <el-row :gutter="40">
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="formData.gpioIp" placeholder="请输入GPIO的IP">
                    <template #prefix>
                      <el-icon class="el-input__icon" style="color: #1296db"><Monitor /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="formData.gpioPort" placeholder="请输入GPIO的端口">
                    <template #prefix>
                      <el-icon class="el-input__icon" style="color: #1296db"><Help /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            </el-card>
          </el-collapse-item>

          <el-collapse-item name="4">
            <template #title>
              <p class="title">&nbsp;LED屏配置</p>
            </template>
            <el-card style="margin: 25px 35px 0 35px;">
              <el-row :gutter="40">
                <el-col :span="12">
                  <el-form-item>
                    <el-input v-model="formData.ledIp1" placeholder="请输入1号显示屏IP">
                      <template #prefix>
                        <el-icon class="el-input__icon" style="color: #1296db"><Monitor /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item>
                    <el-input v-model="formData.ledPort1" placeholder="请输入1号显示屏端口">
                      <template #prefix>
                        <el-icon class="el-input__icon" style="color: #1296db"><Help /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                </el-row>
                <el-row :gutter="40" style="margin-top: 15px;">
                  <el-col :span="12">
                    <el-form-item>
                      <el-input v-model="formData.ledIp2" placeholder="请输入2号显示屏IP">
                        <template #prefix>
                          <el-icon class="el-input__icon" style="color: #1296db"><Monitor /></el-icon>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item>
                      <el-input v-model="formData.ledPort2" placeholder="请输入2号显示屏端口">
                        <template #prefix>
                          <el-icon class="el-input__icon" style="color: #1296db"><Help /></el-icon>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
            </el-card>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visible = false">关闭</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, toRefs, onBeforeUnmount } from 'vue'
import { ElMessage, ElCard } from 'element-plus'
import { postAction, getAction } from '@/api/manage'
import { Help, Monitor } from '@element-plus/icons-vue'
export default defineComponent({
    components: { Monitor, Help },
    setup(props, {emit}) {
      const channelList = ref([]);
      const sysForm = ref({})
      const logData = ref([])
      const visible = ref(false)
      const formData = ref({})
      const activeTab = ref()
      const activeNames = ref(['1','2','3', '4'])
      const readerType = ref(4)
      const title = ref()
      const power1 = ref()
      const power2 = ref()
      const power3 = ref()
      const power4 = ref()
      const power5 = ref()
      const power6 = ref()
      const power7 = ref()
      const power8 = ref()
      const log = ref('')
      const errList = ref([])
      const showErr = ref(false)
      const lockReconnect = ref(false)

      const state = reactive({
        url: {
          getConfig: '/config/getConfig',
          getDevice: '/device/getDevice',
          openReader: '/rfid/openReader',
          updateDevice: '/device/updateDevice',
          removeDevice: '/device/removeDevice',
          saveDevice: '/device/saveDevice',
          updateConfig: '/config/updateConfig',
          getStoreCode: '/config/getStoreCode'
        },
        storeInfo: {},
        storeCode: '',
        lockReconnect: false
      });


      const tableRowClassName = ( { row, rowIndex }) => {
        if (row.isShow) {
          return 'warning-row'
        }
        return ''
      }



      // websocket开始
      let websock = null
      function initWebSocket () {
        // if (websock) {
        //   return
        // }
        websock = new WebSocket(window._CONFIG['wsURL'] + JSON.parse(sessionStorage.getItem('storeInfo')).storeCode);
        websock.onopen = websocketOnopen;
        websock.onerror = websocketOnerror;
        websock.onmessage = websocketOnmessage;
        websock.onclose = websocketClose;
      }

      // Websoket连接成功事件
      const websocketOnopen = (res) => {
        ElMessage.success('服务连接成功');
        console.log("WebSocket连接成功");
      };


      const map = new Map()
      const map1 = new Map()
      // Websoket接收消息事件
      const websocketOnmessage = (res) => {
        let message = JSON.parse(res.data)
        console.log(message)
        if (message.noticeType == 0 || message.noticeType == 4) {
          logData.value = ''
          if (message.noticeType == 0 && message.noticeInfo == 1) {
            map1.set(message.stationId + 'd', 'green')
          } else if ((message.noticeType == 0 && message.noticeInfo == 0) ) {
            map1.set(message.stationId + 'd', '')
          }
          if (message.noticeType == 4 && message.noticeInfo == 1) {
            map1.set(message.stationId + 'g', 'green')
          } else if ((message.noticeType == 4 && message.noticeInfo == 0) ) {
            map1.set(message.stationId + 'g', '')
          }
          let str = '<div>【通道' + message.stationId + ': ' + '</div><div class=' + (map1.get(message.stationId + 'd') || 'red')+ '></div><div>读写器</div><div class='+ (map1.get(message.stationId + 'g') || 'red') + '></div><div>GPIO</div>】'
          map.set(message.stationId, str)
          const sortedArr = Array.from(map).sort((a, b) => a[0] > b[0] ? 1 : -1);
          for(let [key, value] of sortedArr) {
            logData.value += value
          }
          emit('logChange', logData.value)
        }
        if (message.noticeType == 2) {
          if (JSON.parse(sessionStorage.getItem('storeInfo')).isHide) return
          let stationType = message.stationType
          let noticeInfoList = JSON.parse(message.noticeInfo)
          let newArr = noticeInfoList.map(v=> {
            return {...v, stationType: stationType}
          })
          let channel = channelList.value.find(i => i.stationId == message.stationId)
          channel.logData = [...channel.logData,  ...newArr]
          emit('refresh')
        }
        if (message.noticeType == 3) {
          if (!JSON.parse(sessionStorage.getItem('storeInfo')).isHide) return
          let stationType = message.stationType
          let noticeInfoList = JSON.parse(message.noticeInfo)
          let newArr = noticeInfoList.map(v=> {
            return {...v, stationType: stationType}
          })
          let channel = channelList.value.find(i => i.stationId == message.stationId)
          channel.logData = [...channel.logData,  ...newArr]
          let obj = {}
          channel.logData = channel.logData.reduce((item, next) => {
            obj[next.epc] ? '' : obj[next.epc] = true && item.push(next)
            return item
          }, [])
          emit('refresh')
        }
        if (![0,2,3,4].includes(message.noticeType)) {
          let channel = channelList.value.find(i => i.stationId == message.stationId)
          channel.errNum = channel.errNum + 1
          errList.value.unshift({time: parseTime(new Date()), content: message.noticeInfo})
        }
        
      };

      function parseTime(date) {
        var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
        var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
        var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
        return hours + ':' + minutes + ':' + seconds
      }
      // Websoket连接错误事件
      const websocketOnerror = (res) => {
        console.log("WebSocket连接错误");
        reconnect()
      };
      // Websoket断开事件
      const websocketClose = (res) => {
        console.log("WebSocket断开连接");
        emit('logChange', logData.value.replaceAll('green', 'red'))
        console.log(logData.value)
        reconnect()
      };

      function reconnect() {
        if(lockReconnect.value) return;
        lockReconnect.value = true;
        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(() => {
          console.log("尝试重连...,5秒一次");
          initWebSocket();
          lockReconnect.value = false;
        }, 5000);
       }

      onBeforeUnmount(() => {
        console.log('A 组件，切换到 B 组件，A 组件消失时执行')
      })
       

      const loadData = () => {
        if (sessionStorage.getItem('storeInfo')) {
          let config = JSON.parse(sessionStorage.getItem('storeInfo'))
          sysForm.value = {
            id: config.id,
            storeCode: config.storeCode,
            serverIp: config.serverIp,
            serverPort: config.serverPort,
            isHide: config.isHide
          }
          channelList.value = []
          postAction(state.url.getDevice, {storeCode: JSON.parse(sessionStorage.getItem('storeInfo')).storeCode}).then(res => {
            if (res.code !== 99200) return ElMessage.error(res.message);
            res.data.map((item, index) => {
              channelList.value.push(Object.assign({}, item, { logData: [], errNum: 0 }))
            })
            activeTab.value = channelList.value[0].stationId
            emit('logChange', "<div>【通道" + activeTab.value + ": </div><div class=red></div><div>读写器</div><div class=red></div><div>GPIO</div>】")
            initWebSocket()
            getAction(state.url.openReader, {storeCode: JSON.parse(sessionStorage.getItem('storeInfo')).storeCode}).then(res => {
              
            })
          })
        } else {
          getAction(state.url.getStoreCode).then(res => {
            if (res.code !== 99200) {
              emit('changeTab')
              return ElMessage.error(res.message);
            }
            postAction(state.url.getConfig, {storeCode: res.data}).then(res => {
              if (res.code !== 99200) return ElMessage.error(res.message);
              state.storeInfo = res.data[0]
              sessionStorage.setItem('storeInfo', JSON.stringify(state.storeInfo))
              loadData()
            })
          })
        }
      }

      function clearData() {
        let channel = channelList.value.find(i => i.stationId == activeTab.value)
        channel.logData = []
      }

      function changeErr() {
        showErr.value = !showErr.value
        console.log(showErr.value)
      }

      function showChannelSetting() {
        postAction(state.url.getDevice, {storeCode: JSON.parse(sessionStorage.getItem('storeInfo')).storeCode, stationId: activeTab.value}).then(res => {
          if (res.code !== 99200) return ElMessage.error(res.message);
          formData.value = res.data[0]
          readerType.value = res.data[0].readerType
          title.value = activeTab.value + '号通道配置'
          if (res.data[0].readerType == 4) {
            power1.value = res.data[0].readerPower.split(',')[0]
            power2.value = res.data[0].readerPower.split(',')[1]
            power3.value = res.data[0].readerPower.split(',')[2]
            power4.value = res.data[0].readerPower.split(',')[3]
          }
          if (res.data[0].readerType == 8) {
            power1.value = res.data[0].readerPower.split(',')[0]
            power2.value = res.data[0].readerPower.split(',')[1]
            power3.value = res.data[0].readerPower.split(',')[2]
            power4.value = res.data[0].readerPower.split(',')[3]
            power5.value = res.data[0].readerPower.split(',')[4]
            power6.value = res.data[0].readerPower.split(',')[5]
            power7.value = res.data[0].readerPower.split(',')[6]
            power8.value = res.data[0].readerPower.split(',')[7]
          }
          visible.value = true
        })
      }

      function changeType(formData) {
        if (formData.type == 'IN') {
          formData.type = 'OUT'
        } else {
          formData.type = 'IN'
        }
        postAction(state.url.updateDevice, formData).then(res => {
          if (res.code !== 99200) return ElMessage.error(res.message);
          ElMessage.success(res.message)
        })
      }

      function handleSubmit() {
        if (readerType.value == 4) {
          formData.value.readerPower = power1.value + ',' +  power2.value + ',' +  power3.value + ',' +  power4.value 
        }
        if (readerType.value == 8) {
          formData.value.readerPower = power1.value + ',' +  power2.value + ',' +  power3.value + ',' +  power4.value + ',' + power5.value + ',' +  power6.value + ',' +  power7.value + ',' +  power8.value
        }
        postAction(state.url.updateDevice, formData.value).then(res => {
          if (res.code !== 99200) return ElMessage.error(res.message);
          ElMessage.success(res.message)
          formData.value = {}
          visible.value = false
        })
      }

      loadData()
      return {
        ...toRefs(state),
        sysForm,
        channelList,
        log,
        logData,
        formData,
        activeTab,
        readerType,
        activeNames,
        title,
        visible,
        power1,
        power2,
        power3,
        power4,
        power5,
        power6,
        power7,
        power8,
        errList,
        showErr,
        tableRowClassName,
        loadData,
        showChannelSetting,
        handleSubmit,
        clearData,
        changeErr,
        changeType
      }
    },
})
</script>

<style lang="less">
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-5);;
}


// 其他样式代码不变
.el-tabs--border-card >.el-tabs__content {
  padding: 0px !important;
  background-color: var(--color-primary);
}
.text {
  text-align: center;
  font-size: 40px;
}
.head-container {
  padding-bottom: 10px;
  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
    margin-left: 6px;
  }
}

.title {
  font-size: 18px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: #303133;
  padding-bottom: 17px;
  padding-top: 17px;
}




p {
  margin: 0;
  padding: 0;
}
.row {
  overflow: hidden;
  margin-bottom: 22px;
}
.row .col_left {
  float: left;
  width: 420px;
}
.row .col_right {
  float: left;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  height: 26px;
  font-size: 20px;
  font-weight: 'bold';
  font-family: 'Times New Roman', Times, serif;
}

</style>

<style scoped>
</style>
