import "choerodon-ui/lib/form/style";
import _Form from "choerodon-ui/lib/form";
import "choerodon-ui/lib/input/style";
import _Input from "choerodon-ui/lib/input";
var _excluded = ["title", "editable", "dataIndex", "record", "intl"];

var _class;

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

/**
 * @author ale0720@163.com
 * @date 2019-05-09 22:11
 */
import React from 'react';
import { injectIntl } from 'react-intl';
import _ from 'lodash';
import { Consumer } from "./EditableContext";
var TextArea = _Input.TextArea;
var FormItem = _Form.Item;
var formItemLayout = {
  labelCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 100
    }
  },
  wrapperCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 26
    }
  }
};

var EditableCell = injectIntl(_class = /*#__PURE__*/function (_React$Component) {
  _inherits(EditableCell, _React$Component);

  var _super = _createSuper(EditableCell);

  function EditableCell() {
    var _this;

    _classCallCheck(this, EditableCell);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      editing: false,
      pasting: false,
      oldValue: ''
    };

    _this.toggleEdit = function () {
      // eslint-disable-next-line react/no-access-state-in-setstate
      var editing = !_this.state.editing;

      _this.setState({
        editing: editing
      }, function () {
        if (editing) {
          _this.input.focus();
        }
      });
    };

    _this.handleClickOutside = function (e) {
      var editing = _this.state.editing;

      if (editing && _this.cell !== e.target && !_this.cell.contains(e.target)) {
        _this.handleSave();
      }
    };

    _this.handleSave = function () {
      var _this$props = _this.props,
          record = _this$props.record,
          save = _this$props.save;

      _this.form.validateFields(function (error, values) {
        if (error) return;

        _this.toggleEdit();

        if (values.key === '' || values.key === null) {
          record.index = '';
        }

        save(_objectSpread(_objectSpread({}, record), values));
      });
    };

    _this.onChange = function (e) {
      var _this$props2 = _this.props,
          add = _this$props2.add,
          record = _this$props2.record;
      var _this$state = _this.state,
          oldValue = _this$state.oldValue,
          pasting = _this$state.pasting;

      if (pasting && record.key === 'key') {
        var value = oldValue !== '' ? e.target.value.substring(oldValue.length) || e.target.value : e.target.value;

        if (value.includes('=')) {
          var KValue = _.map(value.split('\n'), function (str) {
            if (str) {
              return _.map(str.split('='), function (s) {
                return s.trim();
              });
            }
          });

          _this.handleSave();

          add(_.filter(KValue, function (item) {
            return item;
          }));
        }
      }

      _this.setState({
        pasting: false
      });
    };

    _this.onKeyDown = function (e) {
      if (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) {
        _this.setState({
          pasting: true,
          oldValue: e.target.value
        });
      }
    };

    _this.checkKey = function (rule, value, callback) {
      var intl = _this.props.intl; // eslint-disable-next-line no-useless-escape

      var pattern = /[^0-9A-Za-z\.\-\_]/;

      if (pattern.test(value) && rule.field === 'key') {
        callback(intl.formatMessage({
          id: 'configMap.keyRule'
        }));
      } else {
        callback();
      }
    };

    return _this;
  }

  _createClass(EditableCell, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      if (this.props.editable) {
        document.addEventListener('click', this.handleClickOutside, true);
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      if (this.props.editable) {
        document.removeEventListener('click', this.handleClickOutside, true);
      }
    }
    /**
     * 切换输入编辑状态
     */

  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var editing = this.state.editing;

      var _this$props3 = this.props,
          title = _this$props3.title,
          editable = _this$props3.editable,
          dataIndex = _this$props3.dataIndex,
          record = _this$props3.record,
          intl = _this$props3.intl,
          restProps = _objectWithoutProperties(_this$props3, _excluded);

      return /*#__PURE__*/React.createElement("td", Object.assign({
        ref: function ref(node) {
          _this2.cell = node;
        }
      }, restProps), editable ? /*#__PURE__*/React.createElement(Consumer, null, function (form) {
        _this2.form = form;
        return editing ? /*#__PURE__*/React.createElement(FormItem, {
          className: "c7ncd-edit-table-form-item"
        }, form.getFieldDecorator(dataIndex, {
          initialValue: record[dataIndex],
          rules: [{
            validator: _this2.checkKey
          }]
        })( /*#__PURE__*/React.createElement(TextArea, {
          label: intl.formatMessage({
            id: dataIndex
          }),
          ref: function ref(node) {
            _this2.input = node;
          },
          autosize: true,
          onKeyDown: _this2.onKeyDown,
          onChange: _this2.onChange
        }))) : /*#__PURE__*/React.createElement(TextArea, {
          autosize: true,
          label: intl.formatMessage({
            id: dataIndex
          }),
          className: "editable-cell-value-wrap",
          onClick: _this2.toggleEdit,
          onFocus: _this2.toggleEdit,
          value: title === 'cipher' && dataIndex === 'value' && restProps.children.filter(function (a) {
            return typeof a === 'string';
          }).length ? '******' : restProps.children.filter(function (a) {
            return typeof a === 'string';
          })
        });
      }) : restProps.children);
    }
  }]);

  return EditableCell;
}(React.Component)) || _class;

export { EditableCell as default };