import { defineComponent, reactive, ref, watch } from 'vue';
import './index.less';
import UploadTip from '@/assets/svg/upload/uploadTip2.svg';
import {
  MessagePlugin,
  Button as TButton,
  Upload as TUpload,
  Progress as TProgress,
  UploadFile,
  RequestMethodResponse,
} from 'tdesign-vue-next';
import { getUserCookie } from '@/utils/api/userApi';
import request from '@/utils/otherRequest';
import { show_message } from '@/utils/tdesign_tool';
import { v4 } from 'uuid';
export default defineComponent({
  props: {
    modelValue: String,
    config: Object as any,
    num: Number,
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const files = ref([]);
    // 文件地址
    const Curfile = reactive({
      url: '',
      status: 0,
      // 当前上传模块提交的状态
      uploadStatus: false,
    });
    const actionUrl = ref('');
    // 上传进度条
    const percentage = ref(0);
    // 定时器
    let percentageInterval: any = null;
    // 上传进度定时器
    const openpercentage = () => {
      // 开启一个定时器，模拟上传进度
      percentage.value = 0;
      percentageInterval = setInterval(() => {
        if (percentage.value == 99) {
          return;
        }
        percentage.value += 1;
      }, 100);
    };
    const beforeUpload = (file: File) => {
      try {
        const { config } = props;
        const config_len = Object.keys(config).length;
        if (!config_len) {
          show_message('无法上传,请尝试刷新页面');
          return false;
        }
        return true;
      } catch (e) {
        console.log(e);
        return false;
      }
    };
    const handleFail = ({ file }: any) => {
      MessagePlugin.error(`文件 ${file.name} 上传失败`);
    };
    // 上传成功回调
    const UploadSuccessCallback = (uuid: any, url: any) => {
      // 关闭定时器
      window.clearInterval(percentageInterval);
      MessagePlugin.success('上传成功');
      // 将将完整url传给父组件
      Curfile.url = url;
      // 成功2
      Curfile.status = 2;
      emit('update:modelValue', Curfile.url);
    };
    // 上传失败回调
    const UploadErrorCallback = () => {
      // 关闭定时器
      window.clearInterval(percentageInterval);
      Curfile.url = '';
      // 失败0
      Curfile.status = 0;
      emit('update:modelValue', Curfile.url);
      MessagePlugin.warning('上传失败');
    };
    // 外网上传-func
    const ExtranetUpload = (file: any) => {
      openpercentage();
      return new Promise<RequestMethodResponse>((resolve) => {
        const uuid = v4();
        // 上传中状态
        Curfile.status = 1;
        let url = '';
        const { config } = props;
        url = 'https://' + config.host;
        setTimeout(() => {
          const formData = new FormData();
          formData.append('key', config.dir + uuid + '.png');
          formData.append('policy', config.policy);
          formData.append('OSSAccessKeyId', config.accessid);
          formData.append('success_action_status', '200');
          formData.append('callback', config.callback);
          formData.append('signature', config.signature);
          // formData.append('name', uuid + '.png');
          formData.append('file', file[0].raw);
          request
            .post(url, formData, {
              headers: {
                'Content-Type': 'multipart/form-data;charset=utf-8',
                // Accept: '*/*',
              },
            })
            .then((res: any) => {
              // resolve 参数为关键代码
              if (res == 200) {
                // 外网url
                const url = config.domain + config.dir + uuid + '.png';
                UploadSuccessCallback(uuid, url);
                //
                Curfile.uploadStatus = true;
                resolve({
                  status: 'success',
                  response: { url: Curfile.url },
                });
              } else {
                UploadErrorCallback();
                Curfile.uploadStatus = false;
              }
            })
            .catch((e) => {
              console.log(e);
            });
        }, 1000);
      });
    };
    const requestSuccessMethod = async (file: UploadFile | UploadFile[]) => {
      return ExtranetUpload(file);
    };
    // 未上传
    const notUploadHtml = () => {
      return (
        <TUpload
          v-model={files.value}
          method="PUT"
          requestMethod={requestSuccessMethod}
          action={actionUrl.value}
          headers={{
            authorization: `Bearer ${getUserCookie()}`,
          }}
          accept={'video'}
          theme="custom"
          before-upload={beforeUpload}
          multiple
          max={1}
          draggable={true}
          onfail={handleFail}
        >
          <div class="custom-upload-click-box">
            <div class="title">选择图片</div>
            <div class="title2">或拖拽图片到此处</div>
            <div>
              <UploadTip></UploadTip>
            </div>
            <TButton class="custom-chose-file">选择文件</TButton>
          </div>
        </TUpload>
      );
    };
    // 上传中
    const UploadingHtml = () => {
      return (
        <div class="custom-uploading-stauts">
          <TProgress
            class="custom-t-progress"
            theme="circle"
            percentage={percentage.value}
            size={'small'}
            color={'#00f9f9'}
          />
          <div class="uploading-title">正在上传</div>
        </div>
      );
    };
    const UploadSuccess = () => {
      return (
        <div class="custom-UploadSuccess-stauts">
          <img class="UploadSuccess-img" src={Curfile.url} alt="" />
        </div>
      );
    };
    // 获取当前上传状态
    const currentUploadStatus = () => {
      if (Curfile.status == 0) {
        return notUploadHtml();
      } else if (Curfile.status == 1) {
        // 上传中
        return UploadingHtml();
      } else {
        // 上传完成
        return UploadSuccess();
      }
    };
    watch(
      () => props.num,
      (v) => {
        Curfile.status = 0;
      }
    );
    return () => (
      <div class="custom-real-upload">
        <div class="real-upload-content">
          <div class="custom-real-upload-component">
            {currentUploadStatus()}
          </div>
        </div>
      </div>
    );
  },
});
