import { computed, defineComponent, reactive, ref } from 'vue';
import './index.less';
import UploadTip from '@/assets/svg/upload/uploadTip.svg?component';
import {
  MessagePlugin,
  Button as TButton,
  Upload as TUpload,
  Progress as TProgress,
  UploadFile,
  RequestMethodResponse,
} from 'tdesign-vue-next';
import { useStore } from 'vuex';
import { getUserCookie } from '@/utils/api/userApi';
import request from '@/utils/otherRequest';
import { v4 } from 'uuid';
export default defineComponent({
  props: {
    modelValue: String,
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const store = useStore();
    // 后台配置的地址
    const adminConfigUrl = computed(() => store.getters['user/getadminConfig']);
    // 上传策略
    const uploadStrategy = computed(
      () => store.getters['user/getuploadStrategy']
    );
    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) => {
      return true;
    };
    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('上传失败');
    };
    // 内网上传-Intranet
    const IntranetUpload = (file: any) => {
      openpercentage();
      return new Promise((resolve) => {
        let uuid = v4();
        // 上传中状态
        Curfile.status = 1;
        let url = '';
        if (import.meta.env.MODE == 'production') {
          // 线上地址使用完整url
          url = adminConfigUrl.value + 'video/' + uuid + '.png';
          // url = `http://192.168.1.19:5000/video/` + uuid + '.png';
        } else if (import.meta.env.MODE == 'app') {
          // app
          url = '/video/' + uuid + '.png';
        } else {
          // 本地
          url = '/video/' + uuid + '.png';
        }
        setTimeout(() => {
          request.put(url, file[0].raw).then((res: any) => {
            // resolve 参数为关键代码
            if (res == 200) {
              let url = adminConfigUrl.value + 'video/' + uuid + '.png';
              UploadSuccessCallback(uuid, url);
              //
              Curfile.uploadStatus = true;
              resolve({
                status: 'success',
                response: { url: Curfile.url },
              });
            } else {
              UploadErrorCallback();
              Curfile.uploadStatus = false;
            }
          });
        }, 1000);
      });
    };
    // 外网上传-func
    const ExtranetUpload = (file: any) => {
      openpercentage();
      return new Promise<RequestMethodResponse>((resolve) => {
        let uuid = v4();
        // 上传中状态
        Curfile.status = 1;
        let url = '';
        const { config } = uploadStrategy.value;
        url = 'https://' + config.host;
        setTimeout(() => {
          let 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
                let 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
            theme="circle"
            percentage={percentage.value}
            size={'small'}
          />
          <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();
      }
    };
    return () => (
      <div class="custom-real-upload-component">
        <div class="real-upload-box">{currentUploadStatus()}</div>
      </div>
    );
  },
});
