<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';

import { DeviceType } from '@/views/device-work-status/device-card';
import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import { addAlgorithmConfigUpdate, getAIOptimizeDetail } from '@/api';

import type { FormInstance } from 'ant-design-vue';
import type { AIOptimizeSetItemExpose, FormRules } from '@/types';

interface Props {
  groupId: number;
}

const props = defineProps<Props>();

interface CoolingTowerForm {
  coolingPipeDynamicUpper?: number;
  coolingPipeDynamicLower?: number;
}

const coolingTowerForm = reactive<CoolingTowerForm>({
  coolingPipeDynamicUpper: undefined,
  coolingPipeDynamicLower: undefined,
});

const rules = computed<FormRules<CoolingTowerForm>>(() => {
  return {
    coolingPipeDynamicUpper: [
      {
        required: true,
        message: t('common.plzEnter', { name: t('realTimeMonitor.towerOutWaterTempUpperLimit') }),
        trigger: 'blur',
      },
    ],
    coolingPipeDynamicLower: [
      {
        required: true,
        message: t('common.plzEnter', { name: t('realTimeMonitor.towerOutWaterTempLowerLimit') }),
        trigger: 'blur',
      },
    ],
  };
});

const { handleRequest } = useRequest();

onMounted(() => {
  handleRequest(async () => {
    const { algorithmConfig } = await getAIOptimizeDetail(props.groupId, DeviceType.冷却泵);
    algorithmId = algorithmConfig.id;
    coolingTowerForm.coolingPipeDynamicUpper = algorithmConfig.coolingPipeDynamicUpper;
    coolingTowerForm.coolingPipeDynamicLower = algorithmConfig.coolingPipeDynamicLower;
  });
});

let algorithmId: number | undefined;
const formRef = ref<FormInstance>();

const submit = async () => {
  await formRef.value?.validate();

  await addAlgorithmConfigUpdate({
    id: algorithmId,
    ...coolingTowerForm,
  });
};

defineExpose<AIOptimizeSetItemExpose>({
  submit,
});
</script>

<template>
  <AForm ref="formRef" :model="coolingTowerForm" :rules="rules" layout="vertical">
    <AFormItem :label="t('realTimeMonitor.towerOutWaterTempUpperLimit')" name="coolingPipeDynamicUpper">
      <AInputNumber
        class="hvac-input-number tower-temp-input"
        v-model:value="coolingTowerForm.coolingPipeDynamicUpper"
        :min="0"
        :max="50"
        addon-after="℃"
      />
    </AFormItem>
    <AFormItem :label="t('realTimeMonitor.towerOutWaterTempLowerLimit')" name="coolingPipeDynamicLower">
      <AInputNumber
        class="hvac-input-number tower-temp-input"
        v-model:value="coolingTowerForm.coolingPipeDynamicLower"
        :min="0"
        :max="50"
        addon-after="℃"
      />
    </AFormItem>
  </AForm>
</template>

<style lang="scss" scoped>
.tower-temp-input {
  width: 100%;
}
</style>
