<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    wrapClassName="custom-modal-box"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { addUnitType, updateUnitType, getUnitTypeInfo } from '/@/api/erp/unit/type';

  const { t } = useI18n();
  const FormSchema: FormSchema[] = [
    {
      field: 'name',
      label: '单位类型',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入单位类型',
      },
    },
    {
      field: 'state',
      label: '状态',
      component: 'Switch',
      colProps: { span: 24 },
    },
    {
      field: 'remark',
      label: '备注',
      component: 'InputTextArea',
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入备注',
      },
    },
  ];

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');

  const emit = defineEmits(['success']);

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: FormSchema,
    layout: 'vertical',
    rowProps: { gutter: 32 },
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });

    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      rowId.value = data.id;
      const record = await getUnitTypeInfo(data.id);
      setFieldsValue({
        ...record,
      });
    } else {
      setFieldsValue({
        state: 1,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增单位类型' : '编辑单位类型'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });

      if (!unref(isUpdate)) {
        await addUnitType(values);
        notification.success({
          message: '新增单位类型',
          description: t('成功'),
        });
      } else {
        values.id = rowId.value;
        await updateUnitType(values);
        notification.success({
          message: '编辑单位类型',
          description: t('成功'),
        });
      }

      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
