/*
 * Author: 黎永顺
 * name: 公式列表
 * Description:
 * Date: 2023/4/25
 */
import React, { Component } from "react";
import { WeaInputSearch, WeaLocaleProvider } from "ecCom";
import { Tree } from "antd";
import cs from "classnames";
import { formualSearchField, formualSearchGroup, getFormulaDes } from "../../../apis/item";
import "../index.less";

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

class CodeAction extends Component {
  constructor(props) {
    super(props);
    this.state = {
      disabled: false,
      variableText: "",
      funcText: "",
      variItemText: "",
      variableList: [], //变量列表
      variableExpandedKeys: [], //变量展开的节点
      funcList: [], //函数列表
      funcExpandedKeys: [], //函数展开的节点
      funcHoverItem: {} //选中的函数节点
    };
  }

  componentDidMount() {
    const { groupParams = {} } = this.props;
    this.getFormulaDes();
    this.formualSearchGroup(groupParams);
  }

  componentWillReceiveProps(nextProps, nextContext) {
    const { isCustomFunction, isCustomFunctionClick, onChangeCustomFunction } = nextProps;
    if (isCustomFunction === "1" && !isCustomFunctionClick) {
      this.setState({ disabled: true });
    } else {
      this.setState({ disabled: false }, () => {
        isCustomFunction === "1" && onChangeCustomFunction("0");
      });
    }
  }

  getFormulaDes = () => {
    getFormulaDes().then(({ data }) => {
      if (!_.isEmpty(data)) this.setState({ funcList: data });
    });
  };
  formualSearchGroup = (payload) => {
    formualSearchGroup(payload).then(({ status, data }) => {
      if (status) this.setState({
        variableList: _.map(data, item => ({
          ...item,
          children: [{ name: "", fieldId: "searchInput" }]
        }))
      });
    });
  };
  formualSearchField = (sourceId) => {
    const { groupParams } = this.props;
    const { variableList } = this.state;
    formualSearchField({ sourceId, extendParam: { ...groupParams } }).then(({ status, data }) => {
      if (status) {
        this.setState({
          variableList: _.map(variableList, it => ({
            ...it,
            children: sourceId === it.key ? [...it.children, ...data] : [...it.children]
          }))
        });
      }
    });
  };
  handleExpandVari = (variableExpandedKeys, { expanded, node }) => {
    const { props: { eventKey } } = node;
    const { variableList } = this.state;
    this.setState({ variableExpandedKeys });
    if (expanded) {
      this.formualSearchField(eventKey);
    } else {
      this.setState({
        variableList: _.map(variableList, it => ({
          ...it,
          children: eventKey === it.key ? [{ name: "", fieldId: "searchInput" }] : [...it.children]
        }))
      });
    }
  };
  handleVariNode = (selectedKeys) => {
    const { onVariSelect } = this.props;
    const { variableList } = this.state;
    const parentNode = _.map(variableList, it => it.key);
    if (selectedKeys.join() && selectedKeys.join().indexOf("searchInput") === -1 &&
      !parentNode.includes(selectedKeys.join())) {
      const selectParentNodeKey = selectedKeys.join().split("_")[0];
      const convertStr = _.reduce(variableList, (pre, cur) => {
        if (cur.key === selectParentNodeKey) {
          return pre + cur.value + "." + _.find(cur.children, child => child.fieldId === selectedKeys.join()).name;
        }
        return pre;
      }, "");
      onVariSelect(convertStr);
    }
  };

