<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  // import { useI18n } from 'vue-i18n';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { addIotGroup, updateIotGroup } from '/@/api/iot';
  const { t } = useI18n();
  const formSchema: FormSchema[] = [
    {
      field: 'name',
      label: t('分组名'),
      required: true,
      component: 'Input',
      colProps: { span: 24, style: { paddingTop: '16px' } },
    },
    {
      field: 'sortCode',
      label: t('排序'),
      component: 'InputNumber',
      colProps: { span: 24 },
    },
  ];

  const emit = defineEmits(['success']);
  const isUpdate = ref(true);
  const { notification } = useMessage();
  const rowId = ref('');

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    schemas: formSchema,
    showActionButtonGroup: false,
    layout: 'vertical',
    rowProps: {
      gutter: 32,
    },
  });

  const [registerDrawer, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? t('新增分组') : t('编辑分组')));

  async function handleSubmit() {
    try {
      const values = await validate();

      setModalProps({ confirmLoading: true });
      // TODO custom api
      if (!unref(isUpdate)) {
        //false 新增
        await addIotGroup(values);
        notification.success({
          message: t('提示'),
          description: t('新增分组成功'),
        }); //提示消息
      } else {
        values.id = rowId.value;
        await updateIotGroup(values);
        notification.success({
          message: t('提示'),
          description: t('编辑分组成功'),
        }); //提示消息
      }
      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
