<template>
  <div :class="[prefixCls, { fullscreen }]">
    <!-- @change="handleChange" :action="uploadUrl" -->
    <Upload
      name="file"
      multiple
      :beforeUpload="handleBeforeUpload"
      :customRequest="selfUpload"
      :showUploadList="false"
      accept=".jpg,.jpeg,.gif,.png,.webp"
      :headers="{ 'X-Authorization': 'Bearer' + ' ' + token }"
    >
      <a-button type="primary" v-bind="{ ...getButtonProps }">
        {{ t('component.upload.imgUpload') }}
      </a-button>
    </Upload>
  </div>
</template>
<script lang="ts">
  import { defineComponent, computed, ref, unref } from 'vue';
  import { UploadJianbao } from '/@/api/swHome/index';
  import { message, Upload } from 'ant-design-vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useGlobSetting } from '/@/hooks/setting';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { JWT_TOKEN_KEY } from '/@/enums/cacheEnum';
  import { getAuthCache } from '/@/utils/auth';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getAppEnvConfig } from '/@/utils/env';
  const { VITE_GLOB_BASE_IMG } = getAppEnvConfig();
  export default defineComponent({
    name: 'TinymceImageUpload',
    components: { Upload },
    props: {
      fullscreen: {
        type: Boolean,
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      parameters: {
        type:Object,
        default: false,
      }
    },
    emits: ['uploading', 'done', 'error'],
    setup(props, { emit }) {
      const { createMessage } = useMessage();
      let uploading = false;
      const token: string = getAuthCache(JWT_TOKEN_KEY);
      const { uploadUrl } = useGlobSetting();
      const { t } = useI18n();
      const { prefixCls } = useDesign('tinymce-img-upload');
      const loading = ref(false);

      const getButtonProps = computed(() => {
        const { disabled } = props;
        return {
          loading: unref(loading),
          disabled,
        };
      });
      const selfUpload = async (data) => {
        console.log(data)
        const { parameters } = props;
        let files = new FormData();
        files.append('file', data.file);
        files.append('type', parameters.type);
        files.append('name', data.file.name.split('.')[0]);
        emit('uploading', data.file.name.split('.')[0]);
          loading.value = true;
          uploading = true;
        let img = await UploadJianbao(files).then((res) => {
          return res;
        });
        if (img.code == 200) {
          emit('done', data.file.name.split('.')[0], VITE_GLOB_BASE_IMG+img.data[0]);
          loading.value = false;
          uploading = false;
        } else {
          emit('error');
          loading.value = false;
          uploading = false;
        }
      };
      function handleChange(info: Recordable) {
        const file = info.file;
        const status = file?.status;
        const url = file?.response?.fileStaticUri;
        const name = file?.name;

        if (status === 'uploading') {
          if (!uploading) {
            emit('uploading', name);
            loading.value = true;
            uploading = true;
          }
        } else if (status === 'done') {
          emit('done', name, url);
          loading.value = false;
          uploading = false;
        } else if (status === 'error') {
          createMessage.error('图片上传失败');
          emit('error');
          loading.value = false;
          uploading = false;
        }
      }

      function handleBeforeUpload(file: File) {
        if (file.size > 5 * 1024 * 1024) {
          message.error('上传图片的大小不能超过5MB!');
          return false;
        }
        return true;
      }

      return {
        prefixCls,
        handleChange,
        uploadUrl,
        t,
        getButtonProps,
        token,
        handleBeforeUpload,
        selfUpload
      };
    },
  });
</script>
<style lang="less" scoped>
  @prefix-cls: ~'@{namespace}-tinymce-img-upload';

  .@{prefix-cls} {
    position: absolute;
    top: 4px;
    right: 10px;
    z-index: 20;

    &.fullscreen {
      position: fixed;
      z-index: 10000;
    }
  }
</style>