  render() {
    const {
      variableList, variableExpandedKeys, variableText, variItemText,
      funcList, funcText, funcExpandedKeys, funcHoverItem, disabled
    } = this.state;
    const { groupParams = {} } = this.props;
    const { referenceType } = groupParams;
    const variableDatalist = _.filter(variableList, it => it.value.indexOf(variableText) !== -1);
    const funcDatalist = _.map(funcList, it => ({
      ...it,
      children: _.filter(it.children, child => _.lowerCase(child.name).indexOf(_.lowerCase(funcText)) !== -1)
    }));
    return (
      <div className="excel-codeAction">
        <div className="excel-codeAction-item">
          <div className="excel-codeAction-header">
            <div className="excel-codeAction-header-title">{getLabel(111, "变量")}</div>
          </div>
          <div className="excel-codeAction-content">
            <WeaInputSearch value={variableText} placeholder={getLabel(111, "请输入变量名称")}
                            className="variableOuterInput"
                            onChange={variableText => this.setState({ variableText })}/>
            <Tree className="variableTree" showLine expandedKeys={variableExpandedKeys}
                  onExpand={this.handleExpandVari} onSelect={this.handleVariNode}
            >
              {
                _.map(variableDatalist, item => {
                  const { key, value, children = [] } = item;
                  const itemChildren = _.filter(children.slice(1), it => it.name.indexOf(variItemText) !== -1);
                  return <TreeNode title={value} key={key}>
                    {
                      _.map([...children.slice(0, 1), ...itemChildren], (child, childIndex) => {
                        const { name, fieldId, fieldType } = child;
                        return (
                          fieldId === "searchInput" ?
                            <TreeNode
                              title={
                                <WeaInputSearch
                                  value={variItemText}
                                  placeholder={getLabel(111, "请输入变量名称")}
                                  onChange={variItemText => this.setState({ variItemText })}
                                />
                              }
                              key={fieldId + "_" + childIndex}/> :
                            <TreeNode title={
                              <div className="weapp-excel-code-action-list-variable">
                                <span className="weapp-excel-code-action-list-variable-name">{name}</span>
                                {
                                  fieldType ?
                                    <span
                                      className={cs("weapp-excel-code-action-list-variable-tip", { "danger": fieldType === "string" })}>{fieldType === "number" ? "数字" : "文本"}</span> :
                                    <span></span>
                                }
                              </div>
                            } key={fieldId}/>
                        );
                      })
                    }
                  </TreeNode>;
                })
              }
            </Tree>
          </div>
        </div>
        {
          referenceType !== "sql" &&
          <React.Fragment>
            <div className="excel-codeAction-item">
              <div className="excel-codeAction-header">
                <div className="excel-codeAction-header-title">{getLabel(111, "函数")}</div>
              </div>
              <div className="excel-codeAction-content">
                <WeaInputSearch value={funcText} placeholder={getLabel(111, "请输入函数名称")}
                                className="variableOuterInput"
                                onChange={funcText => this.setState({ funcText })}/>
                <Tree className="variableTree" showLine expandedKeys={funcExpandedKeys}
                      onExpand={funcExpandedKeys => this.setState({ funcExpandedKeys })}
                >
                  {
                    _.map(funcDatalist, item => {
                      const { name, dataType, children = [] } = item;
                      return <TreeNode title={name} disabled={disabled} key={dataType}>
                        {
                          _.map(children, (child, childIndex) => {
                            const { name: childName, chineseName } = child;
                            return (
                              <TreeNode
                                disabled={disabled}
                                title={
                                  <div className="funcListTitle"
                                       onClick={() => this.props.onFuncSelect(childName)}
                                       onMouseEnter={() => this.setState({ funcHoverItem: child })}>
                                    <span className="functionName" title={childName}>{childName}</span>
                                    <span className="functionDesc" title={chineseName}>{chineseName}</span>
                                  </div>
                                }
                                key={childIndex}
                              />
                            );
                          })
                        }
                      </TreeNode>;
                    })
                  }
                </Tree>
              </div>
            </div>
            <div className="excel-codeAction-item">
              <div className="excel-codeAction-header">
                <div className="excel-codeAction-header-title">
                  {!_.isEmpty(funcHoverItem) ? funcHoverItem.name : getLabel(111, "提示")}
                </div>
              </div>
              <div className="excel-codeAction-content"><TipList tips={funcHoverItem}/></div>
            </div>
          </React.Fragment>
        }
      </div>
    );
  }
}

export default CodeAction;

const TipList = (props) => {
  const { tips } = props;
  const { paramDescs = [], formatString, description, example, result } = tips;
  return _.isEmpty(tips) ? <div className="code-action-list">
    <div className="code-action-tips">
      {/*<div>{getLabel(111, "{C:选项} 用来选择特定选项字段下的备选项")}</div>*/}
      {/*<div>{getLabel(111, "{U:姓名} 用来选择工作区成员")}</div>*/}
      {/*<div>{getLabel(111, "{D:数据} 用来选择一个部门")}</div>*/}
    </div>
  </div> : <div className="code-action-list">
    <div className="code-action-tips">
      <div className="code-action-tips-title">{getLabel(111, "语法")}</div>
      <div className="code-action-tips-info">
        <div>{formatString}</div>
        <div>{description}</div>
      </div>
      <div className="code-action-tips-title">{getLabel(111, "参数")}</div>
      {
        _.map(paramDescs, it => {
          return <div className="code-action-tips-info">
            <span>.</span>
            <span>{it}</span>
          </div>;
        })
      }
      <div className="code-action-tips-title">{getLabel(111, "示例")}</div>
      <span className="code-action-tips-info">{example}</span>
      <div className="code-action-tips-title">{getLabel(111, "结果")}</div>
      <span className="code-action-tips-info">{result}</span>
    </div>
  </div>;
};
