import axios from 'axios';
import { UPLOADER_CONFIG } from './config.mjs';

/**
 * 请求 hashCode
 * @example
 * ```ts
 * const { hash, timestamp } = await requestHashCode();
 * console.log(hash, timestamp);
 * ```
 * @ignore
 */
function requestHashCode() {
  var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : UPLOADER_CONFIG.REQUEST_HASH_URL();
  return new Promise(function (resolve, reject) {
    axios({
      method: 'POST',
      url: url
    }).then(function (res) {
      var _a;
      if ((_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a._hash) {
        var hash = res.data._hash;
        resolve({
          hash: hash,
          timestamp: new Date().getTime()
        });
      } else {
        reject({
          errMsg: '上传功能初始化失败，请重试!'
        });
      }
    })["catch"](function () {
      reject({
        errMsg: '上传功能初始化失败，请重试!'
      });
    });
  });
}
/**
 * 请求上传文件
 * @example
 * ```ts
 * const { hash } = await requestHashCode();
 * const { url } = await requestUploadFile({
 *   file: someFile,
 *   hashCode: hash,
 * });
 * console.log('uploaded:', url);
 * ```
 * @ignore
 */
function requestUploadFile(_ref) {
  var file = _ref.file,
    hashCode = _ref.hashCode,
    _ref$uploadFileKey = _ref.uploadFileKey,
    uploadFileKey = _ref$uploadFileKey === void 0 ? UPLOADER_CONFIG.UPLOAD_FILE_KEY : _ref$uploadFileKey,
    _ref$url = _ref.url,
    url = _ref$url === void 0 ? UPLOADER_CONFIG.UPLOAD_URL_PREFIX : _ref$url;
  if (['mp-weixin', 'mp-qq'].includes(process.env.UNI_PLATFORM || '')) {
    return requestUploadFileInMp({
      file: file,
      hashCode: hashCode,
      url: url
    });
  }
  return new Promise(function (resolve, reject) {
    var formData = new FormData();
    formData.append(uploadFileKey, file);
    var reqUrl = "".concat(url).concat(hashCode);
    var config = {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      withCredentials: false // 实时修改配置。这个api要设置为false
    };
    axios.post(reqUrl, formData, config).then(function (rsp) {
      var _a;
      if (((_a = rsp === null || rsp === void 0 ? void 0 : rsp.data) === null || _a === void 0 ? void 0 : _a.url) && rsp.data.url.length > 0) {
        resolve(rsp.data);
      } else {
        reject(new Error(rsp.data.msg || JSON.stringify(rsp)));
      }
    })["catch"](function (e) {
      reject(e);
    });
  });
}
function requestUploadFileInMp(_ref2) {
  var hashCode = _ref2.hashCode,
    file = _ref2.file,
    prefixUrl = _ref2.url;
  return new Promise(function (resolve, reject) {
    var widthHeight = '';
    var url = "".concat(prefixUrl).concat(hashCode, "&width_height=").concat(widthHeight);
    uni.uploadFile({
      url: url,
      // @ts-ignore
      filePath: file.path,
      name: 'upload_pic_input',
      formData: {
        _hash: hashCode
      },
      success: function success(res) {
        if (res.data) {
          var data = {
            url: '',
            r: 0
          };
          try {
            data = JSON.parse(res.data);
          } catch (err) {}
          if (data.r == 0) {
            resolve({
              url: data.url
            });
            return;
          }
          reject(res);
        } else {
          reject(res);
        }
      },
      fail: function fail(res) {
        reject(res);
      }
    });
  });
}

export { requestHashCode, requestUploadFile };
