import { RequestMethodResponse } from 'tdesign-vue-next';
import { v4 } from 'uuid';
import request from '@/utils/otherRequest';
import request2 from '@/utils/OutsideRequest';
import { getUserCookie } from '../api/userApi';

/**
 * 可复用的http请求
 */

/**
 * 图片上传到阿里云
 */
export const UploadImageToAly = (config: any, file: File) => {
  return new Promise<RequestMethodResponse>((resolve) => {
    const uuid = v4();
    let url = '';
    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);
      request
        .post(url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data;charset=utf-8',
            // Accept: '*/*',
          },
        })
        .then((res: any) => {
          // resolve 参数为关键代码
          const url = config.domain + config.dir + uuid + '.png';
          if (res == 200) {
            // 外网url
            resolve({
              status: 'success',
              response: { url: url },
            });
          } else {
            resolve({
              status: 'fail',
              response: { url: url },
            });
          }
        })
        .catch((e) => {
          console.log(e);
        });
    }, 1000);
  });
};

// 请求外部链接
export const useRequest = (
  type: 'get' | 'post',
  url: string,
  data: any,
  needToken: boolean = true
) => {
  if (type == 'get') {
    return request2.get(url, {
      params: data,
      headers: needToken
        ? {
            authorization: `Bearer ${getUserCookie()}`,
          }
        : {},
    });
  } else if (type == 'post') {
    return request2.post(url, data, {
      headers: needToken
        ? {
            authorization: `Bearer ${getUserCookie()}`,
          }
        : {},
    });
  }
};
