<!--
 * @Author: renxin renxin0828@163.com
 * @Date: 2023-06-05 10:03:16
 * @LastEditors: renxin renxin0828@163.com
 * @LastEditTime: 2023-06-08 19:34:24
 * @FilePath: \yx-admin\src\views\system\dict\DictDrawer.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './dict.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

  import { saveOrEditDict } from '/@/api/system/dict';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'DictDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      let id;
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        await resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          id = data.record.id;
          await setFieldsValue({
            ...data.record,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增字典配置' : '编辑字典配置'));

      async function handleSubmit() {
        // unref(fileList).map((e) => {
        //   console.log('fileList.value', e.originFileObj);
        // });

        setDrawerProps({ confirmLoading: true });
        try {
          const values = await validate();
          const { createMessage } = useMessage();
          let successMessage = '添加成功';
          //如果是修改需要传入id
          if (unref(isUpdate)) {
            successMessage = '修改成功';
            Reflect.set(values, 'id', id);
          }

          const data = paramsToFormData(values);

          // unref(fileList.list).map((e: any) => {
          //   data.append('file', e.originFileObj);
          // });

          await saveOrEditDict(data, unref(isUpdate)).then(() => {
            closeDrawer();
            emit('success');
            createMessage.success(successMessage);
          });
        } finally {
          setTimeout(() => {
            setDrawerProps({ confirmLoading: false });
          }, 300);
        }
      }

      function preProcessData(data) {
        Object.keys(data).forEach((item) => {
          if (typeof data[item] === 'undefined' || data[item] === null || data[item] === '') {
            delete data[item];
          }
        });
        return data;
      }
      function paramsToFormData(obj) {
        const data = preProcessData(obj);
        const formData = new FormData();
        Object.keys(data).forEach((key) => {
          if (data[key] instanceof Array) {
            data[key].forEach((item) => {
              formData.append(key, item);
            });
            return;
          }
          formData.append(key, obj[key]);
        });
        return formData;
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>

