<template>
  <BasicModal
    :maskClosable="false"
    width="800px"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :destroyOnClose="true"
  >
    <div style="height: 60vh">
      <a-spin :spinning="spinning">
        <BasicForm @register="registerForm">
          <template #title>
            <div class="text-center text-black text-lg"> 基本信息 </div>
          </template>
          <template #titleT>
            <div class="text-center text-black text-lg"> 描述信息 </div>
          </template>
          <template #iconSelect>
            <Upload
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :customRequest="customUpload"
              :before-upload="beforeUpload"
            >
              <img
                v-if="tenantLogo"
                fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0dHRJFarQ0eUT8LH4BnRU0NHR0UEFVdIlFRV7TzRksomPY8uykTk/zewQfKw/9znv4yvJynLv4uLiV2dBoDiBf4qP3/ARuCRABEFAoBEgghggQ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hJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg=="
                :src="tenantLogo"
                alt="avatar"
              />
              <div v-else>
                <LoadingOutlined v-if="loading" />
                <plus-outlined v-else />
                <div class="ant-upload-text">选择图片</div>
              </div>
            </Upload>
          </template>
        </BasicForm>
      </a-spin>
    </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 './account.data';
  import { filterRoleList } from '/@/api/system/system';
  import { addDzsbsjjr, getDzsbsjjr } from '/@/api/datamanager/groundDisasterId/muSourceData';
  import { LoadingOutlined } from '@ant-design/icons-vue';
  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 { useUserStore } from '/@/store/modules/user';
  import { useGlobSetting } from '/@/hooks/setting';
  export default defineComponent({
    name: 'AccountModal',
    components: {
      BasicModal,
      BasicForm,
      Upload,
      PlusOutlined,
      LoadingOutlined,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const tenantLogo = ref('');
      const loading = ref(false);
      const fileR: any = ref();
      const roleOptions = ref<TOption[]>([]);
      const isUpdate = ref(true);
      const spinning = ref<boolean>(false);
      const postData = reactive({});
      const userStore = useUserStore();
      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: 110,
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 18,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        tenantLogo.value = '';
        await resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          try {
            spinning.value = true;
            const fromData = await getDzsbsjjr(data.record.id);
            setFieldsValue(fromData.result);
            console.log('123', useGlobSetting());
            const { apiUrl } = useGlobSetting();
            console.log('123', apiUrl);
            const url = apiUrl.slice(0, -4);
            console.log('123', url);
            if (fromData.result.fileList.length > 0) {
              tenantLogo.value = `${url}/yxBase/file/download?id=${fromData.result.fileList[0].id}`;
              spinning.value = false;
            } else {
              spinning.value = false;
            }
          } catch (error) {
            spinning.value = false;
          }
        }
      });
      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        setModalProps({ confirmLoading: true });
        try {
          const { createMessage } = useMessage();

          const values = await validate([
            'id',
            'fbdz',
            'zymc',
            'note',
            'jclx',
            'sjlx',
            'sjjd',
            'sjms',
            'sshdid',
            'ssgcid',
            'ssdzdid',
            'sjsj',
            'fileList',
          ]);
          console.log('values1', values);

          if (!unref(isUpdate)) {
            values.createdBy = userStore.getUserInfo?.userId;
          }
          console.log('values2', values);

          Object.assign(postData, values, { bq: '0' });
          const data = paramsToFormData(postData as any);
          console.log('values3', data);

          if (fileR.value) {
            data.append('file', fileR.value);
          }

          const res = await addDzsbsjjr(data, unref(isUpdate));
          console.log(res);

          if (res.code === 1) {
            closeModal();
            emit('success');
            createMessage.success(unref(isUpdate) ? '编辑成功' : '新增成功');
            tenantLogo.value = '';
          } else {
            createMessage.success(res.message);
          }
        } finally {
          setTimeout(() => {
            setModalProps({ confirmLoading: false });
          }, 300);
        }
      }
      async function customUpload({ file }) {
        if (beforeUpload(file)) {
          console.log('file', file);
          tenantLogo.value = '';
          loading.value = true;
          fileR.value = file;
          console.log('tenantLogo.value ', fileR);
          tenantLogo.value = URL.createObjectURL(file);
          return 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) {
        console.log('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) {
        console.log('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 {
        registerModal,
        registerForm,
        handleSubmit,
        getTitle,
        roleOptions,
        customUpload,
        beforeUpload,
        tenantLogo,
        loading,
        spinning,
      };
    },
  });
</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>
