import React, { useEffect, useState, useRef } from 'react';
import { Modal, Input, Form } from 'antd';
import styles from './RuleConfig.less';
import Tree from '@/components/ExpendableTree';
const { TextArea } = Input;
const RuleConfig = props => {
  const { visible, handleCancel, fieldList, onSubumit, RuleContent } = props;
  const [rule, setRule] = useState([]);
  const [expandedKey, setExpandedKey] = useState(''); // 默认展开项
  const [currentSelectId, setCurrentSelectId] = useState(''); // 选中得节点
  const ruleText = useRef();
  const [form] = Form.useForm();
  useEffect(() => {
    if (visible) {
      console.log(fieldList, 'fieldList');
      setExpandedKey(fieldList[0].TableName);
      setRule(RuleContent);
    } else {
      setExpandedKey('');
      setCurrentSelectId('');
      setRule('');
    }
  }, [visible]);
  // 保存线配置
  const onSave = () => {
    onSubumit(rule);
  };
  // 处理树数据
  const mapTree = (val, index) => {
    return {
      title: val.TableName,
      key: val.TableName,
      children: val.TableFieldNames.map(item => ({
        title: item,
        key: `${val.TableName}.${item}`,
      })),
    };
  };
  const onSelect = (prop, treeNode) => {
    console.log(prop, treeNode);
    if (!treeNode.node.children) {
      setRule(`${rule} {${treeNode.node.key}} `);
      ruleText.current.focus();
    }
    setCurrentSelectId(prop[0]);
  };
  return (
    <div>
      <Modal
        title="节点扭转规则配置"
        visible={visible}
        onOk={onSave}
        width="860px"
        onCancel={handleCancel}
        maskClosable={false}
        destroyOnClose
        getContainer={false}
      >
        <div className={styles.configContent}>
          <div className={styles.leftTree}>
            <Tree
              blockNode
              autoExpandParent
              onSelect={onSelect}
              selectedKeys={[currentSelectId]}
              expandedKeys={expandedKey}
              treeData={fieldList.map((item, index) => mapTree(item, index))}
            />
          </div>
          <div className={styles.rightContent}>
            <div className={styles.title}>符合以下条件时工单扭转到对应的节点</div>
            <div className={styles.textAreaBox}>
              <TextArea
                autoSize={{ minRows: 19, maxRows: 19 }}
                value={rule}
                rows={4}
                ref={ruleText}
                onChange={e => setRule(e.target.value)}
              />
            </div>
            <div className={styles.tipBox}>
              <p>请从左侧面板选择字段或选项</p>
              <p>{'支持英文模式下运算符（+、-、*、/、>、<、==、!=、<=、>=）及函数'}</p>
              <p>参考场景：</p>
              <p>当报销金额大于10000时，才能进入所选节点，则可将流转条件设置为：</p>
              <p>{'报销金额>10000'}</p>
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default RuleConfig;
