import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _extends from "@babel/runtime/helpers/extends";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import Cookie from 'js-cookie';
import { project } from '@alilc/lowcode-engine';
import { lottery as lotteryXHR } from "../api/base";
var map = {
  cookiePrefix: '__xiatu__'
};
function setCookieData(jsonData) {
  if (jsonData === void 0) {
    jsonData = {
      token: ''
    };
  }
  var curCookie = getCookieData();
  Cookie.set(map.cookiePrefix + "cookie_data", JSON.stringify(_extends({}, curCookie, jsonData)));
}
function getCookieData() {
  var _cookie = Cookie.get(map.cookiePrefix + "cookie_data");
  return _cookie ? JSON.parse(_cookie) : {
    token: ''
  };
}
function delCookieData(keyName) {
  var curCookie = getCookieData();
  delete curCookie[keyName];
  Cookie.set(map.cookiePrefix + "cookie_data", JSON.stringify(curCookie));
}
var $_GET = function () {
  var search = window.location.href.split('?');
  var searchArr = search[1] ? search[1].split('&') : [];
  var _get = {};
  for (var item in searchArr) {
    if (typeof Array.prototype[item] === 'undefined') {
      var params = searchArr[item].split('=');
      _get[params[0]] = decodeURIComponent(params[1]);
    }
  }
  return _get;
}();

// 获取当前页面
function getSchema() {
  var projectSchema = project.exportSchema();
  var componentsMapArray = projectSchema.componentsMap,
    componentsTree = projectSchema.componentsTree;
  var componentsMap = {};
  componentsMapArray && componentsMapArray.forEach(function (component) {
    componentsMap[component.componentName] = component;
  });
  var schema = componentsTree[0];
  return schema;
}

// 获取当前页面所有参数
function getSchemaAll() {
  var projectSchema = project.exportSchema();
  var componentsMapArray = projectSchema.componentsMap,
    componentsTree = projectSchema.componentsTree;
  var componentsMap = {};
  componentsMapArray && componentsMapArray.forEach(function (component) {
    componentsMap[component.componentName] = component;
  });
  var obj = {
    componentsMap: componentsMap,
    componentsTree: componentsTree
  };
  return obj;
}

// 获取浏览器的search

function getSearchParams(search) {
  var searchParams = {};
  // 如果 location 中有 search 值 ，去除 search 值中的第一个字符 ‘?’
  var searchStr = search.substring(1);
  // 以 & 符为分隔符，解析出 key value 组合 ，组合的形式为 'key=value'
  var searchArr = searchStr.length ? searchStr.split('&') : [];
  searchArr.forEach(function (item) {
    // 以 = 为分隔符，解析出 key 和 value , 其中数组的第一项为 key ，数组的第二项为 value
    var keyAndValue = item.split('=');
    // 如果查询参数中包含中文，会被编码成一串字符串，需要使用 decodeURIComponent 进行 解码
    var key = decodeURIComponent(keyAndValue[0]);
    var value = decodeURIComponent(keyAndValue[1]);
    if (key) {
      searchParams[key] = value;
    }
  });
  return searchParams;
}

// 获取对象类型数据
function getObjData() {
  // const temp = window.JSON.parse(window.JSON.stringify(e));
  // console.log('temp', temp);
  // return new Function(`return ${temp}`)();
}
function b64toFile(dataurl, filename) {
  var arr = dataurl.split(",");
  var mime = arr[0].match(/:(.*?);/)[1];
  var bstr = atob(arr[1]);
  var n = bstr.length;
  var u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, {
    type: mime
  });
}

/**
 * 获取环境变量
 */
function getEnv() {
  switch (true) {
    case process.env.NODE_ENV === 'development':
      // 开发
      switch (true) {
        case /^(192\.168(\.((25[0-5])|(2[0-4]\d)|([1]\d{0,2})|\d{1,2})){2}|10(\.((25[0-5])|(2[0-4]\d)|([1]\d{0,2})|\d{1,2})){3}|172\.(1[6-9]|2\d|3[0-1])(\.((25[0-5])|(2[0-4]\d)|([1]\d{0,2})|\d{1,2})){2})$/g.test(location.hostname):
          // 开发
          return 'lan';
        // 局域网环境

        case location.hostname === 'localhost':
        default:
          return 'local';
        // 本地
      }

    case process.env.NODE_ENV === 'production': // 生产
    default:
      switch (true) {
        case /(?=[^/])([-\w]+\.)+?maimairen\.net$/ig.test(location.hostname):
          return 'test';
        // 测试环境

        case /(?=[^/])([-\w]+\.)+?maimairen\.com$/ig.test(location.hostname):
        default:
          return 'prod';
        // 正式环境
      }
  }
}

// 获取微信的 appid
var getWxAppid = getEnv() === 'prod' ? 'wxe7bfcd062bfb8169' : 'wxe677e4aad49ba784';

// 去微信授权登录
var loginWechat = function loginWechat(url) {
  window.location.href = url || "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + getWxAppid + "&redirect_uri=" + encodeURIComponent(window.location.href) + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
};

// 抽奖
var lottery = function lottery(id) {
  var activityId = $_GET.activityId,
    code = $_GET.code;
  return new Promise( /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(resolve) {
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!code) resolve({
                code: 10401,
                data: loginWechat,
                msg: '您还没有登录'
              });
              if (!(id || activityId)) {
                _context.next = 7;
                break;
              }
              _context.t0 = resolve;
              _context.next = 5;
              return lotteryXHR({
                b: id || activityId
              });
            case 5:
              _context.t1 = _context.sent;
              (0, _context.t0)(_context.t1);
            case 7:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));
    return function (_x) {
      return _ref.apply(this, arguments);
    };
  }());
};
export { setCookieData, getCookieData, delCookieData, getSchema, getSchemaAll, getObjData, $_GET, b64toFile, getSearchParams, getEnv, getWxAppid, lottery };