<template>
    <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      destroyOnClose
      :title="title"
      :centered="true"
      width="60%"
      @ok="handleSubmit"
    >
      <BasicForm @register="registerForm" style="margin: 0px">
        <template #tolVal="{ model, field }">
          <ThresholdInputGroup
            :model="model"
            :field="field"
            type="low"
            :disabled="isDisabledLow"
            :checked="checkedLow"
            :metric-set-val="metricSetVal"
            @change="handleChangeLow"
          />
        </template>
        <template #warnVal="{ model, field }">
          <ThresholdInputGroup
            :model="model"
            :field="field"
            type="middle"
            :disabled="isDisabledMiddle"
            :checked="checkedMiddle"
            :metric-set-val="metricSetVal"
            @change="handleChangeMiddle"
          />
        </template>
        <template #intvVal="{ model, field }">
          <ThresholdInputGroup
            :model="model"
            :field="field"
            type="high"
            :disabled="isDisabledHight"
            :checked="checkedHight"
            :metric-set-val="metricSetVal"
            @change="handleChangeHight"
          />
        </template>
      </BasicForm>
    </BasicModal>
  </template>
  
  <script lang="ts" setup>
  import { ref, computed, unref, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../MetricMonitorSet.data';
  import { saveOrUpdate } from '../MetricMonitorSet.api';
  import ThresholdInputGroup from './ThresholdInputGroup.vue';
  
  const emit = defineEmits(['register', 'success']);
  const mtrcCtp = ref();
  const isUpdate = ref(true);
  
  // 使用响应式对象管理状态
  const state = reactive({
    isDisabledLow: true,
    isDisabledMiddle: true,
    isDisabledHight: true,
    checkedLow: false,
    checkedMiddle: false,
    checkedHight: false
  });
  
  const metricSetVal = ref();
  
  // 表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate,removeSchemaByFiled }] = useForm({
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 }
  });
  
  // 表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {

    clearState();
    
    // 确保移除字段时不会出错
    try {
      await removeSchemaByFiled("formulas");
      await removeSchemaByFiled("params");
    } catch (error) {
      console.warn('移除字段时出错:', error);
    }
  
    mtrcCtp.value = data.mtrcCtp;
    metricSetVal.value = data.record;
    
    await resetFields();
    setModalProps({
      confirmLoading: false,
      showCancelBtn: !!data?.showFooter,
      showOkBtn: !!data?.showFooter
    });
    
    isUpdate.value = !!data?.isUpdate;
    
    if (unref(isUpdate)) {
      await setFieldsValue({
        ...data.record,
      });
      
      // 根据数据设置状态
      if (data.record.noticeReceiveMiddle) {
        state.isDisabledMiddle = false;
        state.checkedMiddle = true;
      }
      if (data.record.noticeReceiveHight) {
        state.isDisabledHight = false;
        state.checkedHight = true;
      }
      if (data.record.noticeReceiveLow) {
        state.isDisabledLow = false;
        state.checkedLow = true;
      }
    } else {
      await setFieldsValue({
        mtrcCtp: data.mtrcCtp
      });
    }
  
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter });
  });
  
  // 设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增风险指标' : '编辑风险指标'));
  
  // 表单提交事件
  async function handleSubmit() {
    try {
      const values = await validate();
      values.mtrcCtp = mtrcCtp.value;
      
      setModalProps({ confirmLoading: true });
      await saveOrUpdate(values);
      closeModal();
      emit('success');
    } catch (error) {
      console.error('表单提交错误:', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  
  function handleChangeLow() {
 
    state.checkedLow = !state.checkedLow;
    state.isDisabledLow = !state.checkedLow;
    
    setFieldsValue({
      noticeReceiveLow: state.checkedLow ? metricSetVal.value?.noticeReceiveLow || '' : ''
    });
  }
  
  function handleChangeMiddle() {
    state.checkedMiddle = !state.checkedMiddle;
    state.isDisabledMiddle = !state.checkedMiddle;
    
    setFieldsValue({
      noticeReceiveMiddle: state.checkedMiddle ? metricSetVal.value?.noticeReceiveMiddle || '' : ''
    });
  }
  
  function handleChangeHight() {
    state.checkedHight = !state.checkedHight;
    state.isDisabledHight = !state.checkedHight;
    
    setFieldsValue({
      noticeReceiveHight: state.checkedHight ? metricSetVal.value?.noticeReceiveHight || '' : ''
    });
  }


  function clearState() {
    state.isDisabledLow = true;
    state.isDisabledMiddle = true;
    state.isDisabledHight = true;
    state.checkedLow = false;
    state.checkedMiddle = false;
    state.checkedHight = false;
  }
  
  const {
    isDisabledLow,
    isDisabledMiddle,
    isDisabledHight,
    checkedLow,
    checkedMiddle,
    checkedHight
  } = state;
  

  </script>
  
  <style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }
  
  :deep(.ant-calendar-picker) {
    width: 100%;
  }
  </style>