<script lang="ts" setup>
import { syncSendCmd } from 'apis/system'
import { FtMessageBox } from 'libs/messageBox'
import { useDeviceStore } from 'stores/deviceStore'
import { useSealStore } from 'stores/sealStore'
import { computed, onMounted, ref } from 'vue'

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

const selected = ref<string[]>([])
// 级联数据：[{ label, value, children: [{ label, value }] }]
const cascaderOptions = ref<{ label: string, value: string, children: { label: string, value: string }[] }[]>([])

const homeStore = useHomeStore()
const deviceStore = useDeviceStore()

// 拉取配置并构建 cascaderOptions
const getPressureConfig = async () => {
  if (__DEVICE_TYPE__ !== useDeviceStore().deviceTypeMap.LargeSpaceDM_B) {
    const res = await syncSendCmd({ className: 'PipelinePressureControl', fnName: 'getConfig' })
    if (res.ackcode === 0) {
      homeStore.updatePressureConfig(res.rely)
      const { typeDisplayNames, types, intensitys } = res.rely
      cascaderOptions.value = typeDisplayNames.map((name: string, idx: number) => {
        const children = (intensitys[types[idx]] || []).map((val: string) => ({ label: `${val}%`, value: val }))
        return { label: name, value: types[idx], children }
      })

      // 初始化当前状态
      const stateRes = await syncSendCmd({ className: 'PipelinePressureControl', fnName: 'getState' })
      if (stateRes.ackcode === 0) {
        const { type, intensity } = stateRes.rely
        selected.value = intensity ? [type, intensity] : [type]
      }
    }
  }
}

onMounted(getPressureConfig)

const deviceType = computed(() => {
  return __DEVICE_TYPE__
})
const sealStore = useSealStore()
const sealInfo = computed(() => sealStore.sealInfo)
// 用户选择后立即更新压力配置（支持仅选择类型的情况）
const confirm = async (val: string[]) => {
  // 判断设备当前的状态
  if (sealInfo.value.workState === 'stopping' || sealInfo.value.workState === 'idle') {
    if (!val || !val.length)
      return
    await homeStore.updatePressure(val)
  }
  else {
    FtMessageBox.error('密封性测试中,禁止修改正负压')
  }
}
</script>

<template>
  <div v-if="deviceType === deviceStore.deviceTypeMap.PipeDM" class="pressure-wrapper">
    <el-cascader
      v-model="selected"
      :options="cascaderOptions"
      placeholder="请选择"
      class="pressure-cascader"
      input-props="{ style: 'text-align: center;' }"
      popper-class="pressure-cascader-popper"
      @change="confirm"
    />
  </div>
</template>

<style scoped>
.pressure-wrapper {
  display: flex;
  justify-content: center;
  padding: 0.5rem 0;
}

.pressure-cascader {
  width: 100%;
  max-width: 7.5rem;
}
</style>

<!-- 全局样式，作用于弹出面板 -->
<style>
.pressure-cascader-popper .el-cascader-menu__item {
  text-align: center;
}
</style>
