<template>
  <div class="app-container opw-page">
    <el-alert
      v-if="showNewTabHint"
      title="当前页签未选择设备，请前往首页选择已登录设备后再操作"
      type="warning"
      show-icon
      :closable="false"
      class="mb16"
    />
    <el-alert
      v-else-if="!ownerDeviceSn"
      title="请先在首页选择已登录设备并建立连接"
      type="warning"
      show-icon
      :closable="false"
      class="mb16"
    />
    <template v-if="canOperateDevice">
      <el-row type="flex" justify="space-between" align="middle" class="mb16">
        <el-col :span="16">
          <el-tag :type="wsConnected ? 'success' : 'info'" size="small">
            {{ wsConnected ? 'WebSocket 已连接' : 'WebSocket 未连接' }}
          </el-tag>
          <span class="bind-text">设备 SN：{{ ownerDeviceSn }}</span>
        </el-col>
        <el-col :span="8" style="text-align: right">
          <el-button size="mini" type="primary" @click="reconnectWs">重连</el-button>
        </el-col>
      </el-row>
      <keep-alive>
        <component
          :is="activeComponent"
          :key="subPageKey"
          :bound-device-sn="ownerDeviceSn"
          @navigate="onNavigate"
        />
      </keep-alive>
    </template>
  </div>
</template>

<script>
import tsbWebSocket from '@/utils/tsbWebSocket'
import OpwMain from './main'
import OpwQuery from './query'
import OpwPassthrough from './passthrough'

const SUB_COMPONENTS = {
  main: OpwMain,
  query: OpwQuery,
  passthrough: OpwPassthrough
}

export default {
  name: 'TsbOpwPage',
  components: { OpwMain, OpwQuery, OpwPassthrough },
  props: {
    boundDeviceSn: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      wsConnected: false,
      wsTimer: null
    }
  },
  computed: {
    ownerDeviceSn() {
      if (this.boundDeviceSn != null && this.boundDeviceSn !== '') {
        return this.boundDeviceSn
      }
      return this.$store.getters.tsbCurrentDeviceSn || tsbWebSocket.getCurrentDeviceSn()
    },
    showNewTabHint() {
      return this.$store.getters.tsbSessionReady && this.$store.getters.tsbIsNewTabWithoutDevice && !this.ownerDeviceSn
    },
    canOperateDevice() {
      const activeSn = this.$store.getters.tsbCurrentDeviceSn
      return !!this.ownerDeviceSn
        && String(activeSn) === String(this.ownerDeviceSn)
        && !this.showNewTabHint
    },
    currentSubPage() {
      const map = this.$store.state.tsb.opwSubPageMap || {}
      return map[String(this.ownerDeviceSn)] || 'main'
    },
    activeComponent() {
      return SUB_COMPONENTS[this.currentSubPage] || OpwMain
    },
    subPageKey() {
      return `${this.ownerDeviceSn}-${this.currentSubPage}`
    }
  },
  created() {
    this.ensureSubPage()
    this.wsTimer = setInterval(() => {
      this.wsConnected = tsbWebSocket.isConnected()
    }, 1000)
  },
  activated() {
    this.ensureSubPage()
  },
  beforeDestroy() {
    if (this.wsTimer) {
      clearInterval(this.wsTimer)
    }
  },
  methods: {
    ensureSubPage() {
      if (this.ownerDeviceSn == null) {
        return
      }
      const map = this.$store.state.tsb.opwSubPageMap || {}
      if (!map[String(this.ownerDeviceSn)]) {
        this.$store.commit('tsb/SET_OPW_SUB_PAGE', { deviceSn: this.ownerDeviceSn, subPage: 'main' })
      }
    },
    onNavigate(subPage) {
      if (!subPage || this.ownerDeviceSn == null) {
        return
      }
      this.$store.commit('tsb/SET_OPW_SUB_PAGE', { deviceSn: this.ownerDeviceSn, subPage })
    },
    reconnectWs() {
      tsbWebSocket.reconnect().catch(msg => {
        this.$message.error(msg || '重连失败')
      })
    }
  }
}
</script>

<style scoped>
.opw-page .mb16 { margin-bottom: 16px; }
.bind-text { margin-left: 12px; color: #909399; font-size: 13px; }
</style>
