"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 _input = _interopRequireDefault(require("../input"));

var _utils = require("../../../../utils");

var _checkbox = _interopRequireDefault(require("../../../../../checkbox"));

var _dropSelect = _interopRequireDefault(require("../drop-select"));

var _verifyCode = _interopRequireDefault(require("../verify-code"));

var _checkbox2 = _interopRequireDefault(require("../checkbox"));

var _phone = _interopRequireDefault(require("../phone"));

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

var _constant = require("../../../../constant");

var _scrollbar = _interopRequireDefault(require("../../../../../scrollbar"));

var _conditionRender = _interopRequireDefault(require("../../../../../condition-render"));

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

require("./index.css");

var _window$BSGlobal, _window$BSGlobal$logi, _window$BSGlobal2, _window$BSGlobal2$ten, _window$BSGlobal3, _window$BSGlobal3$ten, _window$BSGlobal4, _window$BSGlobal4$log, _window$BSGlobal5, _window$BSGlobal5$log, _window$BSGlobal6, _window$BSGlobal6$ten;

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 _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

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

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

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

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

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

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-book-demo-pc-content";
var uname = ((_window$BSGlobal = window.BSGlobal) === null || _window$BSGlobal === void 0 ? void 0 : (_window$BSGlobal$logi = _window$BSGlobal.loginUserInfo) === null || _window$BSGlobal$logi === void 0 ? void 0 : _window$BSGlobal$logi.Name) || "";
var uid = ((_window$BSGlobal2 = window.BSGlobal) === null || _window$BSGlobal2 === void 0 ? void 0 : (_window$BSGlobal2$ten = _window$BSGlobal2.tenantInfo) === null || _window$BSGlobal2$ten === void 0 ? void 0 : _window$BSGlobal2$ten.Id) || "";
var Source = ((_window$BSGlobal3 = window.BSGlobal) === null || _window$BSGlobal3 === void 0 ? void 0 : (_window$BSGlobal3$ten = _window$BSGlobal3.tenantInfo) === null || _window$BSGlobal3$ten === void 0 ? void 0 : _window$BSGlobal3$ten.Source) || (0, _utils.getSource)();
var lname = ((_window$BSGlobal4 = window.BSGlobal) === null || _window$BSGlobal4 === void 0 ? void 0 : (_window$BSGlobal4$log = _window$BSGlobal4.loginUserInfo) === null || _window$BSGlobal4$log === void 0 ? void 0 : _window$BSGlobal4$log.Name) || "";
var lmobile = ((_window$BSGlobal5 = window.BSGlobal) === null || _window$BSGlobal5 === void 0 ? void 0 : (_window$BSGlobal5$log = _window$BSGlobal5.loginUserInfo) === null || _window$BSGlobal5$log === void 0 ? void 0 : _window$BSGlobal5$log.Mobile) || "";
var lcompany = ((_window$BSGlobal6 = window.BSGlobal) === null || _window$BSGlobal6 === void 0 ? void 0 : (_window$BSGlobal6$ten = _window$BSGlobal6.tenantInfo) === null || _window$BSGlobal6$ten === void 0 ? void 0 : _window$BSGlobal6$ten.Name) || "";

