"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _message = _interopRequireDefault(require("@alifd/next/lib/message"));
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _react = _interopRequireWildcard(require("react"));
var _elementReact = require("element-react");
require("element-theme-default");
var _FormPlaceholder = _interopRequireDefault(require("../FormPlaceholder"));
var _base = require("../../../api/base");
var _utils = require("../../../utils/utils");
var _FormUpload = _interopRequireDefault(require("../../../components/XtForm/FormUpload"));
var _indexModule = _interopRequireDefault(require("./index.module.scss"));
require("../../../module/assets/iconfont/xt-icon/xiatu-rich/iconfont.css");
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; }
var FormTplView = /*#__PURE__*/function (_Component) {
  (0, _inheritsLoose2["default"])(FormTplView, _Component);
  function FormTplView(props) {
    var _this;
    _this = _Component.call(this, props) || this;
    _this.getUserIsLogin = function () {
      var pathname = window.location.pathname;
      if (pathname === '/preview.html') {
        // eslint-disable-next-line react/prop-types
        _this.props.triggerWXLogin && _this.props.triggerWXLogin();
      } else {
        _message["default"].error('请先完成登录');
      }
    };
    _this.triggerSubmitSuccess = function () {
      var pathname = window.location.pathname;
      if (pathname === '/preview.html') {
        // eslint-disable-next-line react/prop-types
        _this.props.submitSuccess && _this.props.submitSuccess();
      }
    };
    _this.handleSubmit = function (e) {
      e.preventDefault();
      var _this$state = _this.state,
        form = _this$state.form,
        submited = _this$state.submited,
        isLogin = _this$state.isLogin;
      if (submited) return false;
      if (!isLogin) {
        _this.getUserIsLogin();
        return false;
      }

      // eslint-disable-next-line react/no-string-refs
      _this.refs.form.validate( /*#__PURE__*/function () {
        var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(valid) {
          var _Number, ideaId, submitData, _yield$formSubmit, code;
          return _regenerator["default"].wrap(function _callee$(_context) {
            while (1) switch (_context.prev = _context.next) {
              case 0:
                if (!valid) {
                  _context.next = 8;
                  break;
                }
                ideaId = (_Number = Number(_utils.$_GET.activityId || _utils.$_GET.id)) !== null && _Number !== void 0 ? _Number : 0; // eslint-disable-next-line react/prop-types
                submitData = _this.props.formData.map(function (item, index) {
                  // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
                  var value = form["prop" + (index + 1)];
                  return (0, _extends2["default"])({}, item, {
                    labelKey: item.key,
                    value: Array.isArray(value) ? value : [value]
                  });
                });
                _context.next = 5;
                return (0, _base.formSubmit)({
                  ideaId: ideaId,
                  submitData: submitData
                });
              case 5:
                _yield$formSubmit = _context.sent;
                code = _yield$formSubmit.code;
                if (code === 10200) {
                  _message["default"].success('恭喜：表单提交成功！');
                  _this.setState({
                    submited: !submited
                  });
                  _this.triggerSubmitSuccess();
                }
              case 8:
              case "end":
                return _context.stop();
            }
          }, _callee);
        }));
        return function (_x) {
          return _ref.apply(this, arguments);
        };
      }());
    };
    var _form =
    // eslint-disable-next-line react/prop-types
    props.formData.length ? Object.fromEntries(
    // eslint-disable-next-line react/prop-types
    props.formData.map(function (item, index) {
      return [// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
      "prop" + (index + 1), item.type === 'checkbox' ? [] : ''];
    })) : {};
    var rules =
    // eslint-disable-next-line react/prop-types
    props.formData.length ? Object.fromEntries(
    // eslint-disable-next-line react/prop-types
    props.formData.map(function (item, index) {
      var _item$label;
      var required = (0, _extends2["default"])({
        required: item.required,
        message: ((_item$label = item.label) !== null && _item$label !== void 0 ? _item$label : '暂无选项标题') + "\u4E0D\u80FD\u4E3A\u7A7A",
        trigger: ['blur', 'change']
      }, item.type === 'checkbox' && {
        type: 'array'
      });
      return [// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
      "prop" + (index + 1), item.required && item.pattern ? [(0, _extends2["default"])({}, required), {
        validator: function validator(_, value, callback) {
          var reg = new RegExp(item.pattern.replace(/^\/+|\/+$/g, ''));
          if (!reg.test(value)) callback(new Error("\u8BF7\u8F93\u5165\u6B63\u786E\u7684" + item.label));else callback();
        }
      }] : (0, _extends2["default"])({}, required)];
    })) : {};
    _this.state = {
      form: _form,
      // eslint-disable-next-line react/no-unused-state
      rules: rules,
      // eslint-disable-next-line react/prop-types
      submited: false,
      isLogin: false
    };
    return _this;
  }
  var _proto = FormTplView.prototype;
  _proto.componentDidMount = function componentDidMount() {
    // url中有appid是来源于小程序的分享，appid等于getWxAppid中则是微信公众号
    var _appId = _utils.$_GET === null || _utils.$_GET === void 0 ? void 0 : _utils.$_GET.appId;
    var _getCookieData = (0, _utils.getCookieData)(),
      token = _getCookieData.token;
    if (_appId && _appId === _utils.getWxAppid) {
      token = (0, _utils.getCookieData)().webToken;
    }
    if (token) {
      this.setState({
        isLogin: true
      });
    }
  };
  _proto.onChange = function onChange(key, value) {
    var _Object$assign;
    var isLogin = this.state.isLogin;
    if (!isLogin) this.getUserIsLogin();
    this.setState({
      // eslint-disable-next-line react/no-access-state-in-setstate
      form: Object.assign({}, this.state.form, (_Object$assign = {}, _Object$assign[key] = value, _Object$assign))
    });
  };
  _proto.render = function render() {
    var _this2 = this;
    var _this$state2 = this.state,
      form = _this$state2.form,
      rules = _this$state2.rules,
      submited = _this$state2.submited;
    // eslint-disable-next-line react/prop-types
    var _this$props = this.props,
      formData = _this$props.formData,
      _this$props$formBtnTe = _this$props.formBtnText,
      formBtnText = _this$props$formBtnTe === void 0 ? null : _this$props$formBtnTe,
      isEditting = _this$props.isEditting;
    var block = function block(item) {
      return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, item.image ? /*#__PURE__*/_react["default"].createElement("img", {
        src: item.image
      }) : /*#__PURE__*/_react["default"].createElement("span", {
        className: _indexModule["default"]['content-image'] + " xiatu-rich xt-gongjulan-xinzeng-chatu"
      }), /*#__PURE__*/_react["default"].createElement("span", {
        className: "" + _indexModule["default"]['content-text']
      }, item.value));
    };
    var content = function content(item, index) {
      // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
      var key = "prop" + (index + 1);
      // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
      var value = _this2.state.form["prop" + (index + 1)];
      return {
        input:
        /*#__PURE__*/
        // eslint-disable-next-line react/jsx-no-bind
        _react["default"].createElement(_elementReact.Input, {
          value: value,
          onChange: _this2.onChange.bind(_this2, key)
        }),
        radio:
        /*#__PURE__*/
        // eslint-disable-next-line react/jsx-no-bind
        _react["default"].createElement(_elementReact.Radio.Group, {
          value: value,
          onChange: _this2.onChange.bind(_this2, key)
        }, item.options && item.options.length ? item.options.map(function (cItem, idx) {
          // eslint-disable-next-line @typescript-eslint/no-shadow
          var isImage = item.options.some(function (item) {
            return item.image;
          });
          return /*#__PURE__*/_react["default"].createElement(_elementReact.Radio, {
            value: cItem.value
            // eslint-disable-next-line react/no-array-index-key
            ,
            key: idx,
            className: isImage ? '' : _indexModule["default"]['form-radio']
          }, isImage ? block(cItem) : item.value);
        }) : null),
        checkbox:
        /*#__PURE__*/
        // eslint-disable-next-line react/jsx-no-bind
        _react["default"].createElement(_elementReact.Checkbox.Group, {
          value: value,
          onChange: _this2.onChange.bind(_this2, key)
        }, item.options && item.options.length ? item.options.map(function (cItem, idx) {
          // eslint-disable-next-line @typescript-eslint/no-shadow
          var isImage = item.options.some(function (item) {
            return item.image;
          });
          return /*#__PURE__*/_react["default"].createElement(_elementReact.Checkbox, {
            label: cItem.value
            // eslint-disable-next-line react/no-array-index-key
            ,
            key: idx,
            className: isImage ? '' : _indexModule["default"]['form-radio']
          }, isImage ? block(cItem) : item.value);
        }) : null),
        upload:
        /*#__PURE__*/
        // eslint-disable-next-line react/jsx-no-bind
        _react["default"].createElement(_FormUpload["default"], {
          onChange: _this2.onChange.bind(_this2, key),
          className: _indexModule["default"]['form-upload']
        }),
        address:
        /*#__PURE__*/
        // eslint-disable-next-line react/jsx-no-bind
        _react["default"].createElement(_elementReact.Input, {
          value: value,
          onChange: _this2.onChange.bind(_this2, key)
        })
      };
    };
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: _indexModule["default"].view
    }, /*#__PURE__*/_react["default"].createElement(_elementReact.Form
    // eslint-disable-next-line react/no-string-refs
    , {
      ref: "form",
      model: form,
      rules: rules,
      className: _indexModule["default"]['user-form']
    }, isEditting ? /*#__PURE__*/_react["default"].createElement("div", {
      className: _indexModule["default"]['view-mask']
    }) : null, formData.length ?
    // eslint-disable-next-line react/prop-types
    formData.map(function (item, idx) {
      var _content, _item$type;
      return /*#__PURE__*/_react["default"].createElement(_elementReact.Form.Item, {
        key: item.key
        // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
        ,
        label: idx + 1 + "." + (item.label || '暂无选项标题')
        // eslint-disable-next-line
        ,
        prop: "prop" + (idx + 1)
      }, (_content = content(item, idx)[(_item$type = item.type) !== null && _item$type !== void 0 ? _item$type : 'input']) !== null && _content !== void 0 ? _content : null);
    }) : null, formData.length ? /*#__PURE__*/_react["default"].createElement(_elementReact.Button, {
      type: "primary",
      className: _indexModule["default"]['submit-form'],
      disabled: submited
      // eslint-disable-next-line react/jsx-no-bind
      ,
      onClick: this.handleSubmit.bind(this)
    }, submited ? '已提交' : formBtnText || '提 交') : /*#__PURE__*/_react["default"].createElement(_FormPlaceholder["default"], null)));
  };
  return FormTplView;
}(_react.Component);
exports["default"] = FormTplView;