import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { tencentCos } from "../../api/base";
import date from 'date-php';
import { getAuthorization, util as cosUtil } from 'cos-js-sdk-v5';

// 对更多字符编码的 url encode 格式
var camSafeUrlEncode = function camSafeUrlEncode(str) {
  return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
};
/**
 * 文件上传
 * @param file File对象
 * @param options 配置
 * @param options.pathDir 上传子目录
 * @param options.isDateDir 开启日期目录
 * @param options.reName 文件名
 * @param options.maxSize 最大上传限制(Btye)
 * @param options.onProgress 上传进度
 */
export default function (_x, _x2) {
  return _ref.apply(this, arguments);
}
function _ref() {
  _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(file, options) {
    var mb, name, size, pathDir, _options$isDateDir, isDateDir, reName, _options$maxSize, maxSize, onProgress, _name$match, fileName, fMainName, fExtName, _ref2, _ref2$data, data, code, msg, _ref3, _ref3$Credentials, TmpSecretId, TmpSecretKey, Token, Bucket, Region, protocol, host, uploadBasePath, uploadAjaxUrl, uploadConf;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          mb = Math.pow(Math.pow(2, 10), 2);
          name = file.name, size = file.size;
          pathDir = options.pathDir, _options$isDateDir = options.isDateDir, isDateDir = _options$isDateDir === void 0 ? false : _options$isDateDir, reName = options.reName, _options$maxSize = options.maxSize, maxSize = _options$maxSize === void 0 ? mb * 20 : _options$maxSize, onProgress = options.onProgress; // 文件名, 主名, 扩展名
          _name$match = name.match(/(.*?)(\.[^.]+)?$/), fileName = _name$match[0], fMainName = _name$match[1], fExtName = _name$match[2]; // const fileBlob = window.URL.createObjectURL(file)
          if (!(size > maxSize)) {
            _context.next = 6;
            break;
          }
          return _context.abrupt("return", {
            code: '1000',
            data: '',
            msg: "\u4E0A\u4F20\u7684\u6587\u4EF6(" + fileName + ")\u7684\u5927\u5C0F(" + ((size / mb).toFixed(3) - 0) + "M)\uFF0C\u5DF2\u8D85\u51FA(" + ((maxSize / mb).toFixed(3) - 0) + "M)\u9650\u5236"
          });
        case 6:
          _context.next = 8;
          return tencentCos.authorization();
        case 8:
          _context.t0 = _context.sent;
          if (_context.t0) {
            _context.next = 11;
            break;
          }
          _context.t0 = {
            code: '2000',
            data: '',
            msg: "\u767B\u5F55\u5931\u6548\u6216cos\u7B7E\u540D\u5931\u8D25"
          };
        case 11:
          _ref2 = _context.t0;
          _ref2$data = _ref2.data;
          data = _ref2$data === void 0 ? {} : _ref2$data;
          code = _ref2.code;
          msg = _ref2.msg;
          if (!(code !== 200)) {
            _context.next = 18;
            break;
          }
          return _context.abrupt("return", {
            code: code,
            data: data,
            msg: msg
          });
        case 18:
          _ref3 = (data === null || data === void 0 ? void 0 : data.Response) || {
            Credentials: {}
          }, _ref3$Credentials = _ref3.Credentials, TmpSecretId = _ref3$Credentials.TmpSecretId, TmpSecretKey = _ref3$Credentials.TmpSecretKey, Token = _ref3$Credentials.Token;
          Bucket = '6d61-maimairen-9gx1rgm6b2b080ad-1251020834'; // 存储桶名称
          Region = 'ap-shanghai'; // 地域名称
          protocol = location.protocol === 'https:' ? 'https:' : 'http:';
          host = protocol + "//" + Bucket + ".cos." + Region + ".myqcloud.com/"; // 上传基础路径
          uploadBasePath = function () {
            var path = "upload/" + (process.env.NODE_ENV !== 'production' ? 'dev/' : '');
            if (pathDir) path += pathDir + "/";
            if (isDateDir) path += date('Y/m/d/', new Date());

            /**
             * 重命名文件名
             * opts.reName: undefined -> 原文件名
             * opts.reName: boolean === true -> 随机名称
             * opts.reName: string -> 直接取reName
             */
            if (reName === undefined) {
              path += fileName;
            } else {
              path += typeof reName === 'string' ? "" + reName + fExtName : "" + cosUtil.md5(Date.now().toString() + Math.random().toString(16).substr(2)) + fExtName;
            }
            return path;
          }(); // 上传接口
          uploadAjaxUrl = host + camSafeUrlEncode(uploadBasePath).replace(/%2F/g, '/');
          uploadConf = {
            headers: {
              // Accept: '*/*',
              Authorization: getAuthorization({
                // 根据临时密钥 > 签名
                SecretId: TmpSecretId,
                SecretKey: TmpSecretKey,
                Method: 'put',
                Pathname: "/" + uploadBasePath
              }),
              // 'Content-Type': fileType,
              'x-cos-security-token': Token
            },
            baseURL: '/'
          };
          if (onProgress && typeof onProgress === "function") Object.assign(uploadConf, {
            onUploadProgress: onProgress
          });
          // 开始上传
          _context.next = 29;
          return tencentCos.upload(uploadAjaxUrl, file, uploadConf);
        case 29:
          return _context.abrupt("return", {
            code: '0000',
            data: {
              imgName: fMainName,
              ossPath: uploadAjaxUrl.replace(/^https?:\/\/[^./\\]+(\.[^./\\]+)+/, 'https://img.maimairen.com') // 替换自定义域名
            },

            msg: "\u4E0A\u4F20\u6210\u529F"
          });
        case 30:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _ref.apply(this, arguments);
}