"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.PayDialog = PayDialog;
exports.SubmitDialog = SubmitDialog;

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

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

var _titaUi = require("tita-ui");

var _network = require("../server/network");

var _toast = _interopRequireDefault(require("../../toast"));

var _dialog = _interopRequireDefault(require("../../dialog"));

var _form = _interopRequireDefault(require("../../form"));

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

var _payBackgroundImg = _interopRequireDefault(require("../image/payBackgroundImg.png"));

var _submitLogo = _interopRequireDefault(require("../image/submitLogo.svg"));

var _wxPay = _interopRequireDefault(require("../image/wx-pay.svg"));

var _aliPay = _interopRequireDefault(require("../image/ali-pay.svg"));

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 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 _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 Fields = _form["default"].Fields;
var precls = 'okr-cases-library__pay-window';

function SubmitDialog(props) {
  var handleShowSubmitOkrWindow = props.handleShowSubmitOkrWindow,
      isShowSubmitOkrWindow = props.isShowSubmitOkrWindow;

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

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

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

  var formRef = (0, _react.useRef)();

  var onSubmitButtonClick = function onSubmitButtonClick() {
    var body = {
      type: type,
      position: job,
      scene: scene
    }; // 校验

    var err = formRef.current.verifing({
      truonlyFirstErrore: false
    });

    if (!err.length) {
      (0, _network.postSurvey)(body).then(function () {
        _toast["default"].Success('发送成功');

        handleShowSubmitOkrWindow(false);
      })["catch"](function () {
        _toast["default"].Warning('发送失败');
      });
    }
  };

  return /*#__PURE__*/_react["default"].createElement(_dialog["default"], {
    visible: isShowSubmitOkrWindow,
    noFooter: true,
    width: "480px",
    destroyOnClose: true,
    noCloseIcon: true,
    getContainer: function getContainer() {
      return document.body;
    },
    zIndex: 1200
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "okr-cases-library__submitWindow"
  }, /*#__PURE__*/_react["default"].createElement("img", {
    src: _submitLogo["default"],
    alt: "submit\u5C0F\u9A74"
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "tu-icon-canceled",
    onClick: function onClick() {
      return handleShowSubmitOkrWindow(false);
    }
  }), /*#__PURE__*/_react["default"].createElement(_form["default"], {
    ref: formRef
  }, /*#__PURE__*/_react["default"].createElement(Fields.Input, {
    name: "type",
    label: "OKR \u7684\u7C7B\u578B",
    placeholder: "\u5982\u9500\u552E\u56E2\u961F",
    require: true,
    verifies: [{
      tip: 'OKR类型不能为空',
      test: /\S/
    }],
    onChange: setType
  }), /*#__PURE__*/_react["default"].createElement(Fields.Input, {
    name: "job",
    label: "OKR \u7684\u5C97\u4F4D",
    placeholder: "\u5982\u9500\u552EVP",
    require: true,
    verifies: [{
      tip: 'OKR岗位不能为空',
      test: /\S/
    }],
    onChange: setJob
  }), /*#__PURE__*/_react["default"].createElement(Fields.Textarea, {
    name: "scene",
    label: "OKR \u5E94\u7528\u573A\u666F",
    placeholder: "\u5982\u9500\u552EVP\u9488\u5BF9 \u300C\u5982\u4F55\u7BA1\u7406\u597D\u56E2\u961F\u300D\u8FD9\u4E2A\u95EE\u9898\uFF0C\u5E94\u8BE5\u521B\u5EFA\u600E\u6837\u7684 \u76EE\u6807\u53CA\u5173\u952E\u6210\u679C",
    require: false,
    onChange: setScene,
    resizeType: "none",
    areaHeight: 96
  })), /*#__PURE__*/_react["default"].createElement("div", {
    className: "okr-cases-library__submitWindow-submitButton",
    onClick: onSubmitButtonClick
  }, (0, _getLocale.getLocale)('Pro_detail_Submission'))));
}

