<script lang="ts" setup>
import { getDeviceStatus } from '@/libs/deviceComm'
import { FtMessage } from '@/libs/message'
import { FtMessageBox } from '@/libs/messageBox'
import { useHomeStore } from '@/stores/homeStore'
import { useLiquidStore } from '@/stores/liquidStore'
import { useSealStore } from '@/stores/sealStore'
import { useSystemStore } from '@/stores/systemStore'
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 SoftKeyboard from 'components/common/SoftKeyboard/index.vue'
import LiquidLevel from 'components/liquid/LiquidLevel.vue'
import { ElMessage } from 'element-plus'
import { roundNumber } from 'libs/utils'
import { computed, onMounted, ref, watchEffect } from 'vue'

const liquidStore = useLiquidStore()
const homeStore = useHomeStore()
const sealStore = useSealStore()
const systemStore = useSystemStore()
const stopatg = ref()
const inputValue = ref('')
const keyboardVisible = ref(false)
const keyboardType = ref<'text' | 'number'>('number')
const softKeyboardRef = ref()
const liquidStateData = ref(liquidStore.liquidStateData)
const addWorkState = ref(liquidStore.liquidStateData)// 加液状态
const drainWorkState = ref(liquidStore.liquidStateData)// 排液状态
const liquidTotoal = ref(liquidStore.liquidTotal)// 总容量
const disinfectionState = ref(homeStore.disinfectionState)
const sealInfo = ref(sealStore.sealInfo)
const loading = ref(false)
const btnStyle = {
  width: '27vw',
  height: '7vh',
  textSize: '24px',
  borderRadius: '12px',
  textColor: '#FFFFFF',
}

onMounted(() => {
  subScribeLiquid()
})

watchEffect(() => {
  stopatg.value = inputValue.value
  addWorkState.value = liquidStore.liquidAddWorkState
  drainWorkState.value = liquidStore.liquidDrainWorkState
  liquidTotoal.value = liquidStore.liquidTotal
  liquidStateData.value = liquidStore.liquidStateData
  disinfectionState.value = homeStore.disinfectionState
  sealInfo.value = sealStore.sealInfo
  loading.value = systemStore.loading
})

const subScribeLiquid = () => { // 事件订阅
  subscribeEvent('stateUpdate', (data: Socket.WebSocketResponse<Liquid.LiquidData>) => {
    if (data.fromClass === 'AddLiquidService') {
      liquidStore.updateAddLiquidWorkState(data.rely)
    }

    if (data.fromClass === 'DrainLiquidService') {
      liquidStore.updateDrainLiquidWorkState(data.rely)
    }
  })
}

const openKeyboard = () => {
  keyboardVisible.value = true
}

const nowLiquid = computed(() => {
  return roundNumber(liquidStateData.value.nowLiquid, 0)
})

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

const onStartAddLiquid = async () => {
  const statusName = getDeviceStatus()
  if (statusName) {
    FtMessageBox.error(statusName)
    return
  }
  if (!stopatg.value || stopatg.value < 0) {
    FtMessage.warning('请输入加液容量')
    return
  }
  if (stopatg.value > liquidTotoal.value) {
    FtMessage.warning('加液容量不能大于总容量')
    return
  }
  const params = {
    className: 'AddLiquidService',
    fnName: 'start',
    params: {
      stopatg: Number(stopatg.value),
    },
  }
  systemStore.updateLoading(true)
  syncSendCmd(params)
  // 发起订阅
  const subParams = {
    className: 'AddLiquidService',
    fnName: 'startStateReport',
    params: {},
  }
  syncSendCmd(subParams)
}

const onStopAddLiquid = () => {
  const params = {
    className: 'AddLiquidService',
    fnName: 'stop',
    params: {},
  }
  systemStore.updateLoading(true)
  syncSendCmd(params)
}

// 开始排液
const onStartDrainLiquid = async () => {
  const statusName = getDeviceStatus()
  if (statusName) {
    FtMessageBox.error(statusName)
    return
  }
  const params = {
    className: 'DrainLiquidService',
    fnName: 'start',
    params: {},
  }
  systemStore.updateLoading(true)
  await sendCmd(params)
  // 发起订阅
  const subParams = {
    className: 'DrainLiquidService',
    fnName: 'startStateReport',
    params: {},
  }
  syncSendCmd(subParams)
}

