<script setup lang="ts">
import { useHomeStore } from 'stores/homeStore'
import { ref } from 'vue'

const emits = defineEmits(['ok', 'cancel'])

const homeStore = useHomeStore()

const selectedHeatArea = computed(() => {
  return homeStore.heatAreaList.find(item => item.selected)
})

const form = ref<{
  minutes?: number
  seconds?: number
  time?: number
  temperature?: number
}>({})
const formRef = ref()

const validateHandle = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入目标温度'))
  }
  else if (value < 0 || value > 300) {
    callback(new Error('目标温度范围0℃-300℃'))
  }
  else {
    callback()
  }
}

const rules = {
  temperature: [
    { required: true, trigger: 'blur', validator: validateHandle },
  ],
  time: [
    { required: true, trigger: 'change', message: '请选择时间' },
  ],
}

let currentCommandId = ''
const okHandle = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) {
      return
    }
    currentCommandId = Date.now().toString()
    const params = {
      commandId: currentCommandId,
      command: 'heat_start',
      params: {
        heatId: selectedHeatArea.value?.value,
        ...form.value,
      },
    }
    await homeStore.sendControl(params)
    emits('ok')
  }
  catch (error) {
    console.log(error)
  }
}
const cancel = () => {
  emits('cancel')
}

const convertTime = () => {
  form.value.time = (form.value.minutes || 0) * 60 + (form.value.seconds || 0)
  formRef.value.validateField('time')
}
</script>

<template>
  <FtDialog visible title="开始加热" width="40%" :ok-handle="okHandle" @cancel="cancel">
    <el-form ref="formRef" label-width="auto" :model="form" :rules="rules">
      <el-form-item label="加热区">
        <el-tag>{{ selectedHeatArea?.label }}</el-tag>
      </el-form-item>
      <el-form-item label="目标温度" prop="temperature">
        <el-input v-model="form.temperature" type="number" placeholder="请输入温度">
          <template #append>
            ℃
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="保持时间" prop="time">
        <div style="display: flex;width: 100%">
          <el-select v-model="form.minutes" clearable style="width: 100%" placeholder="请选择分钟" @change="convertTime">
            <el-option v-for="item in 60" :key="item" :label="item" :value="item" />
          </el-select>
          <span style="margin: 0 5px">分</span>
          <el-select v-model="form.seconds" clearable style="width: 100%" placeholder="请输入秒" @change="convertTime">
            <el-option v-for="item in 60" :key="item" :label="item" :value="item" />
          </el-select>
          <span style="margin: 0 5px">秒</span>
        </div>
      </el-form-item>
    </el-form>
  </FtDialog>
</template>

<style scoped lang="scss">
.el-tag {
  margin-right: 5px;
}
</style>
