import "choerodon-ui/lib/button/style";
import _Button from "choerodon-ui/lib/button";
import "choerodon-ui/lib/tabs/style";
import _Tabs from "choerodon-ui/lib/tabs";

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

import React, { Component } from 'react';
import { injectIntl } from 'react-intl';
import ReactCodeMirror from 'react-codemirror';
import ReactMarkdown from 'react-markdown';
import 'codemirror/lib/codemirror.css';
import "./MdEditor.less";
import "./preview.css";

require('codemirror/mode/markdown/markdown');

var TabPane = _Tabs.TabPane;

var MdEditor = /*#__PURE__*/function (_Component) {
  _inherits(MdEditor, _Component);

  var _super = _createSuper(MdEditor);

  function MdEditor(props) {
    var _this;

    _classCallCheck(this, MdEditor);

    _this = _super.call(this, props);
    _this.options = {
      lineNumbers: false,
      lineWrapping: true,
      readOnly: false,
      mode: 'markdown'
    };

    _this.beforeChange = function (cm, obj) {
      // 获取最大长度配置
      var textMaxLength = _this.props.textMaxLength; // 处理来源是粘贴的情况

      if (obj.origin === 'paste') {
        var _value2 = cm.getValue();

        var vlength = _value2.length; // 如果当前文本长度已经大于最大长度 放弃新增

        if (vlength >= textMaxLength) {
          obj.cancel();
          return;
        } // 如果当前文本长度小于最大长度
        // 从新增的文本中找出 剩余长度部分的文字


        for (var i = 0; i < obj.text.length; i++) {
          if (vlength + obj.text[i].length > textMaxLength) {
            obj.text[i] = obj.text[i].slice(0, textMaxLength - vlength);
            obj.text = obj.text.slice(0, i + 1);
            return;
          }

          vlength += obj.text[i].length || 1;
        }
      } // 处理其它情况（delete、input）


      var value = cm.getValue() + obj.text[0]; // 如果 当前文本长度大于最大长度

      if (cm.getValue().length >= textMaxLength) {
        if (obj.text.length > 1) {
          // 处理文本已经超出后的换行
          obj.text.pop();
        } else {
          // 改变新增的文本为空
          obj.text[0] = '';
        }

        return;
      } // 如果 当前文本长度+新增文本 大于最大长度 截取新增文本的部分字符串


      if (value.length > textMaxLength) {
        obj.text[0] = value.slice(cm.getValue().length, textMaxLength);
      }
    };

    _this.componentDidMount = function () {
      if (_this.props.textMaxLength) {
        var editor = _this.mdEditor.getCodeMirror();

        editor.on('beforeChange', _this.beforeChange);
      }
    };

    _this.onChange = function (values, obj) {
      var onChange = _this.props.onChange;

      try {
        var editor = _this.mdEditor.getCodeMirror();

        onChange(values);

        _this.setState({
          valueLength: values.length
        });

        var height = editor.getDoc().height;
        setTimeout(function () {
          editor.setSize('100%', height);
        }, 0);
      } catch (e) {
        throw new Error(e);
      }
    };

    _this.handleTabChange = function (e) {
      return _this.setState({
        tabKey: e
      });
    };

    _this.handleBoxSize = function (flag) {
      _this.setState({
        isExpand: flag
      }, function () {
        var editor = _this.mdEditor.getCodeMirror();

        editor.setSize('100%', editor.getDoc().height);
      });
    };

    var _value = props.value;
    _this.state = {
      tabKey: 'write',
      isExpand: false,
      valueLength: _value ? _value.length : 0
    };
    return _this;
  }

  _createClass(MdEditor, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          formatMessage = _this$props.intl.formatMessage,
          value = _this$props.value,
          textMaxLength = _this$props.textMaxLength;
      var _this$state = this.state,
          isExpand = _this$state.isExpand,
          tabKey = _this$state.tabKey,
          valueLength = _this$state.valueLength;
      var operations = /*#__PURE__*/React.createElement(_Button, {
        icon: isExpand ? 'first_page' : 'last_page',
        onClick: function onClick() {
          return _this2.handleBoxSize(!isExpand);
        }
      }, formatMessage({
        id: isExpand ? 'shrink' : 'expand'
      }));
      return /*#__PURE__*/React.createElement("div", {
        className: "c7n-mdeditor-wrap",
        style: {
          width: isExpand ? '100%' : 512
        }
      }, /*#__PURE__*/React.createElement(_Tabs, {
        animated: false,
        defaultActiveKey: "write",
        tabBarExtraContent: operations,
        onChange: this.handleTabChange
      }, /*#__PURE__*/React.createElement(TabPane, {
        tab: formatMessage({
          id: 'write'
        }),
        key: "write"
      }, /*#__PURE__*/React.createElement("div", {
        className: "c7n-md-placeholder"
      }, formatMessage({
        id: 'md.placeholder'
      })), /*#__PURE__*/React.createElement("div", {
        onClick: function onClick(e) {
          _this2.mdEditor.focus();
        }
      }, /*#__PURE__*/React.createElement(ReactCodeMirror, {
        ref: function ref(cm) {
          _this2.mdEditor = cm;
        },
        options: this.options,
        value: value,
        onChange: this.onChange
      })), textMaxLength ? /*#__PURE__*/React.createElement("div", {
        className: "c7n-md-placeholder c7n-md-text-length-placeholder"
      }, "(".concat(valueLength, "/").concat(textMaxLength, ")")) : null), /*#__PURE__*/React.createElement(TabPane, {
        tab: formatMessage({
          id: 'preview'
        }),
        key: "preview"
      }, /*#__PURE__*/React.createElement("div", {
        className: "c7n-md-parse c7n-md-preview c7n-md-preview-box"
      }, /*#__PURE__*/React.createElement(ReactMarkdown, {
        source: value || formatMessage({
          id: 'noContent'
        }),
        skipHtml: false,
        escapeHtml: false
      })))));
    }
  }]);

  return MdEditor;
}(Component);

MdEditor.defaultProps = {
  value: ''
};
export default injectIntl(MdEditor);