var BookDemoPCContent = function BookDemoPCContent(_ref) {
  var type = _ref.type,
      onSubmitSuccess = _ref.onSubmitSuccess,
      _ref$source = _ref.source,
      source = _ref$source === void 0 ? 0 : _ref$source,
      onChange = _ref.onChange;

  var _useState = (0, _react.useState)((0, _utils.getTypeData)(type)),
      _useState2 = _slicedToArray(_useState, 2),
      data = _useState2[0],
      setData = _useState2[1];

  var _useState3 = (0, _react.useState)(false),
      _useState4 = _slicedToArray(_useState3, 2),
      isFormOverflow = _useState4[0],
      setIsFormOverflow = _useState4[1];

  var _useState5 = (0, _react.useState)(false),
      _useState6 = _slicedToArray(_useState5, 2),
      isAggrePrivacy = _useState6[0],
      setIsAggrePrivacy = _useState6[1];

  var _useState7 = (0, _react.useState)(true),
      _useState8 = _slicedToArray(_useState7, 2),
      hasErr = _useState8[0],
      setHasErr = _useState8[1];

  var _useState9 = (0, _react.useState)(false),
      _useState10 = _slicedToArray(_useState9, 2),
      isLoading = _useState10[0],
      setIsLoading = _useState10[1];

  var _useState11 = (0, _react.useState)([]),
      _useState12 = _slicedToArray(_useState11, 2),
      result = _useState12[0],
      setResult = _useState12[1];

  var formRef = (0, _react.useRef)(document.createElement("div"));

  var handleChangeAggrePrivacyValue = function handleChangeAggrePrivacyValue(value) {
    setIsAggrePrivacy(value);
  };

  var handleValueChange = function handleValueChange(name, id, value, hasError, other) {
    var index = result.findIndex(function (item) {
      return item.name === name;
    });
    result[index].value = value;
    result[index].hasErr = hasError;

    if (id === "verificationCode") {
      result[index].yzmGuid = other.yzmGuid;
      result[index].handelChangeImage = other.handelChangeImage;
    }

    setResult(_toConsumableArray(result));

    if (onChange) {
      onChange(result);
    }
  };

  var emptyFun = function emptyFun() {};

  var handleCommit = function handleCommit() {
    if (hasErr || isLoading) return;
    setIsLoading(true);
    var verificationData = result.filter(function (item) {
      return item.type === "verificationCode";
    })[0];
    var yzmGuidVal = verificationData.yzmGuid || "";
    var handelChangeImage = verificationData.handelChangeImage || emptyFun;
    var setErrMsg = verificationData.setErrMsg || emptyFun;
    var content = uid ? "\u79DF\u6237ID\uFF1A".concat(uid, "\uFF0C\u79DF\u6237\u8D26\u53F7\u540D\u79F0\uFF1A").concat(uname, ",") : "";
    result.forEach(function (item) {
      if (typeof item.value === "string") {
        content += "".concat(item.name, ": ").concat(item.value, ",");
      } else {
        var tempValue = "";
        Object.values(item.value).forEach(function (value) {
          if (value.isSelected) {
            tempValue += "".concat(value.text, ",");
          }
        });
        tempValue = tempValue.slice(0, tempValue.length - 1);
        content += "".concat(item.name, ": ").concat(tempValue, ",");
      }
    });
    content = content.slice(0, content.length - 1);
    (0, _request.sendEmailBookDemo)({
      title: "预约演示",
      content: "".concat(content, "   @fromNew."),
      code: verificationData.value,
      yzmGuidVal: yzmGuidVal.indexOf("?") !== -1 ? yzmGuidVal.slice(0, yzmGuidVal.indexOf("?")) : yzmGuidVal,
      source: source > 0 ? source : Source
    }).then(function (res) {
      if (res.data.Code) {
        (0, _request.sendBookDemoJson)((0, _utils.bookDemoTransformDataToJson)(result, source > 0 ? source : Source, _constant.DemoTypeTextMap[type], content, uid));

        _toast["default"].Success("提交成功");

        if (onSubmitSuccess) {
          onSubmitSuccess();
        }

        localStorage.setItem("isSubmitted", "1");
        var trickerContent = _constant.trackerInfo[type];

        if (window.titaTracker && !localStorage.getItem("titaccc")) {
          window.titaTracker("action").record(_objectSpread({
            actionName: "提交预约演示",
            productName: "预约演示"
          }, trickerContent));
        }
      } else {
        setErrMsg(res.data.Message);

        _toast["default"].Warning(res.data.Message, {
          style: {
            position: "fixed"
          },
          canClose: false
        });
      }

      handelChangeImage();
    })["catch"](function (error) {
      _toast["default"].Error(error, {
        style: {
          position: "fixed"
        },
        canClose: false
      });
    })["finally"](function () {
      setIsLoading(false);
    });
  };

  var renderItem = function renderItem(item) {
    switch (item.type) {
      case "text":
        return /*#__PURE__*/_react["default"].createElement(_input["default"], _extends({}, item, {
          onChange: handleValueChange
        }));

      case "phone":
        return /*#__PURE__*/_react["default"].createElement(_phone["default"], _extends({}, item, {
          onChange: handleValueChange
        }));

      case "dropSelect":
        return /*#__PURE__*/_react["default"].createElement(_dropSelect["default"], _extends({}, item, {
          onChange: handleValueChange
        }));

      case "checkbox":
        return /*#__PURE__*/_react["default"].createElement(_checkbox2["default"], _extends({}, item, {
          onChange: handleValueChange
        }));

      case "verificationCode":
        return /*#__PURE__*/_react["default"].createElement(_verifyCode["default"], _extends({}, item, {
          onChange: handleValueChange
        }));

      default:
        return /*#__PURE__*/_react["default"].createElement("span", null);
    }
  };

  (0, _react.useEffect)(function () {
    var resultHasErr = !isAggrePrivacy || result.filter(function (item) {
      return item.required && item.hasErr;
    }).length > 0;
    setHasErr(resultHasErr);
  }, [result, isAggrePrivacy]);
  (0, _react.useEffect)(function () {
    setTimeout(function () {
      if (formRef.current.offsetHeight > 366) {
        setIsFormOverflow(true);
      }
    }, 0);
    var formField = data.formField.map(function (item) {
      if (item.id === "username") {
        return _objectSpread(_objectSpread({}, item), {}, {
          value: lname,
          hasErr: !lname
        });
      }

      if (item.id === "phone") {
        return _objectSpread(_objectSpread({}, item), {}, {
          value: lmobile,
          hasErr: !lmobile
        });
      }

      if (item.id === "tenantName") {
        return _objectSpread(_objectSpread({}, item), {}, {
          value: lcompany,
          hasErr: !lcompany
        });
      }

      return item;
    });
    data.formField = formField;
    setData(_objectSpread({}, data));
    setResult(formField.map(function (item) {
      return {
        name: item.name,
        value: item.type === "dropSelect" ? item.option[0].text : item.value,
        id: item.id,
        hasErr: !(item.value || item.type === "dropSelect"),
        required: item.required,
        type: item.type,
        multiSelect: item.multiSelect
      };
    }));
    var trickerContent = _constant.trackerInfo[type];

    if (window.titaTracker && !localStorage.getItem("titaccc")) {
      window.titaTracker("action").record({
        actionName: "点开预约演示",
        productName: "预约演示",
        actionGroup: trickerContent.actionGroup
      });
    }
  }, []);
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: preCls
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__left")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__left-title")
  }, data.title), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__left-desc")
  }, data.desc), /*#__PURE__*/_react["default"].createElement("img", {
    className: "".concat(preCls, "__left-img"),
    alt: "\u9884\u7EA6\u6F14\u793A",
    src: data.img
  })), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__right")
  }, /*#__PURE__*/_react["default"].createElement(_scrollbar["default"], {
    style: {
      maxHeight: "366px"
    }
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(preCls, "__right-form")),
    ref: formRef
  }, data.formField.map(function (item) {
    return renderItem(item);
  }))), /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])(_defineProperty({}, "".concat(preCls, "__right-commit--shadow"), isFormOverflow))
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(preCls, "__right-commit"))
  }, /*#__PURE__*/_react["default"].createElement("button", {
    type: "button",
    className: (0, _classnames["default"])("".concat(preCls, "__right-commit-btn"), _defineProperty({}, "".concat(preCls, "__right-commit-btn--disabled"), hasErr || isLoading)),
    onClick: handleCommit
  }, "\u63D0\u4EA4", /*#__PURE__*/_react["default"].createElement(_conditionRender["default"], {
    condition: isLoading
  }, /*#__PURE__*/_react["default"].createElement("span", null, "\u4E2D\u3002\u3002\u3002"))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__privacy")
  }, /*#__PURE__*/_react["default"].createElement(_checkbox["default"], {
    onChange: handleChangeAggrePrivacyValue
  }), /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(preCls, "__privacy-aggre")
  }, "\u6211\u5DF2\u9605\u8BFB\u5E76\u540C\u610F "), /*#__PURE__*/_react["default"].createElement("a", {
    href: "https://okr.tita.com/#/privacy",
    target: "_blank",
    className: "".concat(preCls, "__privacy-link"),
    rel: "noreferrer"
  }, "\u300A\u9690\u79C1\u653F\u7B56\u300B"), "\u548C", /*#__PURE__*/_react["default"].createElement("a", {
    target: "_blank",
    className: "".concat(preCls, "__privacy-link"),
    href: "https://okr.tita.com/#/userAgreement",
    rel: "noreferrer"
  }, "\u300A\u7528\u6237\u670D\u52A1\u534F\u8BAE\u300B")))));
};

BookDemoPCContent.defaultProps = {
  source: 0,
  onChange: function onChange() {},
  onSubmitSuccess: function onSubmitSuccess() {}
};
var _default = BookDemoPCContent;
exports["default"] = _default;