"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _message = _interopRequireDefault(require("@alifd/next/lib/message"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _react = _interopRequireWildcard(require("react"));
var _indexModule = _interopRequireDefault(require("./index.module.scss"));
var _elementReact = require("element-react");
var _base = require("../../../../api/base");
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 saveTpl = /*#__PURE__*/function (_Component) {
  (0, _inheritsLoose2["default"])(saveTpl, _Component);
  function saveTpl() {
    var _this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _Component.call.apply(_Component, [this].concat(args)) || this;
    _this.state = {
      visible: false,
      isAddTag: false,
      form: {
        title: '',
        // 模板标题 -1
        sub_title: '',
        // 副标题 -1
        ctg_pid: undefined,
        // 模板分类父ID -1
        ctg_id: undefined,
        // 模板分类ID -1
        is_hot: true,
        // 是否显示在推荐列表 -0
        is_bigshrimp: true,
        // 是否大虾推荐 1:是 0:否 默认:0
        tag: [] // 自定义标签
        // tpl_id: '', // 模板ID -1
        // is_show: true, // 是否显示 -0
        // sort_by: 0, // 排序值,值越大排约前,默认:0
        // schema:'' , // 模板schema-1
      },

      rules: {
        title: [{
          required: true,
          message: '请输入模板标题',
          trigger: 'blur'
        }],
        sub_title: [{
          required: true,
          message: '请选择模板副标题',
          trigger: 'blur'
        }],
        ctg_id: [{
          required: true,
          type: 'number',
          message: '请选择分类',
          trigger: 'change'
        }]
      },
      category: [] // 所有分类
    };
    _this.setBoolValue = function (field, status) {
      var _this$setState;
      // const {formVisible} = this.state
      var sField = _this.state[field];
      _this.setState((_this$setState = {}, _this$setState[field] = typeof status === 'boolean' ? status : !sField, _this$setState));
    };
    _this.onChange = function (key, value) {
      var _Object$assign;
      _this.setState({
        form: Object.assign({}, _this.state.form, (_Object$assign = {}, _Object$assign[key] = value, _Object$assign))
      });
      // if (/^tag\.\d+$/g.test(key)) { // tag 特殊情况
      //     // 1. 读取时: 拆分逗号分割字符串
      //     // 2. 写入时: 合并字符串(join)
      //     const _key = key.match(/^(?<t>tag)\.(?<k>\d+)$/)?.groups // 取出 tag
      //     const _tag = Object.assign(
      //         Array(3).fill(''),
      //         this.state?.form?.tag.split(',')
      //     )
      //     _tag[_key.k] = value
      //
      //     debugger
      //     // 更新 tag
      //     this.setState({
      //         form: Object.assign(
      //             {},
      //             this.state.form,
      //             {
      //                 // tag: //_tag.filter(res => /[\S]/g.test(res) && res !== undefined).join(',')
      //             }
      //         )
      //     });
      //
      // } else {
      //     this.setState({
      //         form: Object.assign({}, this.state.form, {[key]: value})
      //     });
      // }
    };
    return _this;
  }
  var _proto = saveTpl.prototype;
  _proto.componentDidMount = function componentDidMount() {
    var _this2 = this;
    (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
      var _yield$categoryList, code, data;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return (0, _base.categoryList)({
                is_show: 1,
                parent_id: -1
              });
            case 2:
              _yield$categoryList = _context.sent;
              code = _yield$categoryList.code;
              data = _yield$categoryList.data;
              if (code === 10200) {
                _this2.setState({
                  category: data
                });
              }
            case 6:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }))();
    // const getCategroyList =
    // getCategroyList.then(res=>console.log(res))
  }

  // 表输入控制
  ;
  /**
   * 删除 TAG
   * @param tag 要删除的 tag
   */
  _proto.delTag = function delTag(tag) {
    var tags = this.state.form.tag;
    var idx = tags.findIndex(function (res) {
      return res === tag;
    });
    tags.splice(idx, 1);
    this.forceUpdate();
  }

  /**
   * 添加 TAG 的input 切换
   */;
  _proto.showAddTag = function showAddTag() {
    var _this3 = this;
    this.setState({
      isAddTag: true
    }, function () {
      _this3.refs.saveTagInput.focus();
    });
  }

  /**
   * 添加 TAG 的input focus 事件
   * @param ev
   */;
  _proto.changeTag = function changeTag(ev) {
    var tagVal = ev.target.value;
    if (tagVal.length > 0) {
      var _this$state;
      ev.target.value = '';
      // debugger
      (_this$state = this.state) === null || _this$state === void 0 ? void 0 : _this$state.form.tag.push(tagVal);
    }
    this.state.isAddTag = false;
    this.forceUpdate();
  };
  _proto.render = function render() {
    var _this4 = this,
      _form$tag;
    var _this$state2 = this.state,
      form = _this$state2.form,
      rules = _this$state2.rules,
      category = _this$state2.category,
      isAddTag = _this$state2.isAddTag;
    var _this$props = this.props,
      formData = _this$props.formData,
      setParentBoolValue = _this$props.setParentBoolValue,
      tabChange = _this$props.tabChange;
    var submitForm = function submitForm() {};

    /**
     * 保存表单
     * @param ev event事件
     */
    var saveTplHandler = function saveTplHandler(ev) {
      ev.preventDefault();
      _this4.refs.form.validate( /*#__PURE__*/function () {
        var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(valid) {
          var _form, schema, _yield$templateAdd, code;
          return _regenerator["default"].wrap(function _callee2$(_context2) {
            while (1) {
              switch (_context2.prev = _context2.next) {
                case 0:
                  if (!valid) {
                    _context2.next = 10;
                    break;
                  }
                  // 合并两个默认参数
                  _form = Object.assign({}, form, {
                    is_show: 1,
                    // 是否显示 1:显示 0:隐藏,默认:1
                    sort_by: 0,
                    // 排序值,值越大排约前,默认:0
                    tag: form.tag.join(',')
                  }); // 转换所有 boolean 值为 0|1
                  Object.keys(_form).forEach(function (res) {
                    if (typeof _form[res] === 'boolean') _form[res] = _form[res] - 0;
                  });

                  // 拉取表单值
                  schema = formData.list;
                  Object.assign(_form, {
                    schema: JSON.stringify(schema)
                  });

                  // 发起保存表单为板请求
                  _context2.next = 7;
                  return (0, _base.templateAdd)(_form);
                case 7:
                  _yield$templateAdd = _context2.sent;
                  code = _yield$templateAdd.code;
                  if (code === 10200) {
                    tabChange('-9999') && tabChange(_form.ctg_pid);
                    _this4.setBoolValue('visible', false);
                    setParentBoolValue('formVisible', false);
                    _message["default"].success('保存成功');
                  }
                case 10:
                case "end":
                  return _context2.stop();
              }
            }
          }, _callee2);
        }));
        return function (_x) {
          return _ref2.apply(this, arguments);
        };
      }());
      ///
    };

    return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_elementReact.Dialog, {
      title: "\u4FDD\u5B58\u4E3A\u6A21\u677F",
      visible: this.state.visible,
      closeOnClickModal: false,
      onCancel: function onCancel(e) {
        e.preventDefault();
        _this4.refs.form.resetFields();
        _this4.setBoolValue('visible', false);
      },
      className: _indexModule["default"]['save-tpl']
    }, /*#__PURE__*/_react["default"].createElement(_elementReact.Form, {
      ref: "form",
      model: form,
      rules: rules,
      className: "form"
    }, /*#__PURE__*/_react["default"].createElement(_elementReact.Form.Item, {
      label: "\u6A21\u677F\u6807\u9898",
      prop: "title"
    }, /*#__PURE__*/_react["default"].createElement(_elementReact.Input, {
      value: form.title,
      placeholder: "\u8BF7\u8F93\u5165\u6A21\u677F\u6807\u9898",
      onChange: this.onChange.bind(this, 'title')
    })), /*#__PURE__*/_react["default"].createElement(_elementReact.Form.Item, {
      label: "\u6A21\u677F\u526F\u6807\u9898",
      prop: "sub_title"
    }, /*#__PURE__*/_react["default"].createElement(_elementReact.Input, {
      value: form.sub_title,
      placeholder: "\u8BF7\u8F93\u5165\u6A21\u677F\u526F\u6807\u9898",
      onChange: this.onChange.bind(this, 'sub_title')
    })), /*#__PURE__*/_react["default"].createElement(_elementReact.Form.Item, {
      label: "\u6A21\u677F\u5206\u7C7B",
      prop: "ctg_id"
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: _indexModule["default"]['dis-flex']
    }, /*#__PURE__*/_react["default"].createElement(_elementReact.Select, {
      value: form.ctg_pid,
      placeholder: "\u4E00\u7EA7\u5206\u7C7B",
      onChange: this.onChange.bind(this, 'ctg_pid')
    }, category.filter(function (res) {
      return res.parent_id === 0;
    }).map(function (res) {
      return /*#__PURE__*/_react["default"].createElement(_elementReact.Select.Option, {
        label: res.title,
        key: res.ctg_id,
        value: res.ctg_id
      });
    })), /*#__PURE__*/_react["default"].createElement(_elementReact.Select, {
      value: form.ctg_id,
      placeholder: "\u4E8C\u7EA7\u5206\u7C7B",
      onChange: this.onChange.bind(this, 'ctg_id')
    }, category.filter(function (res) {
      return res.parent_id === form.ctg_pid;
    }).map(function (res) {
      return /*#__PURE__*/_react["default"].createElement(_elementReact.Select.Option, {
        label: res.title,
        key: res.ctg_id,
        value: res.ctg_id
      });
    })))), /*#__PURE__*/_react["default"].createElement(_elementReact.Form.Item, {
      label: "\u63A8\u8350",
      className: _indexModule["default"]['inline-label']
    }, /*#__PURE__*/_react["default"].createElement(_elementReact.Switch, {
      value: form.is_hot,
      onText: "",
      offText: "",
      onChange: this.onChange.bind(this, 'is_hot')
    })), /*#__PURE__*/_react["default"].createElement(_elementReact.Form.Item, {
      label: "\u5927\u867E\u63A8\u8350",
      className: _indexModule["default"]['inline-label']
    }, /*#__PURE__*/_react["default"].createElement(_elementReact.Switch, {
      value: form.is_bigshrimp,
      onText: "",
      offText: "",
      onChange: this.onChange.bind(this, 'is_bigshrimp')
    })), /*#__PURE__*/_react["default"].createElement(_elementReact.Form.Item, {
      label: "\u81EA\u5B9A\u4E49\u6807\u7B7E(\u53EF\u5B9A\u4E493\u4E2A\u6807\u7B7E)"
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: _indexModule["default"].tags
    }, (_form$tag = form.tag) === null || _form$tag === void 0 ? void 0 : _form$tag.map(function (res) {
      return /*#__PURE__*/_react["default"].createElement(_elementReact.Tag, {
        closable: true,
        onClose: _this4.delTag.bind(_this4, res),
        key: Math.random(),
        type: "danger"
      }, res);
    }), form.tag.length < 3 ? isAddTag ? /*#__PURE__*/_react["default"].createElement(_elementReact.Input, {
      ref: "saveTagInput",
      size: "small",
      onBlur: this.changeTag.bind(this),
      "on-Key-Up": "this.tagKeyup.bind(this)",
      className: _indexModule["default"]['add-tag-input'],
      maxLength: 4
    }) : /*#__PURE__*/_react["default"].createElement("span", {
      className: "xiatu-rich xt-xinzeng " + _indexModule["default"]['add-tag-button'],
      onClick: this.showAddTag.bind(this)
    }) : ''))), /*#__PURE__*/_react["default"].createElement("div", {
      className: _indexModule["default"]['save-tpl-bottom']
    }, /*#__PURE__*/_react["default"].createElement(_elementReact.Button, {
      type: "primary",
      className: _indexModule["default"]['save-button'],
      onClick: function onClick(ev) {
        return saveTplHandler(ev);
      }
    }, /*#__PURE__*/_react["default"].createElement("span", {
      className: "xiatu-rich xt-baocun"
    })))), /*#__PURE__*/_react["default"].createElement(_elementReact.Button, {
      type: "primary",
      disabled: JSON.stringify(formData) === '{}',
      onClick: function onClick() {
        return _this4.setBoolValue('visible', true);
      },
      className: _indexModule["default"]['form-footer-btn']
    }, /*#__PURE__*/_react["default"].createElement("span", {
      className: _indexModule["default"]['form-footer-btn-icon'] + " xiatu-rich xt-calendar-edit"
    }), "\u4FDD\u5B58\u4E3A\u6A21\u677F"));
  };
  return saveTpl;
}(_react.Component);
exports["default"] = saveTpl;