"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"));

require("dingtalk-jsapi/entry/union");

var _coolAppSdk = require("dingtalk-jsapi/plugin/coolAppSdk");

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

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

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

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

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

var _helpers = require("../../utils/helpers");

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-dingding-btn';
var userId = (0, _bsGlobal.getUserInfo)().Id;
var dingdingSource = 861;
var isDingDing = (0, _bsGlobal.getSource)() === 861;

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

  var _useState = (0, _react.useState)(''),
      _useState2 = _slicedToArray(_useState, 2),
      coolAppCode = _useState2[0],
      setCoolAppCode = _useState2[1];

  var _useState3 = (0, _react.useState)(''),
      _useState4 = _slicedToArray(_useState3, 2),
      suiteKey = _useState4[0],
      setSuiteKey = _useState4[1];

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

  var _useState7 = (0, _react.useState)(false),
      _useState8 = _slicedToArray(_useState7, 2),
      isShowDingChat = _useState8[0],
      setIsShowDingChat = _useState8[1];

  var _useState9 = (0, _react.useState)([]),
      _useState10 = _slicedToArray(_useState9, 2),
      dingChatGroupMember = _useState10[0],
      setDingChatGroupMember = _useState10[1];

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

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

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

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

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

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

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

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

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

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

  var isWx = navigator.userAgent.match(/wxwork/);
  var isMac = navigator.userAgent.match(/Mac/);
  var appId = (0, _helpers.getTenantInfo)().suiteAppId;

  var handleClickWechatBtn = function handleClickWechatBtn() {
    if (isDingDing) {
      //有群了，判断没在群就先进群再打开群
      if (chatId !== null && chatId !== 'chatId') {// addMembers({
        //   context: {
        //     coolAppCode: coolAppCode, //酷应用的编码
        //     clientId: suiteKey, // 应用标识
        //     corpId: corpId, // 根据对应场景获取 corpId
        //   },
        //   openConversationList: [chatId], //要添加成员的的群ID
        //   userIds: dingChatGroupMember, //需要入群的成员userId。
        // })
        //   .then((res) => {
        //     console.log(res, 'addMembers')
        //     if (res.errorCode === '0') {
        //       console.log("添加成功res"+ JSON.stringify(res))
        //     } else {
        //       // if (userId === principalUser.userId) {
        //       //   setPrincipalUserModalVisible(true)
        //       // } else {
        //       //   setMemberVisible(true)
        //       // }
        //     }
        //   })
        //   .catch((e) => {
        //     console.log('添加失败' + JSON.stringify(e))
        //   })
      } else {
        setCreateDingchatVisible(true);
      }
    }
  };

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


  var handleCreateGroupChat = function handleCreateGroupChat() {
    (0, _coolAppSdk.createGroup)({
      context: {
        coolAppCode: coolAppCode,
        clientId: suiteKey,
        corpId: corpId // 根据对应场景获取 corpId

      },
      title: "\u300C".concat(apply, "\u7FA4\u300D").concat(name),
      memberUserIds: dingChatGroupMember
    }).then(function (res) {
      if (res.errorCode === '0') {
        // 建群成功
        if (res.detail.openConversationId) {
          // 创建的群id
          (0, _request.rpost)('v1')('chat/add', {
            objId: id,
            objType: objType,
            chatId: res.detail.openConversationId,
            SourceTye: dingdingSource
          });
          setChatId(res.detail.openConversationId);
        }
      }
    })["catch"](function (e) {// 用户主动退出安装
    });
    setCreateDingchatVisible(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,
        SourceTye: dingdingSource
      }).then(function (res) {
        if (res.Message === '没有权限') {
          setIsShowDingChat(false);
          return;
        } else {
          setIsShowDingChat(true);

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

          if (isDingDing) {
            setChatId(res.Data.obj);
            (0, _request.rpost)('v1')('chat/users', {
              objId: id,
              objType: objType,
              SourceTye: dingdingSource
            }).then(function (res) {
              var _res$Data = res.Data,
                  CoolAppCode = _res$Data.CoolAppCode,
                  SuiteKey = _res$Data.SuiteKey,
                  CorpId = _res$Data.CorpId;
              setCoolAppCode(CoolAppCode);
              setSuiteKey(SuiteKey);
              setCorpId(CorpId);
              setDingChatGroupMember(res.Data.openUserIds);
              setUrl(res.Data.link);
            });
            (0, _request.rpost)('v1')('chat/user', {
              objId: id,
              objType: objType,
              SourceTye: dingdingSource
            }).then(function (res) {
              setLoginUserOpenId(res.Data.obj);
            });
          } else {
            setIsShowDingChat(true);
            return;
          }
        }
      });
    }
  }, [chatId]);
  (0, _react.useEffect)(function () {
    if (isShowDingChat && chatId === null) {
      setTooltip('点击一键发起钉钉群聊');
    } else if (isShowDingChat && chatId !== null && chatId !== 'chatId') {
      setTooltip("\u9489\u9489\u7FA4\u804A\u540D\u79F0:\u300C".concat(apply, "\u7FA4\u300D").concat(name));
    } else if (isShowDingChat && chatId === 'chatId') {
      setTooltip('浏览器不支持此功能，请到钉钉工作台中使用');
    }
  }, [chatId, isShowDingChat]);
  (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({}, "".concat(preCls, "__img"), isShowDingChat)),
    onMouseDown: handleClickWechatBtn
  })), /*#__PURE__*/_react["default"].createElement(_dialogConfirm["default"], {
    zIndex: 1200,
    visible: createDingchatVisible,
    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")), /*#__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\u9489\u9489\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 = DingdingBtn;
exports["default"] = _default;