/*
 * Author: 黎永顺
 * name: 短信设置弹框
 * Description:
 * Date: 2023/11/23
 */
import React, { Component } from "react";
import { WeaDialog, WeaLocaleProvider } from "ecCom";
import { Button, Col, Row, Tree } from "antd";
import uuidV4 from "uuid/v4";
import { getSmsSalaryItemSet } from "../../../../apis/payroll";
import { Controlled as CodeMirror } from "react-codemirror2";
import "codemirror/lib/codemirror.css";
import "codemirror/lib/codemirror.js";
import "codemirror/mode/javascript/javascript.js";

const TreeNode = Tree.TreeNode;
const getLabel = WeaLocaleProvider.getLabel;

class SmsSettingDialog extends Component {
  constructor(props) {
    super(props);
    this.state = {
      variableExpandedKeys: [], variableList: [], smsContent: ""
    };
    this.editorRef = null;
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) this.getSmsSalaryItemSet(nextProps);
    if (nextProps.visible !== this.props.visible && !nextProps.visible) this.setState({
      variableList: [], variableExpandedKeys: [], smsContent: ""
    });
  }

  getSmsSalaryItemSet = (props) => {
    this.setState({ smsContent: props.content });
    getSmsSalaryItemSet({ salarySobId: props.salarySobId }).then(({ status, data }) => {
      if (status) this.setState({
        variableList: _.map(data, item => ({
          key: item.groupId, value: item.groupName,
          children: item.items
        }))
      });
    });
  };
  insertText = text => {
    const cursor = this.editorRef.getCursor();
    this.editorRef.replaceRange(text, cursor);
    this.editorRef.refresh();
    this.editorRef.focus();
  };
  handleBackSpaceRedo = () => {
    const { ch, line } = this.editorRef.getCursor();
    const delStr = this.editorRef.getRange({ line, ch: ch - 1 }, { line, ch });
    const codeValue = this.editorRef.getValue();
    if (delStr === "}") {
      if (codeValue.slice(0, ch).lastIndexOf("{") === -1) {
        this.editorRef.replaceRange("", { line, ch: ch - 1 }, { line, ch });
      } else {
        this.editorRef.replaceRange("", { line, ch: codeValue.slice(0, ch).lastIndexOf("{") + 1 }, { line, ch });
      }
    }
    this.editorRef.refresh();
    this.editorRef.focus();
  };
  handleExpandVari = variableExpandedKeys => this.setState({ variableExpandedKeys });
  handleVariNode = (__, { selectedNodes }) => {
    const [selectedNode] = selectedNodes;
    const { props } = selectedNode;
    if (_.isNil(props.children)) this.insertText(`{${props.title}}`);
  };

  render() {
    const { variableExpandedKeys, variableList, smsContent } = this.state;
    return (
      <WeaDialog
        {...this.props} hasScroll className="smsSettingDialog" initLoadCss title={getLabel(111, "短信设置")}
        onCancel={() => this.props.onCancel({ smsContent })}
        buttons={[<Button type="primary"
                          onClick={() => this.props.onCancel({ smsContent })}>{getLabel(826, "确定")}</Button>]}
        style={{
          width: 800,
          height: 606.6,
          minHeight: 200,
          minWidth: 380,
          maxHeight: "90%",
          maxWidth: "90%",
          overflow: "hidden",
          transform: "translate(0px, 0px)"
        }}
      >
        <div className="smsSettingCont">
          <Row>
            <Col span={16}>
              <CodeMirror
                editorDidMount={editor => this.editorRef = editor}
                value={smsContent}
                onBeforeChange={(editor, data, value) => {
                  this.setState({ smsContent: value });
                }}
                onChange={editor => editor.getAllMarks().forEach(m => m.clear())}
                options={{
                  lineNumbers: false,
                  mode: "javascript",
                  autofocus: false,
                  styleActiveLine: true,
                  lineWrapping: true,
                  matchBrackets: true,
                  lint: false,
                  indentUnit: 2,
                  cursorHeight: 0.85,
                  placeholder: "",
                  showCursorWhenSelecting: true
                }}
                onKeyDown={(_, { keyCode }) => keyCode === 8 && this.handleBackSpaceRedo()}
              />
            </Col>
            <Col span={8}>
              <div className="smsSetting-var-header">
                <div className="smsSetting-var-header-title">{getLabel(33748, "变量")}</div>
              </div>
              <div className="smsSetting-var-header-content">
                <Tree className="variableTree" showLine expandedKeys={variableExpandedKeys}
                      onExpand={this.handleExpandVari} onSelect={this.handleVariNode}
                >
                  {
                    _.map(variableList, item => {
                      const { key, value, children = [] } = item;
                      return <TreeNode title={value} key={key}>
                        {
                          _.map(children, child => {
                            const { name, id } = child;
                            return (<TreeNode title={name} key={id || uuidV4()}/>);
                          })
                        }
                      </TreeNode>;
                    })
                  }
                </Tree>
              </div>
            </Col>
          </Row>
        </div>
      </WeaDialog>
    );
  }
}

export default SmsSettingDialog;
