"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 _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _react = require("react");
var _elementReact = require("element-react");
var _XtFormLeft = _interopRequireDefault(require("./XtFormLeft"));
var _XtFormRight = _interopRequireDefault(require("./XtFormRight"));
var _SaveTpl = _interopRequireDefault(require("./XtFormRight/SaveTpl"));
var _utils = require("../../utils/utils");
var _base = require("../../api/base");
var _indexModule = _interopRequireDefault(require("./index.module.scss"));
var XtFormSetter = /*#__PURE__*/function (_Component) {
  (0, _inheritsLoose2["default"])(XtFormSetter, _Component);
  function XtFormSetter(props) {
    var _$_GET$ctg_id, _$_GET$tpl_id;
    var _this;
    _this = _Component.call(this, props) || this;
    _this.setBoolValue = function (field, status) {
      var _this$setState;
      var value = _this.state[field];
      _this.setState((_this$setState = {}, _this$setState[field] = typeof status === 'boolean' ? status : !value, _this$setState));
    };
    _this.state = {
      formVisible: false,
      saveTplVisible: false,
      form: {
        list: []
      },
      menu: {
        tpl: {
          tabList: [],
          ctg_id: (_$_GET$ctg_id = _utils.$_GET === null || _utils.$_GET === void 0 ? void 0 : _utils.$_GET.ctg_id) !== null && _$_GET$ctg_id !== void 0 ? _$_GET$ctg_id : '',
          tpl_id: (_$_GET$tpl_id = _utils.$_GET === null || _utils.$_GET === void 0 ? void 0 : _utils.$_GET.tpl_id) !== null && _$_GET$tpl_id !== void 0 ? _$_GET$tpl_id : ''
        }
      },
      tplId: 0,
      isEditting: false
    };
    _this.initData();
    return _this;
  }
  var _proto = XtFormSetter.prototype;
  _proto.initData = /*#__PURE__*/function () {
    var _initData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
      var menu, _yield$categoryList, data, code, _yield$templateList, tpCode, tpData;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              menu = this.state.menu;
              _context.next = 3;
              return (0, _base.categoryList)({
                is_show: 1,
                parent_id: 0
              });
            case 3:
              _yield$categoryList = _context.sent;
              data = _yield$categoryList.data;
              code = _yield$categoryList.code;
              if (!(code !== 10200)) {
                _context.next = 8;
                break;
              }
              return _context.abrupt("return");
            case 8:
              _context.next = 10;
              return (0, _base.templateList)({
                is_hot: 1
              });
            case 10:
              _yield$templateList = _context.sent;
              tpCode = _yield$templateList.code;
              tpData = _yield$templateList.data;
              if (!(tpCode !== 10200)) {
                _context.next = 15;
                break;
              }
              return _context.abrupt("return");
            case 15:
              data.map(function (res) {
                return (0, _extends2["default"])({}, res, {
                  tplList: []
                });
              });
              data.unshift({
                ctg_id: -9999,
                is_show: 1,
                parent_id: 0,
                sort_by: 0,
                title: '推荐',
                tplList: tpData
              });
              menu.tpl.tabList = data;
              this.setState({
                menu: menu
              });
            case 19:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, this);
    }));
    function initData() {
      return _initData.apply(this, arguments);
    }
    return initData;
  }()
  /**
   * boolean值显示与隐藏
   * @param field 字段
   * @param status 状态 - 非 boolean 类型 取反
   */
  ;
  _proto.render = function render() {
    var _this2 = this;
    var _this$state = this.state,
      menu = _this$state.menu,
      form = _this$state.form;
    var _this$props = this.props,
      _this$props$value = _this$props.value,
      formData = _this$props$value.formData,
      f_id = _this$props$value.f_id,
      onChange = _this$props.onChange;
    var tabList = menu.tpl.tabList;
    var tabChange = /*#__PURE__*/function () {
      var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(ctgId) {
        var success, params, _yield$templateList2, code, data;
        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                success = tabList.find(function (res) {
                  return [+ctgId, ctgId].includes(res.ctg_id);
                });
                params = {
                  is_hot: ctgId === '-9999' ? 1 : -1
                };
                if (ctgId !== '-9999') Object.assign(params, {
                  ctg_parent_id: ctgId
                });
                _context2.next = 5;
                return (0, _base.templateList)(params);
              case 5:
                _yield$templateList2 = _context2.sent;
                code = _yield$templateList2.code;
                data = _yield$templateList2.data;
                if (!(code !== 10200)) {
                  _context2.next = 10;
                  break;
                }
                return _context2.abrupt("return");
              case 10:
                success.tplList = data;
                _this2.setState({
                  menu: menu
                });
              case 12:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }));
      return function tabChange(_x) {
        return _ref.apply(this, arguments);
      };
    }();
    var menuClick = /*#__PURE__*/function () {
      var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(item) {
        var tpl_id, ctg_id, _yield$templateQuery, code, data;
        return _regenerator["default"].wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                tpl_id = item.tpl_id, ctg_id = item.ctg_id;
                tabList.forEach(function (res) {
                  var _res$tplList;
                  res === null || res === void 0 ? void 0 : (_res$tplList = res.tplList) === null || _res$tplList === void 0 ? void 0 : _res$tplList.map(function (cRes) {
                    var tplId = cRes.tpl_id,
                      ctgId = cRes.ctg_id;
                    cRes.active = tpl_id === tplId && ctg_id === ctgId; // 高亮选中
                    return cRes;
                  });
                });
                if (!tpl_id) {
                  _context3.next = 11;
                  break;
                }
                _context3.next = 5;
                return (0, _base.templateQuery)({
                  tpl_id: tpl_id
                });
              case 5:
                _yield$templateQuery = _context3.sent;
                code = _yield$templateQuery.code;
                data = _yield$templateQuery.data;
                if (!(code !== 10200 && !data)) {
                  _context3.next = 10;
                  break;
                }
                return _context3.abrupt("return");
              case 10:
                Object.assign(item, {
                  list: JSON.parse(data.schema)
                });
              case 11:
                _this2.setState({
                  menu: menu,
                  form: Object.assign({
                    list: []
                  }, item),
                  isEditting: false
                });
              case 12:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3);
      }));
      return function menuClick(_x2) {
        return _ref2.apply(this, arguments);
      };
    }();

    /**
     * 更新 表单数据
     * @param value 更新值
     * @param item 数据项
     * @param key 更新字段
     */
    var changeFormValue = function changeFormValue(value, item, key) {
      item[key] = value;
      _this2.setState({
        form: form
      });
    };

    /**
     * 表单排序控制
     * @param item 当前数据
     * @param type prev: 上移, next:下移, top:置顶, delete:删除
     */
    var changeForm = function changeForm(item, type) {
      var itemIdx = form.list.findIndex(function (res) {
        return res.key === item.key;
      });
      var otherIdx = {
        prev: itemIdx - 1,
        next: itemIdx + 1,
        top: 0,
        bottom: form.list.length
      };
      var tmp = [];
      var setFormList = function setFormList(list) {
        return _this2.setState({
          form: (0, _extends2["default"])({}, form, {
            list: list
          })
        });
      };
      switch (type) {
        case 'prev': // 上移
        case 'next': // 下移
        case 'top': // 置顶
        case 'bottom':
          // 沉底
          if (['prev', 'top'].includes(type) && itemIdx === 0) break; // 上移&&置顶边界处理
          if (['next'].includes(type) && itemIdx >= form.list.length - 1) break; // 下移边界处理

          Object.assign(tmp, form.list.filter(function (res) {
            return res.key !== item.key;
          }));
          tmp.splice(otherIdx[type], 0, form.list[itemIdx]);
          Object.assign(form.list, tmp);
          setFormList(form.list); // 更新数据
          break;
        case 'delete':
          _elementReact.MessageBox.confirm('您确认删除此选项么', '提示', {
            type: 'warning'
          }).then(function () {
            form.list.splice(itemIdx, 1);
            (0, _elementReact.Message)({
              type: 'success',
              message: '删除成功!'
            });
            setFormList(form.list);
          });
          break;
        default:
          return '';
      }
    };

    /**
     * 添加表单项
     * @param item 表单类型数据
     */
    var addFormIem = function addFormIem(item) {
      form.list.push(item);
      _this2.setState({
        form: form
      });
    };

    /**
     * 添加单选|多选的选项数据
     * @param item 当前表单项
     * @param type 0:其它,1 空白选项
     */
    var addFromOptions = function addFromOptions(item, type) {
      if (![0, 1].includes(type)) return;
      var opts = type === 0 ? {
        value: [],
        other: true
      } : {
        value: '',
        image: ''
      };
      opts.key = Date.now().toString(32) + Math.random().toString(32).slice(1);
      form.list.map(function (res) {
        if (res.key === item.key) {
          var insetIdx = res.options.findIndex(function (res) {
            return res.other !== undefined;
          });
          if (type === 0 && insetIdx !== -1) return res;
          Array.isArray(res === null || res === void 0 ? void 0 : res.options) && res.options.splice(insetIdx !== -1 ? insetIdx : res.options.length, 0, opts);
        }
        return res;
      });
      _this2.setState({
        form: form
      });
    };

    /**
     * 删除单选|多选的选项数据
     * @param item 当前表单项
     * @param opt 删除项
     */
    var delFromOptions = function delFromOptions(item, opt) {
      item.options.splice(item.options.findIndex(function (cld) {
        return cld.key === opt.key;
      }), 1);
      _this2.setState({
        form: form
      });
    };
    var saveFormHandler = /*#__PURE__*/function () {
      var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(ev) {
        var _this2$state$form, _this2$state$form$lis, schema, tpl_id;
        return _regenerator["default"].wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                ev.preventDefault();
                _this2$state$form = _this2.state.form, _this2$state$form$lis = _this2$state$form.list, schema = _this2$state$form$lis === void 0 ? {} : _this2$state$form$lis, tpl_id = _this2$state$form.tpl_id;
                onChange({
                  formData: schema
                });
                _this2.setBoolValue('formVisible', false);
                _this2.setState({
                  tplId: tpl_id
                });
              case 5:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4);
      }));
      return function saveFormHandler(_x3) {
        return _ref3.apply(this, arguments);
      };
    }();
    var xtFormReset = function xtFormReset() {
      tabList.forEach(function (item) {
        var _item$tplList;
        item === null || item === void 0 ? void 0 : (_item$tplList = item.tplList) === null || _item$tplList === void 0 ? void 0 : _item$tplList.map(function (event) {
          // eslint-disable-next-line no-param-reassign
          event.active = event.tpl_id === _this2.state.tplId;
          return event;
        });
      });
      _this2.setState({
        menu: menu,
        form: Object.assign(form, {
          list: formData
        }),
        isEditting: false
      });
    };
    var changeIsEdit = function changeIsEdit(params) {
      _this2.setState({
        isEditting: params
      });
    };
    return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(_elementReact.Button, {
      size: "small",
      type: "primary",
      onClick: function onClick() {
        xtFormReset();
        _this2.setBoolValue('formVisible', true);
      }
    }, /*#__PURE__*/React.createElement("span", {
      className: "xiatu-rich xt-editor " + _indexModule["default"]['btn-editor']
    }), "\u7F16\u8F91\u8868\u5355"), /*#__PURE__*/React.createElement(_elementReact.Dialog, {
      title: "\u7F16\u8F91\u8868\u5355",
      visible: this.state.formVisible,
      closeOnClickModal: false,
      onCancel: function onCancel() {
        _this2.setBoolValue('formVisible', false);
      },
      className: _indexModule["default"].dialog
    }, /*#__PURE__*/React.createElement("div", {
      className: _indexModule["default"].form
    }, /*#__PURE__*/React.createElement("div", {
      className: _indexModule["default"]['form-body']
    }, /*#__PURE__*/React.createElement("div", {
      className: _indexModule["default"]['form-left']
    }, /*#__PURE__*/React.createElement(_XtFormLeft["default"], {
      formData: this.state.menu,
      tabChange: tabChange,
      menuClick: menuClick
    })), /*#__PURE__*/React.createElement("div", {
      className: _indexModule["default"]['form-right']
    }, /*#__PURE__*/React.createElement(_XtFormRight["default"], {
      formData: this.state.form,
      ref: "formRight",
      f_id: f_id,
      isEditting: this.state.isEditting,
      changeIsEdit: changeIsEdit,
      changeForm: changeForm,
      addFromOptions: addFromOptions,
      delFromOptions: delFromOptions,
      changeFormValue: changeFormValue,
      addFormIem: addFormIem
    }))), /*#__PURE__*/React.createElement("div", {
      className: _indexModule["default"]['form-footer']
    }, /*#__PURE__*/React.createElement("div", {
      className: _indexModule["default"]['form-footer-left']
    }, "\u8868\u5355\u9898\u76EE\uFF1A5\u4E2A"), /*#__PURE__*/React.createElement("div", {
      className: _indexModule["default"]['form-footer-right']
    }, /*#__PURE__*/React.createElement(_SaveTpl["default"], {
      formData: this.state.form,
      tabChange: tabChange,
      setParentBoolValue: this.setBoolValue
    }), /*#__PURE__*/React.createElement(_elementReact.Button, {
      type: "primary",
      onClick: function onClick(ev) {
        return saveFormHandler.bind(_this2)(ev);
      },
      disabled: JSON.stringify(this.state.form) === '{}',
      className: _indexModule["default"]['form-footer-btn']
    }, /*#__PURE__*/React.createElement("span", {
      className: _indexModule["default"]['form-footer-btn-icon'] + " xiatu-rich xt-baocun"
    }), "\u4FDD\u5B58\u8868\u5355"))))));
  };
  return XtFormSetter;
}(_react.Component);
exports["default"] = XtFormSetter;
XtFormSetter.displayName = 'XtFormSetter';