<template>
  <BasicModal
    width="800px"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :useWrapper="true"
    :minHeight="500"
  >
    <div style="height: 50vh">
      <BasicForm @register="registerForm">
        <template #title>
          <div class="text-center text-black text-2xl">
            <!-- <a-typography-title style="font-size: 16px;">流域基础信息</a-typography-title> -->
            <a-menu v-model:selectedKeys="current" mode="horizontal">
              <a-menu-item key="mail1"> 基础信息 </a-menu-item>
              <a-menu-item key="mail2"> 版本信息 </a-menu-item>
            </a-menu>
          </div>
        </template>
        <template #upload>
          <a-upload name="file" :multiple="true">
            <a-button type="primary">
              <upload-outlined></upload-outlined>
              选择文件
            </a-button>
            <span style="font-size: 14px; margin-left: 10px"
              >支持上传png、jpeg、gif、tif、doc、xls、pdf等格式文件</span
            >
          </a-upload>
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, reactive, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  // import { accountFormSchema } from './fileUploadData';
  import { filterRoleList } from '/@/api/system/system';
  // import { addDzsbsjjr } from '/@/api/datamanager/groundDisasterId/muSourceData';

  import { message, Upload } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  // import { FileItem } from '/@/components/Upload/src/typing';
  import { TOption } from '/@/views/rule/linkedge/config/config.data';
  import { PlusOutlined } from '@ant-design/icons-vue';
  // import { upload } from '/@/api/oss/ossFileUploader';
  import { addFileResource } from '../../api/fileUploadApi';
  export default defineComponent({
    name: 'AccountModal',
    components: {
      BasicModal,
      BasicForm,
      Upload,
      PlusOutlined,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const current = ref(['mail1']);
      const tenantLogo = ref('');
      const loading = ref(false);
      const roleOptions = ref<TOption[]>([]);
      const isUpdate = ref(true);
      const rowId = ref('');
      const postData = reactive({});

      const getRoleList = async () => {
        const res = await filterRoleList();
        console.log(res);
        roleOptions.value = res.map((m) => {
          return {
            label: m.name,
            value: m.id,
          };
        });
      };
      onMounted(async () => {
        await getRoleList();
      });

      const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
        labelWidth: 100,
        // schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 18,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        await resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          rowId.value = data.record.id;
          setFieldsValue(data.record);
        }
      });
      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        setModalProps({ confirmLoading: true });
        try {
          const { createMessage } = useMessage();
          const values = await validate(['parentId']);
          Object.assign(postData, values);

          console.log('准备传递的参数' + JSON.stringify(postData));

          await addFileResource(paramsToFormData(postData as any), unref(isUpdate));
          closeModal();
          emit('success');
          createMessage.success(unref(isUpdate) ? '编辑成功' : '新增成功');
        } finally {
          setTimeout(() => {
            setModalProps({ confirmLoading: false });
          }, 300);
        }
      }
      // async function customUpload({ file }) {
      //   if (beforeUpload(file)) {
      //     tenantLogo.value = '';
      //     loading.value = true;
      //     const formData = new FormData();
      //     formData.append('file', file);
      //     const response = await upload(formData);
      //     if (response.fileStaticUri) {
      //       tenantLogo.value = response.fileStaticUri;
      //       loading.value = false;
      //     }
      //   }
      // }
      // const beforeUpload = (file: FileItem) => {
      //   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;
      // };
      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 {
        current,
        registerModal,
        registerForm,
        handleSubmit,
        getTitle,
        roleOptions,
        // customUpload,
        // beforeUpload,
        tenantLogo,
        loading,
      };
    },
  });
</script>
<style scoped lang="less">
  :deep(.vben-basic-tree) {
    width: 100% !important;
  }

  :deep(.is-unflod) {
    display: none !important;
  }

  :deep(.is-flod) {
    display: none !important;
  }
</style>
