"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.parseTag = exports.parseStringV2 = exports.parseString = exports.parseOpenDataStringToImg = exports.parseHtmlAndTextTag = exports.isWxTrial = exports.isWechat = exports.isPlatform = exports.getSource = exports.getOpenId = exports["default"] = exports.OpenUserName = exports.OpenDepartmentName = void 0;

var _react = _interopRequireWildcard(require("react"));

var _bsGlobal = require("./bs-global");

var _openDataPainter = require("../components/open-data-painter");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var WX_SOURCE = 860;
var WX_UA_STR = 'micromessenger';
var FEISHU_SOURCE = 862;
var DINGTALK_SOURCE = 861;
var ignorePIds = [-1, 0, 10000];

var getSource = function getSource() {
  var _getBSGlobal;

  return (_getBSGlobal = (0, _bsGlobal.getBSGlobal)('tenantInfo')) === null || _getBSGlobal === void 0 ? void 0 : _getBSGlobal.Source;
};

exports.getSource = getSource;

var isWechat = function isWechat() {
  return getSource() === WX_SOURCE;
};

exports.isWechat = isWechat;

var isWxTrial = function isWxTrial() {
  return getSource() === WX_SOURCE && (0, _bsGlobal.getVersion)() === 1;
};

exports.isWxTrial = isWxTrial;

var getUA = function getUA() {
  return navigator.userAgent.toLowerCase();
};

var getOpenId = function getOpenId(id, type) {
  var openIds;

  if (type == 'userName') {
    openIds = (0, _bsGlobal.getBSGlobal)('openIds');
  } else if (type == 'departmentName') {
    openIds = (0, _bsGlobal.getBSGlobal)('openDepartmentIds');
  }

  return openIds && openIds[id];
};

exports.getOpenId = getOpenId;

function openData() {
  var _getBSGlobal2;

  // 企业微信租户 && 非自建应用
  if ((getSource() === WX_SOURCE || getUA().includes(WX_UA_STR)) && (_getBSGlobal2 = (0, _bsGlobal.getBSGlobal)('tenantInfo')) !== null && _getBSGlobal2 !== void 0 && _getBSGlobal2.isTranslate) {
    return function (p) {
      var pId = p.id,
          pName = p.name,
          pCorpId = p.corpId,
          pType = p.type;
      var ref = (0, _react.useRef)(null);
      (0, _react.useLayoutEffect)(function () {
        var _ref;

        // @ts-ignore
        (_ref = window.WWOpenData && window.WWOpenData || window.top.WWOpenData) === null || _ref === void 0 ? void 0 : _ref.bind(ref.current);
      }, [pId, pName]);

      if (pId === undefined && pCorpId === undefined) {
        return pName || null;
      } // @ts-ignore


      var openId = pCorpId || getOpenId(pId, pType);

      if (!openId) {
        if (pId !== undefined && !ignorePIds.includes(pId)) {// Sentry.withScope((scope) => {
          //   scope.setTag('error-level', 'P1')
          //   scope.setTag('error-type', 'openId不存在')
          //   scope.setTag('fail-type', pType)
          //   scope.setTag('p-id', pId)
          //   scope.setTag('p-name', pName)
          //   scope.setExtra('fail_type', pType)
          //   scope.setExtra('p_id', pId)
          //   scope.setExtra('p_name', pName)
          //   scope.setExtra('corp_id', pCorpId)
          //   scope.setExtra('open_id', getOpenId(pId, pType))
          //   p.callFunc && scope.setExtra('fail_callFunc', p.callFunc)
          //   p.extra && scope.setExtra('fail_extra', p.extra)
          //   Sentry.captureException(
          //     new Error('企业微信openData调用失败'),
          //     scope,
          //   )
          // })
        }

        return pName || pId || null;
      }

      return /*#__PURE__*/_react["default"].createElement("div", {
        style: {
          display: 'inline',
          position: 'relative',
          overflow: 'hidden',
          textOverflow: 'ellipsis'
        }
      }, (window.WWOpenData || window.top.WWOpenData) && /*#__PURE__*/_react["default"].createElement("ww-open-data", {
        ref: ref,
        type: pType,
        openid: openId
      }), !window.WWOpenData && !window.top.WWOpenData && (pName || pId), /*#__PURE__*/_react["default"].createElement("div", {
        style: {
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          zIndex: 1
        }
      }));
    };
  }

  return function (p) {
    return p.name || p.id || null;
  };
}

