import React, { useEffect, useState, useRef } from 'react';
import { RuleValidation } from '@/services/workflow/workflow';
import { Modal, Input, Form, message, Dropdown, Menu } from 'antd';
import styles from './index.less';
import Tree from '@/components/ExpendableTree';
const { TextArea } = Input;
const fnList = [
  { label: '是否为工作日', value: '$fn.isWorkDay()' },
  { label: '是否为工作时间', value: '$fn.isWorkTime()' },
  { label: '上报人工单统计', value: '$fn.caseNum()' },
];
const RuleConfig = props => {
  const { visible, handleCancel, fieldList, onSubumit, RuleContent, flag, flowID } = props;
  const [rule, setRule] = useState([]);
  const [expandedKey, setExpandedKey] = useState(''); // 默认展开项
  const [currentSelectId, setCurrentSelectId] = useState(''); // 选中得节点
  const ruleText = useRef();
  const chooseIndex = useRef(0);
  const [form] = Form.useForm();
  useEffect(() => {
    if (visible) {
      console.log(fieldList, 'fieldList');
      setExpandedKey(fieldList[0].TableName);
      setRule(RuleContent);
      setTimeout(() => {
        console.log(document.getElementById('ruleText'));
        console.log(ruleText.current);
        document
          .getElementById('ruleText')
          .setSelectionRange(RuleContent.length, RuleContent.length); // 重新定位光标
      }, 0);
    } else {
      chooseIndex.current = 0;
      setExpandedKey('');
      setCurrentSelectId('');
      setRule('');
    }
  }, [visible]);
  // 保存线配置
  const onSave = () => {
    RuleValidation({ ruleContent: rule, flowId: flowID }).then(res => {
      if (res.data) {
        onSubumit(rule);
      } else {
        message.error('请检查规则是否正确');
      }
    });
  };
  // 处理树数据
  const mapTree = (val, index) => ({
    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) {
      insert(`{${treeNode.node.key}}`);
    }
    setCurrentSelectId(prop[0]);
  };
  const insert = text => {
    let ednIndex = document.getElementById('ruleText').selectionEnd;
    let rangeIndex = document.getElementById('ruleText').selectionStart;
    console.log(ednIndex, rangeIndex, 'endene');
    setRule(`${rule.slice(0, rangeIndex)}${text}${rule.slice(rangeIndex)}`);
    rangeIndex += text.toString().length;
    ruleText.current.focus();
  };
  const insertFn = value => {
    insert(value);
  };
  const fnListRender = (
    <Menu>
      {fnList.map(item => (
        <Menu.Item key={item.value} onClick={() => insertFn(item.value)}>
          {item.label}
        </Menu.Item>
      ))}
    </Menu>
  );
  return (
    <div>
      <Modal
        title="规则配置"
        visible={visible}
        onOk={onSave}
        width="740px"
        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}>
            {flag == 1 && <div className={styles.title}>符合以下条件时工单扭转到对应的节点</div>}
            <div className={styles.textAreaBox}>
              <Dropdown overlay={fnListRender} placement="bottom" arrow>
                <div className={styles.insertFn}>插入函数</div>
              </Dropdown>

              <TextArea
                id="ruleText"
                autoSize={{ minRows: 19, maxRows: 19 }}
                value={rule}
                rows={4}
                ref={ruleText}
                onChange={e => setRule(e.target.value)}
              />
            </div>

            <ul className={styles.tipBox}>
              <li>
                <p>请从左侧面板选择字段或选项</p>
                <p>
                  {'支持'} <i>英文</i> {'模式下运算符（+、-、*、/、>、<、=、!=、<=、>=）'}
                </p>
              </li>

              {flag === 1 ? (
                <>
                  <li>
                    <p>参考场景：</p>
                    <p>当报销金额大于1000时，才能进入所选节点，则可将流转条件设置为：</p>
                    <p>
                      <em>{'报销金额 > 1000'}</em>
                    </p>
                  </li>
                </>
              ) : (
                <li>{`示例：{表名.是否缴费} = ‘是’ and {表名.缴费金额} > 1000`}</li>
              )}
            </ul>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default RuleConfig;
