<script lang="ts" setup>
import { sendCmd, subscribeEvent, syncSendCmd } from 'apis/system'
import homeFinish from 'assets/images/home/home-finish.svg'
import homeStart from 'assets/images/home/home-start.svg'
import SealInstrumentSvg from 'assets/images/seal/seal-instrument.svg'
import SoftKeyboard from 'components/common/SoftKeyboard/index.vue'
import DashboardChart from 'components/seal/DashboardChart.vue'
import { startPosityveTimer, stopPosityveTimer } from 'libs/timer'
import { computed, onMounted, ref, watch, watchEffect } from 'vue'

import { getDeviceStatus } from '@/libs/deviceComm'
import { FtMessage } from '@/libs/message'
import { FtMessageBox } from '@/libs/messageBox'
import { useSealStore } from '@/stores/sealStore'
import { useSystemStore } from '@/stores/systemStore'

defineOptions({
  name: 'Seal',
})
const sealStore = useSealStore()
const systemStore = useSystemStore()
const sealInfo = ref(sealStore.sealInfo)
const inputValue = ref('')
const keyboardVisible = ref(false)
const keyboardType = ref<'text' | 'number'>('number')
const softKeyboardRef = ref()
const inflationTime = ref()
const sealRemainTimeS = ref<string>()
const currentPressure = ref(sealStore.sealInfo.pressure)
const realTimePressure = ref(sealStore.sealInfo.pressure)
const loading = ref(false)

onMounted(() => {
  // initData()
  systemStore.subscribeSealEvent()
  subscribeSealState()
  initAirLeakConfig()
})

const getFirstPressure = () => {
  // 当前气压是开始测试后，状态变为leakTesting后，6秒后获取的压力值为初始值。 由赵贺确认
  if (sealInfo.value.workState === 'leakTesting') {
    // 开始计时
    startPosityveTimer((time) => {
      sealRemainTimeS.value = time
    })
    loading.value = false
    if (!currentPressure.value) {
      currentPressure.value = realTimePressure.value
    }
  }
}

watchEffect(() => {
  sealInfo.value = sealStore.sealInfo
  realTimePressure.value = sealStore.sealInfo.pressure
  getFirstPressure()
})

watch(inputValue, (newVal: string | number) => {
  if (Number(newVal) < 1000) {
    inflationTime.value = newVal
  }
  // else {
  //   inputValue.value = inflationTime.value
  // }
})

/**
 * @function 初始化打压配置
 * @desc 获取打压配置
 */
const initAirLeakConfig = async () => {
  const params = {
    className: 'AirLeakDetectTest',
    fnName: 'getServiceConfig',
  }
  const res = await sendCmd(params)
  inflationTime.value = res.inflationTimeMs
}

const subscribeSealState = () => {
  // 订阅测试状态
  subscribeEvent('stateUpdate', (data: Socket.WebSocketResponse<Seal.SealStateItem>) => {
    if (data.fromClass === 'AirLeakDetectTest') {
      // 更新测试状态
      sealStore.updateSealInfo(data.rely)
    }
  })
}

const stopText = computed(() => {
  return sealInfo.value.workState === 'stopping' ? '停止中...' : '停止测试'
})

// const pressure = ref()
const onStartTest = () => {
  const statusName = getDeviceStatus()
  if (statusName) {
    FtMessageBox.error(statusName)
    return
  }
  const params = {
    className: 'AirLeakDetectTest',
    fnName: 'start',
    params: {
      inflationTimeMs: 0,
    },
  }
  loading.value = true
  syncSendCmd(params).then((res) => {
    if (res.ackcode === 0) {
      FtMessage.success('开始执行密封测试')
    }
    else {
      FtMessage.error('指令发送失败，请稍候再试')
    }
  }).catch(() => {
    FtMessage.error('指令发送失败，请稍候再试')
  })
}
const onFinishTest = () => {
  const stopParams = {
    className: 'AirLeakDetectTest',
    fnName: 'stop',
    params: {},
  }
  loading.value = true
  syncSendCmd(stopParams).then((res) => {
    if (res.ackcode === 0) {
      // 停止倒计时
      stopPosityveTimer()
      FtMessage.success('测试已停止')
      sealRemainTimeS.value = ''
    }
    loading.value = false
  }).finally(() => {
    loading.value = false
  })
}

const handleConfirm = (value: string) => {
  console.log('确认输入:', value)
}

const stopDisabled = computed(() => {
  return sealInfo.value.workState === 'stopping' || sealInfo.value.workState === 'idle'
})

const diffPressure = computed(() => {
  return Number(currentPressure.value) - Number(realTimePressure.value)
})
</script>