var getOpenData = openData();

var OpenUserName = function OpenUserName(p) {
  return getOpenData(_objectSpread(_objectSpread({}, p), {}, {
    type: 'userName'
  }));
};

exports.OpenUserName = OpenUserName;

var OpenDepartmentName = function OpenDepartmentName(p) {
  return getOpenData(_objectSpread(_objectSpread({}, p), {}, {
    type: 'departmentName'
  }));
};

exports.OpenDepartmentName = OpenDepartmentName;
var openDataMap = {
  user: OpenUserName,
  department: OpenDepartmentName
}; // name:'wx'|'dd'|'feishu',type:'source'|'env'|'all' = 'all'

var isPlatform = function isPlatform(name) {
  var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'all';

  switch (name) {
    case 'wx':
      {
        if (type == 'source') return getSource() === WX_SOURCE;
        if (type == 'env') return getUA().includes(WX_UA_STR);
        return getSource() === WX_SOURCE || getUA().includes(WX_UA_STR);
      }

    case 'dd':
      {
        return getSource() === DINGTALK_SOURCE;
      }

    case 'feishu':
      {
        return getSource() === FEISHU_SOURCE;
      }

    default:
      return false;
  }
};

exports.isPlatform = isPlatform;

var parseTag = function parseTag(str) {
  var _window$BSGlobal$tena;

  var source = (_window$BSGlobal$tena = window.BSGlobal.tenantInfo) === null || _window$BSGlobal$tena === void 0 ? void 0 : _window$BSGlobal$tena.Source;
  var ua = navigator.userAgent.toLowerCase();
  var reg = /<\w+[\w\W]*?(userId|departmentId)=["'](\S+?)["'][\w\W]*?>@([\w\W]*?)<\/\w+>/g;
  var strReg = /<\w+[\w\s"'\/=\:\.]*?(?:userId|departmentId)=["']\S+?["'][\w\s"'\/=\:\.]*?>[\w\W]*?<\/\w+?>/;
  var openDatas = [];
  var matchStr = reg.exec(str); // if (source != WX_SOURCE && ua.indexOf('micromessenger') == -1)
  //   return <span dangerouslySetInnerHTML={{ '__html': str }} />;

  while (matchStr != null) {
    var OpenDataCompoent = matchStr[1] == 'userId' ? OpenUserName : OpenDepartmentName;

    if (!OpenDataCompoent) {
      openDatas.push( /*#__PURE__*/_react["default"].createElement("span", {
        dangerouslySetInnerHTML: {
          __html: matchStr[0]
        },
        onClick: function onClick(e) {
          return e.stopPropagation();
        }
      }));
    } else {
      openDatas.push( /*#__PURE__*/_react["default"].createElement("span", {
        style: {
          color: '#1890ff',
          margin: '0 4px'
        },
        onClick: function onClick(e) {
          return e.stopPropagation();
        }
      }, "@", /*#__PURE__*/_react["default"].createElement(OpenDataCompoent, {
        id: matchStr[2],
        name: matchStr[3]
      })));
    }

    matchStr = reg.exec(str);
  }

  var commonStrs = str.split(strReg);
  var renderData = [];

  for (var i = 0; i < commonStrs.length; i++) {
    renderData.push( /*#__PURE__*/_react["default"].createElement("span", {
      dangerouslySetInnerHTML: {
        __html: commonStrs[i]
      }
    }));
    renderData.push(openDatas[i]);
  }

  return renderData;
};

exports.parseTag = parseTag;

var parseString = function parseString(str) {
  var _window$BSGlobal$tena2;

  // @ts-ignore
  var source = (_window$BSGlobal$tena2 = window.BSGlobal.tenantInfo) === null || _window$BSGlobal$tena2 === void 0 ? void 0 : _window$BSGlobal$tena2.Source;
  var ua = navigator.userAgent.toLowerCase();

  if (source != WX_SOURCE && ua.indexOf('wxwork') == -1) {
    return /*#__PURE__*/_react["default"].createElement("span", {
      dangerouslySetInnerHTML: {
        __html: str
      }
    });
  }

  var reg = /\[(\w+?)\:(\w+?)\]/g;
  var strReg = /\[\w+?\:\w+?\]/;
  var openDatas = [];
  var matchStr = reg.exec(str);
  if (!matchStr) return parseStringV2(str);

  while (matchStr != null) {
    var OpenDataCompoent = openDataMap[matchStr[2]];

    if (!OpenDataCompoent) {
      var v2Paresed = parseStringV2(matchStr[0]);
      openDatas.push( /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, v2Paresed));
    } else {
      openDatas.push( /*#__PURE__*/_react["default"].createElement("span", null, /*#__PURE__*/_react["default"].createElement(OpenDataCompoent, {
        id: matchStr[1],
        callFunc: "parseString",
        extra: str
      })));
    }

    matchStr = reg.exec(str);
  }

  var commonStrs = str.split(strReg);
  var renderData = [];

  for (var i = 0; i < commonStrs.length; i++) {
    var _v2Paresed = parseStringV2(commonStrs[i]);

    renderData.push( /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, _v2Paresed)); // renderData.push(
    //   <span dangerouslySetInnerHTML={{ __html: commonStrs[i] }} />,
    // )

    renderData.push(openDatas[i]);
  }

  return renderData;
};

