import request from '@/utils/request';
import createCOS from '@/utils/txyunCosUpLoad.js';
import { uploadDocumentFile } from './upload/index.js';
import router from '../router/index';
import { computed } from 'vue';
import { shrinkImage } from 'shrinkpng';
const sn = computed(() => router.currentRoute.value.query.sn || 'default');
export default class CommonApi {
  static uploadFileWidthSn(file, sn) {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('sn', sn || '');

    return request({
      url: '/console/upload_file',
      method: 'post',
      data: formData
    });
  }
  static uploadFileWidthSnForAnswer(file, sn) {
    const formData = new FormData();
    formData.append('file', file);

    return request({
      url: `/answer/upload_file/${sn}`,
      method: 'post',
      data: formData
    });
  }
  /** OssInfo */
  static getOssInfo() {
    return request({
      url: '/console/files/credentials'
    });
  }
  static async cosUpload3DCompress(file, quality = 20) {
    const _file = await shrinkImage(file, { quality });
    return await this.cosUpload3D(_file);
  }
  static async cosUpload3D(file, defaultName = '') {
    let name = defaultName?.replace?.(/[\s+]/g, '_') || '';

    const getRandomFileName = () => {
      return `3D/upload/${new Date().getTime()}_${Math.floor(Math.random() * 1000)}`;
    };

    name = name || getRandomFileName();
    const { data } = await CommonApi.getOssInfo();
    const param = {
      region: data.Region,
      host: data.Host,
      sessionToken: data.sessionToken,
      tmpSecretId: data.tmpSecretId,
      tmpSecretKey: data.tmpSecretKey,
      bucket: data.Bucket,
      startTime: data.startTime,
      expiredTime: data.expiredTime,
      name: `${data.prefix}/${name}`,
      file
    };

    try {
      const location = await createCOS(param);
      return {
        url: `https://${location}`,
        name
      };
    } catch (error) {
      return {
        url: '',
        name: ''
      };
    }
  }
  /**
   * 上传文件
   * @param {文件file} file
   * @returns {url:"",name:'fileName'}
   */
  static async cosUpload(file, fileName) {
    let name = fileName?.replace?.(/[\s+]/g, '_') || '';

    const getRandomFileName = (name) => {
      return `survey/${sn.value}/${new Date().getTime()}-${Math.floor(Math.random() * 1000)}-${name}`;
    };
    /* eslint-disable no-useless-escape */
    const reg = /\\|\/|\?|\？|\*|"|“|”|'|‘|’|<|>|{|}|\[|\]|\【|\】|：|:|、|\^|\$|!|~|`|\s|\+/g;
    name =
      name ||
      getRandomFileName(file?.name?.replace(reg, '') ?? '' ?? `${new Date().getTime()}.png`);
    const res = await CommonApi.getOssInfo();
    /* eslint-enable no-useless-escape */

    const { data } = res.data;
    const param = {
      region: data.Region,
      host: data.Host,
      sessionToken: data.sessionToken,
      tmpSecretId: data.tmpSecretId,
      tmpSecretKey: data.tmpSecretKey,
      bucket: data.Bucket,
      startTime: data.startTime,
      expiredTime: data.expiredTime,
      name: `${data.prefix}/${name}`,
      file
    };
    try {
      const location = await createCOS(param);
      return {
        url: `https://${location}`,
        name
      };
    } catch (error) {
      return {
        url: '',
        name: ''
      };
    }
  }
  /**
   * 上传文件到阿里云和文档库
   * @param {文件file} file
   * @param {问卷id} sn
   * @param {1=问卷设计,2=数据分析,3=问卷预览,4=数据明细,5=图表分析,6=高级分析,7=市场模拟} importType
   * @returns {url:"",name:'fileName'}
   */
  static async docuHousecosUpload(file, sn, importType, startFileName = 'survey') {
    // eslint-disable-next-line standard/no-callback-literal
    const reg = /\\|\/|\?|？|\*|"|“|”|'|‘|’|<|>|{|}|\[|\]|【|】|：|:|、|\^|\$|!|~|`|\s|\+/g;

    // eslint-disable-next-line standard/no-callback-literal
    const fileName = `${startFileName}/${new Date().getTime()}_${Math.floor(Math.random() * 1000)}_${
      file?.name?.replace(reg, '') ?? '' ?? `${new Date().getTime()}.png`
    }`;
    try {
      const result = await this.cosUpload(file, fileName);
      uploadDocumentFile({
        url: JSON.stringify([{ name: file.name, url: result.url, size: file.size }]),
        parent_sn: sn?.value || sn,
        import_type: importType || 1
      });
      return result;
    } catch (error) {
      // error
    }
  }
}
