"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["default"] = void 0;

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

var _classnames = _interopRequireDefault(require("classnames"));

var _tooltip = _interopRequireDefault(require("../tooltip"));

var _dialogConfirm = _interopRequireWildcard(require("../dialog-confirm"));

var _getLocale = require("../../utils/getLocale");

var _request = require("../../utils/request");

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

require("./index.css");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

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 _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; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var preCls = 'titaui-wechat-btn';
var userId = (0, _bsGlobal.getUserInfo)().Id;
var isDingDing = (0, _bsGlobal.getSource)() === 861;

var WeChatBtn = function WeChatBtn(props) {
  var id = props.id,
      objType = props.objType,
      name = props.name,
      principalUser = props.principalUser;

  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      isShowWeChat = _useState2[0],
      setIsShowWeChat = _useState2[1];

  var _useState3 = (0, _react.useState)([]),
      _useState4 = _slicedToArray(_useState3, 2),
      weChatGroupMember = _useState4[0],
      setWeChatGroupMember = _useState4[1];

  var _useState5 = (0, _react.useState)('chatId'),
      _useState6 = _slicedToArray(_useState5, 2),
      chatId = _useState6[0],
      setChatId = _useState6[1];

  var _useState7 = (0, _react.useState)(),
      _useState8 = _slicedToArray(_useState7, 2),
      loginUserOpenId = _useState8[0],
      setLoginUserOpenId = _useState8[1];

  var _useState9 = (0, _react.useState)(''),
      _useState10 = _slicedToArray(_useState9, 2),
      url = _useState10[0],
      setUrl = _useState10[1];

  var _useState11 = (0, _react.useState)(false),
      _useState12 = _slicedToArray(_useState11, 2),
      createWechatVisible = _useState12[0],
      setCreateWechatVisible = _useState12[1];

  var _useState13 = (0, _react.useState)(''),
      _useState14 = _slicedToArray(_useState13, 2),
      tooltip = _useState14[0],
      setTooltip = _useState14[1];

  var _useState15 = (0, _react.useState)('目标'),
      _useState16 = _slicedToArray(_useState15, 2),
      apply = _useState16[0],
      setApply = _useState16[1];

  var _useState17 = (0, _react.useState)(false),
      _useState18 = _slicedToArray(_useState17, 2),
      isHasGroup = _useState18[0],
      setIsHasGroup = _useState18[1];

  var _useState19 = (0, _react.useState)(false),
      _useState20 = _slicedToArray(_useState19, 2),
      macWarnModalVisible = _useState20[0],
      setMacWarnModalVisible = _useState20[1];

  var _useState21 = (0, _react.useState)(false),
      _useState22 = _slicedToArray(_useState21, 2),
      principalUserModalVisible = _useState22[0],
      setPrincipalUserModalVisible = _useState22[1];

  var _useState23 = (0, _react.useState)(false),
      _useState24 = _slicedToArray(_useState23, 2),
      memberVisible = _useState24[0],
      setMemberVisible = _useState24[1];

  var isWx = navigator.userAgent.match(/wxwork/);
  var isMac = navigator.userAgent.match(/Mac/);
  /**
   * 点击企业微信图标这块稍许复杂 注释说明一下
   * 先判断有没有群 没群就新建群
   * 有群就先调用加人的接口 人本身不在群的情况 成功加人就打开进入群聊
   * 人在群的情况 加人接口返回报错信息updateEnterpriseChat:fail_unsupported chat 则调用打开群接口
   * 群解散的情况 则弹窗提示 联系负责人手动加群
   * mac 不支持加人接口
   */

  var handleClickWechatBtn = function handleClickWechatBtn() {
    if (isWx) {
      //有群了，判断没在群就先进群再打开群
      if (chatId !== null && chatId !== 'chatId') {
        wx.invoke('openExistedChatWithMsg', {
          chatId: chatId
        }, function (res) {
          if (res.err_msg === 'openExistedChatWithMsg:ok') {
            console.log('打开群成功');
          } else {
            if (isMac) {
              setMacWarnModalVisible(true);
            } else {
              wx.invoke('updateEnterpriseChat', {
                chatId: chatId,
                userIdsToAdd: loginUserOpenId
              }, function (res) {
                console.log(chatId);

                if (res.err_msg == 'updateEnterpriseChat:ok') {
                  wx.invoke('openExistedChatWithMsg', {
                    chatId: chatId
                  }, function (res) {
                    if (res.err_msg == 'openExistedChatWithMsg:ok') {
                      console.log('打开群成功');
                    }
                  });
                } else {
                  if (userId === principalUser.userId) {
                    setPrincipalUserModalVisible(true);
                  } else {
                    setMemberVisible(true);
                  }
                }
              });
            }
          }
        });
      } else {
        setCreateWechatVisible(true);
      }
    }

    if (window.titaTracker) {
      window.titaTracker("action").record({
        productName: "企业微信群聊",
        actionGroup: "".concat(objType === 62 ? '目标' : '任务', "-\u70B9\u51FB\u4F01\u4E1A\u5FAE\u4FE1\u7FA4\u804A\u56FE\u6807"),
        actionName: "".concat(objType === 62 ? '目标' : '任务', "-\u70B9\u51FB\u4F01\u4E1A\u5FAE\u4FE1\u7FA4\u804A\u56FE\u6807")
      });
    }
  };

  var closeCreateWeChatModal = function closeCreateWeChatModal() {
    setCreateWechatVisible(false);
  }; //创建群聊or打开群聊


  var handleCreateGroupChat = function handleCreateGroupChat() {
    wx.invoke('createChatWithMsg', {
      selectedOpenUserIds: weChatGroupMember,
      chatName: "\u300C".concat(apply, "\u7FA4\u300D").concat(name),
      msg: {
        msgtype: 'link',
        link: {
          title: name,
          desc: '',
          url: url,
          imgUrl: 'https://club.tita.com/wp-content/uploads/2022/03/1648725106-20220331191146996.png'
        }
      }
    }, function (res) {
      if (res.err_msg === 'createChatWithMsg:ok') {
        if (res.chatId) {
          (0, _request.rpost)('v1')('chat/add', {
            objId: id,
            objType: objType,
            chatId: res.chatId
          });
          wx.invoke('openExistedChatWithMsg', {
            chatId: res.chatId
          });
        }
      }
    });
    setCreateWechatVisible(false);
    setPrincipalUserModalVisible(false);
  };

  var handleKnowMacWarn = function handleKnowMacWarn() {
    setMacWarnModalVisible(false);
  };

  var closeprincipalUserModal = function closeprincipalUserModal() {
    setPrincipalUserModalVisible(false);
  };

  var handleMemberVisible = function handleMemberVisible() {
    setMemberVisible(false);
  }; //chatId 为null表示未创建群聊 chatId为默认值chatId表示不是企业微信工作台，可能是其他浏览器等 chatId有值，表示创建了群聊


  (0, _react.useEffect)(function () {
    if (isDingDing) {
      return;
    } else {
      (0, _request.rpost)('v1')('chat/info', {
        objId: id,
        objType: objType
      }).then(function (res) {
        if (res.Message === '没有权限') {
          setIsShowWeChat(false);
          return;
        } else {
          setIsShowWeChat(true);

          if (res.Data.obj) {
            setIsHasGroup(true);
          }

          if (isWx) {
            console.log(res.Data.obj);
            setChatId(res.Data.obj);
            (0, _request.rpost)('v1')('chat/users', {
              objId: id,
              objType: objType
            }).then(function (res) {
              setWeChatGroupMember(res.Data.openUserIds);
              setUrl(res.Data.link);
            });
            (0, _request.rpost)('v1')('chat/user', {
              objId: id,
              objType: objType
            }).then(function (res) {
              setLoginUserOpenId(res.Data.obj);
            });
          } else {
            setIsShowWeChat(true);
            return;
          }
        }
      });
    }
  }, [chatId]);
  (0, _react.useEffect)(function () {
    if (isShowWeChat && chatId === null) {
      setTooltip((0, _getLocale.getLocale)('OKR_Db_ClickWeComg'));
    } else if (isShowWeChat && chatId !== null && chatId !== 'chatId') {
      setTooltip('进入群聊');
    } else if (isShowWeChat && chatId === 'chatId') {
      setTooltip('浏览器不支持此功能，请到企业微信工作台中使用');
    }
  }, [chatId, isShowWeChat]);
  (0, _react.useEffect)(function () {
    if (objType === 62) {
      setApply('目标');
    } else {
      setApply('任务');
    }
  }, []);
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
    overlay: tooltip,
    placement: "bottom"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])(preCls, _defineProperty({}, "".concat(preCls, "__chat"), isHasGroup), _defineProperty({}, 'tu-icon-qw-chat', isShowWeChat)),
    onMouseDown: handleClickWechatBtn
  })), /*#__PURE__*/_react["default"].createElement(_dialogConfirm["default"], {
    zIndex: 1200,
    visible: createWechatVisible,
    type: "warning"
  }, /*#__PURE__*/_react["default"].createElement("span", {
    type: "title"
  }, "\u786E\u5B9A\u53D1\u8D77\u7FA4\u804A\u5417"), /*#__PURE__*/_react["default"].createElement("span", {
    type: "content"
  }, "\u53EF\u9009\u62E9".concat(apply, "\u76F8\u5173\u4EBA\u5458\u5FEB\u901F\u5EFA\u7FA4\u6C9F\u901A\u3002\u6CE8\u610F\uFF0C\u81F3\u5C11\u9009\u62E9 3 \u4EBA\uFF0C\u624D\u80FD\u6B63\u5E38\u53D1\u8D77\u7FA4\u804A\u3002")), /*#__PURE__*/_react["default"].createElement(_dialogConfirm.CancelButton, {
    type: "button",
    onClick: closeCreateWeChatModal
  }, "\u53D6\u6D88"), /*#__PURE__*/_react["default"].createElement(_dialogConfirm.SureButton, {
    type: "button",
    onClick: handleCreateGroupChat
  }, "\u53D1\u8D77\u7FA4\u804A")), /*#__PURE__*/_react["default"].createElement(_dialogConfirm["default"], {
    zIndex: 1200,
    visible: macWarnModalVisible,
    type: "warning"
  }, /*#__PURE__*/_react["default"].createElement("span", {
    type: "title"
  }, "\u8BF7\u6CE8\u610F"), /*#__PURE__*/_react["default"].createElement("span", {
    type: "content"
  }, "\u8BE5\u4F01\u4E1A\u5FAE\u4FE1\u7248\u672C\u4E0D\u652F\u6301\u81EA\u52A8\u52A0\u5165\uFF0C\u8BF7\u8054\u7CFB".concat(apply, "\u8D1F\u8D23\u4EBA\u624B\u52A8\u52A0\u4F60\u5165\u7FA4")), /*#__PURE__*/_react["default"].createElement(_dialogConfirm.SureButton, {
    type: "button",
    onClick: handleKnowMacWarn
  }, "\u6211\u77E5\u9053\u4E86")), /*#__PURE__*/_react["default"].createElement(_dialogConfirm["default"], {
    zIndex: 1200,
    visible: principalUserModalVisible,
    type: "warning"
  }, /*#__PURE__*/_react["default"].createElement("span", {
    type: "title"
  }, "\u8BF7\u6CE8\u610F"), /*#__PURE__*/_react["default"].createElement("span", {
    type: "content"
  }, "\u4F60\u4E0D\u5728\u7FA4\u91CC\u6216\u8BE5\u7FA4\u5DF2\u89E3\u6563\u3002\u53EF\u4EE5\u8054\u7CFB".concat(apply, "\u6210\u5458\u62C9\u4F60\u5165\u7FA4\u3002\u4F60\u4E5F\u53EF\u4EE5\u91CD\u65B0\u5EFA\u7FA4\u3002")), /*#__PURE__*/_react["default"].createElement(_dialogConfirm.CancelButton, {
    type: "button",
    onClick: closeprincipalUserModal
  }, "\u53D6\u6D88"), /*#__PURE__*/_react["default"].createElement(_dialogConfirm.SureButton, {
    type: "button",
    onClick: handleCreateGroupChat
  }, "\u53D1\u8D77\u7FA4\u804A")), /*#__PURE__*/_react["default"].createElement(_dialogConfirm["default"], {
    zIndex: 1200,
    visible: memberVisible,
    type: "warning"
  }, /*#__PURE__*/_react["default"].createElement("span", {
    type: "title"
  }, "\u8BF7\u6CE8\u610F"), /*#__PURE__*/_react["default"].createElement("span", {
    type: "content"
  }, "\u4F60\u4E0D\u5728\u7FA4\u91CC\u6216\u8BE5\u7FA4\u5DF2\u89E3\u6563\u3002\u53EF\u4EE5\u8054\u7CFB".concat(apply, "\u6210\u5458\u62C9\u4F60\u5165\u7FA4\u3002")), /*#__PURE__*/_react["default"].createElement(_dialogConfirm.SureButton, {
    type: "button",
    onClick: handleMemberVisible
  }, "\u6211\u77E5\u9053\u4E86")));
};

var _default = WeChatBtn;
exports["default"] = _default;