<template>
  <div v-loading="loading" class="dashboard-container">
    <main class="main-content">
      <div class="seal-left">
        <!-- 仪表盘 -->
        <div class="seal-chart">
          <div class="chart-ml">
            <DashboardChart />
          </div>
          <div class="seal-opt">
            <div class="seal-status">
              <div class="seal-time-text">
                测试时间：
              </div>
              <div v-if="sealInfo.workState === 'idle'" class="seal-time-statue seal-time-text">
                未开始
              </div>
              <div v-else class="seal-test-time">
                {{ sealRemainTimeS }}
              </div>
            </div>
            <div class="seal-status">
              <div class="seal-diff-text">
                测试前气压：
              </div>
              <div v-if="sealInfo.workState === 'idle'" class="seal-diff-statue seal-diff-text">
                未开始
              </div>
              <div v-else class="seal-test-time">
                {{ currentPressure }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="seal-right">
        <div class="left-title">
          <div class="title-text-test">
            <img :src="SealInstrumentSvg" alt="仪表盘">
            <div class="title-text">
              气压差值
            </div>
            <div class="title-text title-text-kpa">
              <span>{{ diffPressure }}</span>
              <span class="title-kpa-pl">Kp</span>
            </div>
          </div>
        </div>
        <div class="seal-right-btn">
          <div>
            <div class="seal-add-btn">
              <bt-button
                button-text="启动测试"
                bg-color="#31CB7A"
                text-color="#FFFFFF"
                width="27vw"
                height="7vh"
                text-size="24px"
                border-radius="12px"
                :disabled="sealInfo.workState !== 'idle'"
                min-height="4rem"
                @click="onStartTest"
              >
                <template #icon>
                  <img :src="homeStart" alt="">
                </template>
              </bt-button>
            </div>
            <div class="seal-add-btn">
              <bt-button
                :button-text="stopText"
                bg-color="#FF6767"
                text-color="#FFFFFF"
                width="27vw"
                height="7vh"
                text-size="24px"
                border-radius="12px"
                :disabled="stopDisabled"
                min-height="4rem"
                @click="onFinishTest"
              >
                <template #icon>
                  <img :src="homeFinish" alt="">
                </template>
              </bt-button>
            </div>
          </div>
        </div>
      </div>
    </main>
    <SoftKeyboard
      ref="softKeyboardRef"
      v-model="inputValue"
      :is-visible="keyboardVisible"
      :keyboard-type="keyboardType"
      @update-keyboard-visible="(visible: boolean) => keyboardVisible = visible"
      @confirm="handleConfirm"
      @close="keyboardVisible = false"
    />
  </div>
</template>

<style lang="scss" scoped>
.main-content{
  display: grid;
  grid-template-columns: repeat(3,1fr);
  height: $main-container-height;
  gap: 10px;
  .seal-left{
    background: #FFFFFF;
    grid-column:  1 / 3;
    box-shadow: 0px 1px 5px 0px rgba(9, 39, 62, 0.15);
    background: $gradient-color;
    .seal-chart{
    }
    .chart-ml{
      margin: 2rem;
      height: 32rem;
    }
  }
}
.seal-opt{
  display: flex;
  gap: 2rem;
  margin-left: 9rem;
  margin-top: -2rem;
  .seal-status{
    display: flex;
    justify-content: center;
    align-items: center;
    background: #F6FAFE;
    width: 16rem;
    height: 5rem;
    border-radius: 15px;
  }
  .seal-time-text{
    font-size: 1.5rem;
    font-weight: 500;
    padding-left: 0.5rem;
  }
  .seal-test-time{
    font-size: 24px;
    color: #2892F3;
  }
  .seal-time-statue{
    height: 3rem;
    width: 5rem;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: 600;
  }
  .seal-diff-text{
    font-size: 1.5rem;
    font-weight: 500;
    padding-left: 0.5rem;
  }
  .seal-diff-statue{
    height: 3rem;
    width: 5rem;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: 600;
  }
}

.seal-right{
  background: $gradient-color;
  display: grid;
  grid-template-rows: repeat(2, 1fr);
  .left-title{
    //padding-top: 3.5vw;
    padding-left: 2.5vw;
    display: flex;
    .title-text-test{
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 1rem;
      .title-text{
        font-size: 20px;
      }
      .title-text-kpa{
        color: #409EFF;
      }
      .title-kpa-pl{
        padding-left: 5px;
        font-weight: bold;
      }
    }
  }
  .seal-right-btn{
    height: 30vh;
    grid-row: 2 / 4;
    margin-top: -6rem;
    .seal-input{
      padding-left: 2rem;
      height: 8rem;
      font-size: 2.143vw;
      font-weight: 400;
      .inflation-time{
        height: 4rem;
      }
      .seal-diff-text{
        height: 4rem;
      }
      .input{
        width: 25vw;
      }
    }
    .seal-add-btn{
      width: 25vw;
      height: 12vh;
      border-radius: 12px;
      color: #FFFFFF;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      gap: 10px;
      margin: 2rem;
    }
  }
}
</style>