const onStopDrainLiquid = async () => {
  if (drainWorkState.value.workState === 'idle') {
    ElMessage.warning('正在加液中，不可进行排液操作')
    return
  }
  const params = {
    className: 'DrainLiquidService',
    fnName: 'stop',
    params: {},
  }
  systemStore.updateLoading(true)
  await syncSendCmd(params)
}
</script>

<template>
  <div v-loading="loading">
    <main class="main-content">
      <div class="liquid-left">
        <LiquidLevel />
      </div>
      <div class="liquid-right">
        <!-- 当前液位 -->
        <div class="liquid-surplus-title">
          <div>当前液位：</div>
          <div class="liquid-title-g">
            {{ nowLiquid }}g
          </div>
        </div>

        <!-- 输入加液/排液量 -->
        <div class="liquid-input">
          <el-input
            v-model="stopatg"
            v-prevent-keyboard
            class="input"
            name="nowLiquid"
            placeholder="请输入"
            style="height: 4rem"
            @focus="openKeyboard"
          >
            <template #append>
              <bt-button
                type="primary"
                :button-text="`${liquidTotoal}g`"
                bg-color="#2892F3"
                text-color="#ffffff"
                height="4rem"
                text-size="24px"
              />
            </template>
          </el-input>
        </div>

        <!-- 操作区 -->
        <div class="liquid-opt">
          <div>
            <div class="liquid-add-btn">
              <bt-button
                v-if="addWorkState.workState === 'idle'"
                button-text="开始加液"
                bg-color="#31CB7A"
                :text-color="btnStyle.textColor"
                :width="btnStyle.width"
                :height="btnStyle.height"
                :text-size="btnStyle.textSize"
                :border-radius="btnStyle.borderRadius"
                @click="onStartAddLiquid"
              >
                <template #icon>
                  <img :src="homeStart" alt="">
                </template>
              </bt-button>
              <bt-button
                v-else
                button-text="停止加液"
                bg-color="#FF6767"
                :text-color="btnStyle.textColor"
                :width="btnStyle.width"
                :height="btnStyle.height"
                :text-size="btnStyle.textSize"
                :border-radius="btnStyle.borderRadius"
                @click="onStopAddLiquid"
              >
                <template #icon>
                  <img :src="homeFinish" alt="">
                </template>
              </bt-button>
            </div>
            <div class="liquid-drain">
              <bt-button
                v-if="drainWorkState.workState === 'idle'"
                button-text="开始排液"
                bg-color="#2892F3"
                :text-color="btnStyle.textColor"
                :width="btnStyle.width"
                :height="btnStyle.height"
                :text-size="btnStyle.textSize"
                :border-radius="btnStyle.borderRadius"
                @click="onStartDrainLiquid"
              >
                <template #icon>
                  <img :src="homeStart" alt="">
                </template>
              </bt-button>
              <bt-button
                v-else
                button-text="停止排液"
                bg-color="#FF6767"
                :text-color="btnStyle.textColor"
                :width="btnStyle.width"
                :height="btnStyle.height"
                :text-size="btnStyle.textSize"
                :border-radius="btnStyle.borderRadius"
                @click="onStopDrainLiquid"
              >
                <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) => 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;
  overflow: hidden;
  .liquid-left{
    background: #FFFFFF;
    grid-column:  1 / 3;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0px 1px 5px 0px rgba(9, 39, 62, 0.15);
    background: $gradient-color;
  }
  .liquid-right{
    background:#FFFFFF;
    box-shadow: 0px 1px 5px 0px rgba(9, 39, 62, 0.15);
    padding-top: 15vh;
    width: 100%;
    background: $gradient-color;
    .liquid-surplus-title{
      height: 10vh;
      display: flex;
      padding-left: 2rem;
      align-items: center;
      font-size: 24px;
      font-weight: 400;

      .liquid-title-g{
        color: #2892F3;
        font-weight: bold;
      }
    }
    .liquid-input{
      display: flex;
      padding-left: 2rem;
      align-items: center;
      .input{
        width: 25vw;
      }
    }

    .liquid-opt{
      display: flex;
      justify-content: center;
      margin-top: 5vh;
    }
    .liquid-add-btn{
      width: 27vw;
      height: 8vh;
      border-radius: 12px;
      color: #FFFFFF;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      gap: 10px;
    }

    .liquid-drain{
      margin-top: 1.5rem;
    }
  }
}
</style>
