<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
    :destroyOnClose="true"
  >
    <BasicForm @register="registerForm">
      <template #upload>
        <Upload
          accept="image/jpeg,image/png"
          list-type="picture"
          v-model:fileList="fileList.list"
          class="upload-list-inline"
          :customRequest="customUpload"
          :before-upload="beforeUpload"
          :remove="remove"
          @change="onChange"
        >
          <a-button type="primary">
            <upload-outlined />
            图片上传
          </a-button>
        </Upload>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, reactive } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from './dict.item.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import { saveOrEditDictItem } from '/@/api/system/dict';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { message, Upload } from 'ant-design-vue';
  import { uploadDelete } from '/@/api/oss/ossFileUploader';
  import { useGlobSetting } from '/@/hooks/setting';
  export default defineComponent({
    name: 'ItemDrawer',
    components: { BasicDrawer, BasicForm, Upload, UploadOutlined },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const fileList = reactive({
        list: [],
      });
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      let dictId, id;
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        await resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        dictId = data.dictId;
        fileList.list = [];
        if (unref(isUpdate)) {
          id = data.record.id;
          await setFieldsValue({
            ...data.record,
          });
          const { apiUrl } = useGlobSetting();
          const url = apiUrl.slice(0, -4);

          if (data.record.fileList.length > 0) {
            fileList.list = data.record.fileList.map((e) => {
              return {
                id: e.id,
                uid: e.id - 100000,
                name: e.fileName,
                status: 'done',
                url: `${url}/yxBase/file/download?id=${e.id}`,
                thumbUrl: `${url}/yxBase/file/download?id=${e.id}`,
              };
            });
          }
        }
      });

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

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

          const data = paramsToFormData(values);

          unref(fileList.list).map((e: any) => {
            if (e.originFileObj) {
              data.append('file', e.originFileObj);
            }
          });
          await saveOrEditDictItem(data, unref(isUpdate));
          closeDrawer();
          emit('success');
          createMessage.success(message);
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      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;
      }
      async function customUpload(info: any) {
        const { file } = info;

        // if (beforeUpload(file)) {
        //   const formData = new FormData();
        //   formData.append('file', file);
        //   const response: any = await uploadT(formData);
        //   console.log('response', response);
        //   if (response.code === 1) {
        //     fileList.value.push(response.result[0]);
        //   }
        // }

        if (beforeUpload(file)) {
          info.onSuccess('', file);
          info.onProgress({ percent: 1 }, file);
          // fileList.value.push(URL.createObjectURL(file));
          // return false;
        }
      }
      const beforeUpload = (file: any) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        // if (!isJpgOrPng) {
        //   message.error('只能上传图片文件!');
        // }
        const isLt2M = (file.size as number) / 1024 / 1024 > 5;
        // if (!isLt2M) {
        //   message.error('图片大小不能超过5MB!');
        // }
        return isJpgOrPng && isLt2M;
      };
      const onChange = (info: any) => {
        console.log('onChange', info);

        fileList.list = info.fileList;

        const { file } = info;
        if (file.status === 'uploading') {
          return {};
        }
        if (file.status === 'removed') {
          return {};
        }
        if (file.status === 'error') {
          message.error('文件上传失败');
        }
        if (file.status === 'done') {
          console.log('done');
        }
      };

      const remove = (file: any) => {
        if (file.id) {
          uploadDelete(file.id).then((res: any) => {
            emit('success');
            if (res.code === 1) {
              return true;
            } else {
              return false;
            }
          });
        }
      };
      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        customUpload,
        beforeUpload,
        remove,
        onChange,
        fileList,
      };
    },
  });
</script>
<style scoped lang="less">
  :deep(.ant-progress-outer) {
    display: none;
  }
</style>
