<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 {
    getCategoryListInfo,
    updateCategoryList,
    addCategoryList,
  } from '/@/api/erp/material/category';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  const FormSchema: FormSchema[] = [
    {
      field: 'typeName',
      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,
    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 getCategoryListInfo(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 addCategoryList(values);
        notification.success({
          message: '新增物料类别',
          description: t('成功'),
        });
      } else {
        values.id = rowId.value;
        await updateCategoryList(values);
        notification.success({
          message: '编辑物料类别',
          description: t('成功'),
        });
      }

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