<template>
  <div class="opw-main">
    <el-card shadow="never">
      <el-row :gutter="12" type="flex" align="middle">
        <el-col :span="8">
          <div class="field-label">波特率</div>
          <el-select v-model="form.baudRate" size="small" style="width: 100%" @change="onBaudRateChange">
            <el-option v-for="item in baudRates" :key="item" :label="item" :value="item" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" size="small" @click="openQuery">液位仪查询</el-button>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" size="small" plain @click="openPassthrough">液位仪透传</el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import tsbWebSocket from '@/utils/tsbWebSocket'
import { OPW_CMD, OPW_BAUDRATES, applyPartialFields } from '@/utils/tsbOpwConfig'

const PAGE_CMD = OPW_CMD.MAIN
const DISPLAY_FIELDS = ['baudRate']

function createDefaultForm() {
  return { baudRate: '9600' }
}

export default {
  name: 'TsbOpwMain',
  props: {
    boundDeviceSn: { type: [Number, String], default: null }
  },
  data() {
    return {
      baudRates: OPW_BAUDRATES,
      form: createDefaultForm()
    }
  },
  computed: {
    ownerDeviceSn() {
      return this.boundDeviceSn
    },
    canOperateDevice() {
      const activeSn = this.$store.getters.tsbCurrentDeviceSn
      return String(activeSn) === String(this.ownerDeviceSn)
    }
  },
  watch: {
    '$store.state.tsb.pageDataVersion'() {
      this.tryApplyWsPageData(false)
    },
    '$store.state.tsb.deviceSwitchVersion'() {
      if (String(this.$store.getters.tsbCurrentDeviceSn) === String(this.ownerDeviceSn)) {
        this.refreshPageFromStore()
      }
    }
  },
  activated() {
    this.refreshPageFromStore()
  },
  deactivated() {
    this.savePageCache()
  },
  methods: {
    pageCacheKey() {
      return this.ownerDeviceSn != null ? `${this.ownerDeviceSn}::opw-main` : null
    },
    pageDataKey() {
      return this.ownerDeviceSn != null ? `${this.ownerDeviceSn}::${PAGE_CMD}` : PAGE_CMD
    },
    savePageCache() {
      const key = this.pageCacheKey()
      if (!key) return
      this.$store.commit('tsb/SET_DEVICE_PAGE_FORM', {
        key,
        data: { form: { ...this.form }, initialized: true }
      })
    },
    restorePageCache() {
      const key = this.pageCacheKey()
      if (!key) return false
      const cached = this.$store.state.tsb.devicePageFormCache[key]
      if (!cached || !cached.initialized) return false
      this.form = { ...cached.form }
      return true
    },
    tryApplyWsPageData(clearInitFlag) {
      const data = this.$store.state.tsb.pageData[this.pageDataKey()]
      if (!data) return false
      applyPartialFields(this.form, data, DISPLAY_FIELDS, createDefaultForm())
      if (clearInitFlag && this.$store.state.tsb.initFromWs[this.pageDataKey()]) {
        this.$store.commit('tsb/CLEAR_WS_INIT', { cmdType: PAGE_CMD, deviceSn: this.ownerDeviceSn })
      }
      this.savePageCache()
      return true
    },
    refreshPageFromStore() {
      if (this.tryApplyWsPageData(true)) return
      if (this.restorePageCache()) return
      this.initPageData()
    },
    initPageData() {
      this.form = createDefaultForm()
      if (this.canOperateDevice) {
        this.syncDefaultParamsToDevice()
      }
      this.savePageCache()
    },
    syncDefaultParamsToDevice() {
      tsbWebSocket.sendPageSync(PAGE_CMD, { ...this.form })
    },
    syncField(payload) {
      if (!this.canOperateDevice) return
      tsbWebSocket.sendPageSync(PAGE_CMD, payload)
    },
    onBaudRateChange(val) {
      this.syncField({ baudRate: val })
      this.savePageCache()
    },
    openQuery() {
      this.$emit('navigate', 'query')
    },
    openPassthrough() {
      this.$emit('navigate', 'passthrough')
    }
  }
}
</script>

<style scoped>
.field-label { font-size: 13px; color: #606266; margin-bottom: 6px; }
</style>