exports.parseString = parseString;
var openDataMapV2 = {
  userName: OpenUserName,
  departmentName: OpenDepartmentName
};

var parseStringV2 = function parseStringV2(str) {
  var _window$BSGlobal$tena3;

  // @ts-ignore
  var source = (_window$BSGlobal$tena3 = window.BSGlobal.tenantInfo) === null || _window$BSGlobal$tena3 === void 0 ? void 0 : _window$BSGlobal$tena3.Source;
  var ua = navigator.userAgent.toLowerCase();

  if (source != WX_SOURCE && ua.indexOf('micromessenger') == -1) {
    return /*#__PURE__*/_react["default"].createElement("span", {
      dangerouslySetInnerHTML: {
        __html: str
      }
    });
  }

  var reg = /\$(userName|departmentName)\=(.+?)\$/g;
  var strReg = /\$(?:userName|departmentName)\=.+?\$/;
  var openDatas = [];
  var matchStr = reg.exec(str);

  while (matchStr != null) {
    var OpenDataCompoent = openDataMapV2[matchStr[1]];

    if (!OpenDataCompoent) {
      openDatas.push(matchStr[0]);
    } else {
      openDatas.push( /*#__PURE__*/_react["default"].createElement("span", null, /*#__PURE__*/_react["default"].createElement(OpenDataCompoent, {
        corpId: matchStr[2]
      })));
    }

    matchStr = reg.exec(str);
  }

  var commonStrs = str.split(strReg);
  var renderData = [];

  for (var i = 0; i < commonStrs.length; i++) {
    renderData.push( /*#__PURE__*/_react["default"].createElement("span", {
      dangerouslySetInnerHTML: {
        __html: commonStrs[i]
      }
    }));
    renderData.push(openDatas[i]);
  }

  return renderData;
};

exports.parseStringV2 = parseStringV2;