function PayDialog(props) {
  var isShowPayWindow = props.isShowPayWindow,
      handleShowPayWindow = props.handleShowPayWindow;
  var getOrderInfoTimers = (0, _react.useRef)(0);

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

  var _useState9 = (0, _react.useState)(function () {
    // @ts-ignore
    var Version = window.BSGlobal.tenantAuthentication.Version; // @ts-ignore

    // @ts-ignore
    var tenantType = window.BSGlobal.tenantInfo.tenantType; // 外部注冊賬號使用的產品ID不同

    // 外部注冊賬號使用的產品ID不同
    if (Version === 1 && tenantType === 3) return 'D9E059E4-4303-4EE2-9275-AE2FA74BBAA6';
    return '60AFAD35-5273-4A06-B2F4-9A3193096BE7';
  }),
      _useState10 = _slicedToArray(_useState9, 1),
      packageId = _useState10[0];

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

  var _useState13 = (0, _react.useState)('wxPay'),
      _useState14 = _slicedToArray(_useState13, 2),
      payCode = _useState14[0],
      setPayCode = _useState14[1];

  var _useState15 = (0, _react.useState)('微信'),
      _useState16 = _slicedToArray(_useState15, 2),
      payName = _useState16[0],
      setPayName = _useState16[1];

  var _useState17 = (0, _react.useState)({
    PayCode: 'directPay',
    PayName: '支付宝'
  }),
      _useState18 = _slicedToArray(_useState17, 2),
      wxModel = _useState18[0],
      setWxModel = _useState18[1];

  var _useState19 = (0, _react.useState)({
    PayCode: 'wxPay',
    PayName: '微信'
  }),
      _useState20 = _slicedToArray(_useState19, 2),
      aliModel = _useState20[0],
      setAliModel = _useState20[1];

  (0, _react.useEffect)(function () {
    // 获取OKR产品信息
    (0, _network.getOkrCaseProducts)(packageId).then(function (products) {
      if (!products.length) return;
      var _products$ = products[0],
          productId = _products$.Id,
          priceY = _products$.priceY,
          name = _products$.name;
      setPrice(priceY); // 获取订单信息

      (0, _network.postOkrCasesOrder)({
        PackageId: packageId,
        Description: name,
        Products: [{
          ProductId: productId,
          Total: 1
        }]
      }).then(function (orderInfo) {
        var Id = orderInfo.Id,
            AliModel = orderInfo.AliModel,
            WxModel = orderInfo.WxModel;
        setWxModel(WxModel);
        setAliModel(AliModel);
        setOrderId(Id);
      });
    });
  }, []); // 点击立即支付后，2分钟内，每个10s，循环获取订单信息

  var loopOrderInfo = function loopOrderInfo(id) {
    if (getOrderInfoTimers.current === 12) {
      getOrderInfoTimers.current = 1;
    }

    setTimeout(function () {
      // 循环获取订单信息 2 分钟
      if (getOrderInfoTimers.current < 12) {
        (0, _network.getOkrOrderInfo)(id).then(function (res) {
          getOrderInfoTimers.current += 1; // @ts-ignore

          var OrderStatus = res.OrderStatus; // 未支付成功重新获取订单

          if (OrderStatus !== 2) {
            loopOrderInfo(id);
          } else {
            // 订单已支付
            _titaUi.Modal.success({
              title: '支付成功',
              content: 'OKR案例库已开通',
              okText: '立即使用',
              onOk: function () {
                var _onOk = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
                  return regeneratorRuntime.wrap(function _callee$(_context) {
                    while (1) {
                      switch (_context.prev = _context.next) {
                        case 0:
                          // 跳转页面
                          window.location.reload();

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

                function onOk() {
                  return _onOk.apply(this, arguments);
                }

                return onOk;
              }()
            });
          }
        });
      }
    }, 10 * 1000); // 10s
  };

  var onPayOrderChange = function onPayOrderChange(orderModel) {
    var PayCode = orderModel.PayCode,
        PayName = orderModel.PayName;
    setPayCode(PayCode);
    setPayName(PayName);
  };

  var clickPayNowHandler = function clickPayNowHandler(e) {
    if (payCode === 'wxPay') {
      e.preventDefault();
      var path = window.location.href.split('#')[0];
      path = path.replace(/eLearningHome/, 'Home');
      var encode = encodeURIComponent("orderId=".concat(orderId, "&payCode=").concat(payCode, "&payName=").concat(payName)); // if(isDingDing()){
      // window.open(`${path}#/pay?${encode}`, "_self");
      // window.location.reload();
      // }else{

      window.open("".concat(path, "#/pay?").concat(encode), '_blank'); // }
      // postWxPayOrder({
      //   order_id: orderId,
      //   default_bank: payCode,
      //   default_bank_name: payName,
      // }).then((res) => {
      //   window.open(res, '_blank')
      // })
    }

    loopOrderInfo(orderId);
  };

  return /*#__PURE__*/_react["default"].createElement(_dialog["default"], {
    visible: isShowPayWindow,
    noFooter: true,
    width: "480px",
    destroyOnClose: true,
    noCloseIcon: true,
    getContainer: function getContainer() {
      return document.body;
    }
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: precls
  }, /*#__PURE__*/_react["default"].createElement("img", {
    src: _payBackgroundImg["default"],
    alt: "\u652F\u4ED8\u80CC\u666F\u6D6E\u51FA",
    className: "".concat(precls, "__bg-img")
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "tu-icon-canceled",
    onClick: function onClick() {
      return handleShowPayWindow(false);
    },
    style: {
      width: '18px',
      height: '18px'
    }
  }), /*#__PURE__*/_react["default"].createElement("p", {
    className: "".concat(precls, "__head")
  }, price, " \u8D2D\u4E70\u5343\u4EFD OKR \u6848\u4F8B\u5E93"), /*#__PURE__*/_react["default"].createElement("p", {
    className: "".concat(precls, "__detail")
  }, "\u53EF\u67E5\u770B \u4F7F\u7528\u6848\u4F8B\u5E93\u6240\u6709\u884C\u4E1A\u7684\u6848\u4F8B", /*#__PURE__*/_react["default"].createElement("a", {
    href: "https://club.tita.com/okr-examples",
    target: "_blank",
    rel: "noreferrer"
  }, (0, _getLocale.getLocale)('Mod_Checkdetails'))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(precls, "__amount")
  }, "\u5E94\u4ED8\u91D1\u989D\uFF1A", /*#__PURE__*/_react["default"].createElement("b", null, /*#__PURE__*/_react["default"].createElement("span", {
    style: {
      fontSize: '32px'
    }
  }, "29.8"), "\u5143/\u5E74")), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(precls, "__type")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(precls, "__commit-order"), "".concat(precls, "__commit-order--wx"), _defineProperty({}, "".concat(precls, "__commit-order--active"), payCode === (wxModel === null || wxModel === void 0 ? void 0 : wxModel.PayCode))),
    onClick: function onClick() {
      return onPayOrderChange(wxModel);
    }
  }, /*#__PURE__*/_react["default"].createElement("img", {
    src: _wxPay["default"],
    alt: "",
    width: 20,
    style: {
      marginRight: 4
    }
  }), "\u5FAE\u4FE1\u652F\u4ED8"), /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(precls, "__commit-order"), _defineProperty({}, "".concat(precls, "__commit-order--active"), payCode === (aliModel === null || aliModel === void 0 ? void 0 : aliModel.PayCode))),
    onClick: function onClick() {
      return onPayOrderChange(aliModel);
    }
  }, /*#__PURE__*/_react["default"].createElement("img", {
    src: _aliPay["default"],
    alt: "",
    width: 20,
    style: {
      marginRight: 4
    }
  }), "\u652F\u4ED8\u5B9D\u652F\u4ED8")), /*#__PURE__*/_react["default"].createElement("a", {
    className: "".concat(precls, "__payButton"),
    onClick: clickPayNowHandler,
    href: "/app/payorder?orderid=".concat(orderId, "&mobile=13552865071&defcode=").concat(payCode, "&defCodeName=").concat(payName, "&IsContactCustomerService=false"),
    target: "_blank",
    rel: "noreferrer"
  }, "\u7ACB\u5373\u652F\u4ED8")));
}