<script lang="ts" setup>
import { syncSendCmd } from 'apis/system'
import homeFinish from 'assets/images/home/home-finish.svg'
import homeSettingSvg from 'assets/images/home/home-setting.svg'
import Config from 'components/home/config.vue'
import HomeFormula from 'components/home/HomeFormula.vue'
import LineChart from 'components/home/LineChart.vue'
import { stopTimer } from 'libs/countdownTimer'
import { deviceStateMap } from 'libs/utils'
import { cloneDeep } from 'lodash'
import { computed, onMounted, onUnmounted, provide, ref, watchEffect } from 'vue'
import { useRouter } from 'vue-router'

import { useFormulaStore } from '@/stores/formulaStore'
import { useHomeStore } from '@/stores/homeStore'

const configRef = ref()
provide<(methods: Home.GrandsonMethods) => void>('registerGrandsonMethods', (methods) => {
  configRef.value = methods
})
const router = useRouter()
const formulaStore = useFormulaStore()
const homeStore = useHomeStore()
const formulaInfo = ref()
const disinfectionState = ref(homeStore.disinfectionState)
const curStateRemainTime = ref(homeStore.curStateRemainTime)
const disinfectFormulaVisible = ref(false)
const isDeviceIdle = ref(homeStore.isDeviceIdle)
const loading = ref(false)

watchEffect(() => {
  formulaInfo.value = formulaStore.currentSelectedFormulaInfo
  disinfectionState.value = homeStore.disinfectionState
  curStateRemainTime.value = homeStore.curStateRemainTime
  isDeviceIdle.value = homeStore.isDeviceIdle
})

const onDisinfectConfig = () => {
  disinfectFormulaVisible.value = true
}

// 结束消毒
const onFinishDisinfect = async () => {
  stopTimer()
  const stopParams = {
    className: 'DisinfectionCtrlServiceExt',
    fnName: 'stop',
    params: {
      loglevel: formulaStore.loglevel,
    },
  }
  loading.value = true
  syncSendCmd(stopParams).then((res) => {
    if (res.ackcode === 0) {
      loading.value = false
    }
  })
}

const onSave = () => {
  const formData = configRef.value?.getFormData()
  formulaStore.updateSelectedFormula(cloneDeep(formData))
  onClose()
}

const goHome = () => {
  router.push('/home')
}
const onClose = () => {
  disinfectFormulaVisible.value = false
}

const chartList = ref<any[]>([])
const operationState = computed(() => {
  return disinfectionState.value.state === 'idle' || disinfectionState.value.state === 'finished'
})

let poll = null

const getData = async (type?: string) => {
  const data = await syncSendCmd({
    className: 'H2O2SensorMgr',
    fnName: 'getH2O2SensorList',
  })

  const list = data.rely
  !type && (chartList.value = list.map(item => ({ ...item, data: [] })))
  for (let i = 0; i < list.length; i++) {
    const item: any = list[i]
    const res = await syncSendCmd({
      className: 'H2O2SensorMgr',
      fnName: 'getDisinfectionH2O2DataRecordList',
      params: {
        type: item.type,
        id: item.id,
        interval: 30,
      },
    })
    item.data = res.rely
  }
  chartList.value = list
  console.log(chartList.value)
}

const chartLoading = ref(false)
onMounted(async () => {
  chartLoading.value = true
  await getData()
  chartLoading.value = false
  poll = setInterval(() => {
    if (operationState.value) {
      clearInterval(poll)
      return
    }
    getData('interval')
  }, 1000 * 30)
})

onUnmounted(() => {
  clearInterval(poll)
})
</script>

<template>
  <main class="main-content">
    <div class="line-chart-title">
      <div v-if="formulaInfo && formulaInfo.name" class="line-chart-formula">
        <HomeFormula style="background: #e0f0ff" />
      </div>
      <div class="line-chart-set">
        <bt-button
          v-if="!isDeviceIdle"
          button-text="运行参数"
          text-size="24px"
          border-radius="5px"
          height="3.5rem"
          text-color="#1989fa"
          padding="0.8vw"
          @click="onDisinfectConfig"
        >
          <template #icon>
            <img :src="homeSettingSvg" width="15" alt="">
          </template>
        </bt-button>
      </div>
    </div>
    <div
      v-loading="chartLoading"
      class="line-chart-content"
      :style="{ 'grid-template-columns': `repeat(${chartList.length},1fr)` }"
    >
      <div v-for="(item, index) in chartList" :key="index">
        <LineChart :env-data="item" />
      </div>
    </div>
    <div class="line-chart-bottom">
      <div class="home-chart-time">
        <div v-if="!homeStore.isDeviceIdle" class="home-remain-time">
          <div class="home-chart-label">
            <span v-if="disinfectionState.state === 'disinfection'"> 预计剩余时间: </span>
            <span v-else> 消毒状态： </span>
          </div>
          <div v-if="curStateRemainTime" class="home-chart-value">
            {{ curStateRemainTime }}
          </div>
          <div v-else class="home-chart-value">
            {{ deviceStateMap[disinfectionState.state] }}
          </div>
        </div>
      </div>
      <div class="home-chart-btn">
        <bt-button
          v-if="!isDeviceIdle"
          button-text="结束消毒"
          bg-color="#FF6767"
          text-color="#FFFFFF"
          width="15vw"
          height="7vh"
          text-size="24px"
          border-radius="12px"
          @click="onFinishDisinfect"
        >
          <template #icon>
            <img :src="homeFinish" alt="">
          </template>
        </bt-button>
        <bt-button
          button-text="返回"
          width="10vw"
          height="7vh"
          text-color="#1989fa"
          text-size="24px"
          border-radius="12px"
          @click="goHome"
        />
      </div>
    </div>
    <ft-dialog v-model="disinfectFormulaVisible" title="运行参数" width="80vw" :ok-handle="onSave" @cancel="onClose">
      <div>
        <Config ref="configRef" />
      </div>
    </ft-dialog>
  </main>
</template>

<style lang="scss" scoped>
.main-content {
  overflow: hidden;
  background: $gradient-color;
  height: $main-container-height;
  .line-chart-formula {
    width: 40vw;
    //background: #E0F0FF;
    height: 3.5rem;
    display: flex;
    justify-content: center;
    align-items: center;
    //border: 1px solid #E0F0FF;
    border-radius: 10px;
    margin-left: 2rem;
  }
  .line-chart-set {
    display: flex;
    justify-content: end;
    align-items: center;
    width: 65vw;
    padding-right: 20px;
  }
  .line-chart-title {
    height: 15%;
    display: flex;
    align-items: center;
  }
  .line-chart-content {
    display: grid;
    height: 65%;
  }
  .line-chart-bottom {
    height: 15%;
    display: flex;
    padding-right: 20px;
    .home-chart-btn {
      display: flex;
      justify-content: end;
      width: 65%;
    }
    .home-chart-time {
      width: 35%;
      .home-remain-time {
        background: #f6fafe;
        width: 27vw;
        height: 8vh;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        gap: 10px;
        margin-left: 1rem;
        .home-chart-value {
          color: #2892f3;
        }
      }
    }
  }
}
</style>