var parseOpenDataStringToImg = /*#__PURE__*/function () {
  var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(str) {
    var font,
        reg,
        strReg,
        openDatas,
        matchStr,
        commonStrs,
        renderData,
        i,
        _args = arguments;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            font = _args.length > 1 && _args[1] !== undefined ? _args[1] : {
              lineHeight: 20,
              fontSize: 18,
              fontWeight: '500',
              color: '#3f4755'
            };
            font = _objectSpread(_objectSpread({}, {
              lineHeight: 20,
              fontSize: 18,
              fontWeight: '500',
              color: '#3f4755'
            }), font || {});
            reg = /\$(userName|departmentName)\=(.+?)\$/g;
            strReg = /\$(?:userName|departmentName)\=.+?\$/;
            openDatas = [];
            matchStr = reg.exec(str);

          case 6:
            if (!(matchStr != null)) {
              _context.next = 15;
              break;
            }

            _context.t0 = openDatas;
            _context.next = 10;
            return getCanvasImg(matchStr[2], matchStr[1], font);

          case 10:
            _context.t1 = _context.sent;

            _context.t0.push.call(_context.t0, _context.t1);

            matchStr = reg.exec(str);
            _context.next = 6;
            break;

          case 15:
            commonStrs = (str === null || str === void 0 ? void 0 : str.split(strReg)) || [];
            renderData = [];

            for (i = 0; i < commonStrs.length; i++) {
              renderData.push( /*#__PURE__*/_react["default"].createElement("span", {
                dangerouslySetInnerHTML: {
                  __html: commonStrs[i]
                }
              }));
              renderData.push(openDatas[i]);
            }

            return _context.abrupt("return", renderData);

          case 19:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function parseOpenDataStringToImg(_x) {
    return _ref2.apply(this, arguments);
  };
}();

exports.parseOpenDataStringToImg = parseOpenDataStringToImg;

var getCanvasImg = /*#__PURE__*/function () {
  var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(id, type, _ref3) {
    var lineHeight, fontSize, fontWeight, color, font, canvas, ctx, name, img, _ctx$measureText, width, actualWidth, src;

    return regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            lineHeight = _ref3.lineHeight, fontSize = _ref3.fontSize, fontWeight = _ref3.fontWeight, color = _ref3.color;
            font = "".concat(fontWeight, " ").concat(fontSize, "px/").concat(lineHeight, "px arial,sans-serif");
            canvas = document.createElement('canvas');
            ctx = canvas.getContext('2d');

            if (ctx) {
              _context2.next = 6;
              break;
            }

            return _context2.abrupt("return", null);

          case 6:
            _context2.next = 8;
            return (0, _openDataPainter.getOpenData)({
              openId: id,
              type: type
            });

          case 8:
            name = _context2.sent;
            img = document.createElement('img');
            ctx.font = font; // const fitStr = fittingString(ctx, name, 92);

            _ctx$measureText = ctx.measureText(name || ''), width = _ctx$measureText.width;
            actualWidth = Math.min(width, 92);
            (0, _openDataPainter.setSize)(canvas, ctx, actualWidth, lineHeight);
            ctx.textBaseline = 'middle';
            ctx.font = font;
            ctx.fillStyle = color;
            ctx.fillText(name || '', 0, lineHeight / 2);
            src = canvas.toDataURL();
            return _context2.abrupt("return", /*#__PURE__*/_react["default"].createElement("img", {
              src: src,
              width: actualWidth,
              height: lineHeight
            }));

          case 20:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));

  return function getCanvasImg(_x2, _x3, _x4) {
    return _ref4.apply(this, arguments);
  };
}();

var parseHtmlAndTextTag = function parseHtmlAndTextTag(str) {
  var reg = /<\w+[\w\W]*?(userId|departmentId)=["'](\S+?)["'][\w\W]*?>@([\w\W]*?)<\/\w+>/g;
  var strReg = /<\w+[\w\s"'\/=\:\.]*?(?:userId|departmentId)=["']\S+?["'][\w\s"'\/=\:\.]*?>[\w\W]*?<\/\w+?>/;
  var openDatas = [];
  var matchStr = reg.exec(str);
  var renderData = [];
  if (matchStr == null) return parseString(str);

  while (matchStr != null) {
    if (matchStr) {
      var OpenDataCompoent = matchStr[1] == 'userId' ? OpenUserName : OpenDepartmentName;

      if (!OpenDataCompoent) {
        var strParsed = parseString(matchStr[0]);
        openDatas.push( /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, strParsed));
      } else {
        openDatas.push( /*#__PURE__*/_react["default"].createElement("span", {
          style: {
            color: '#1890ff',
            margin: '0 4px'
          },
          onClick: function onClick(e) {
            return e.stopPropagation();
          }
        }, "@", /*#__PURE__*/_react["default"].createElement(OpenDataCompoent, {
          id: matchStr[2],
          name: matchStr[3]
        })));
      }

      matchStr = reg.exec(str);
    }
  }

  var commonStrs = str.split(strReg);

  for (var i = 0; i < commonStrs.length; i++) {
    var _strParsed = parseString(commonStrs[i]);

    renderData.push( /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, _strParsed));
    renderData.push(openDatas[i]);
  }

  return renderData.filter(function (item) {
    return item !== undefined;
  });
};

exports.parseHtmlAndTextTag = parseHtmlAndTextTag;
var _default = {
  OpenUserName: OpenUserName,
  OpenDepartmentName: OpenDepartmentName,
  isWechat: isWechat,
  isPlatform: isPlatform,
  parseString: parseString,
  parseTag: parseTag,
  parseHtmlAndTextTag: parseHtmlAndTextTag
};
exports["default"] = _default;