import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle } from 'react';

import { Input, Select, Divider, Tooltip, message } from 'antd';
import { DeleteOutlined, PlusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import lodash from 'lodash';
import RuleConfig from '@/components/RuleConfig';
import styles from '../NodeModal.less';
import { GetFormDataSource } from '@/services/workflow/workflow';

let chnNumChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
let chnUnitSection = ['', '万', '亿', '万亿', '亿亿'];
let chnUnitChar = ['', '十', '百', '千'];
const { Option } = Select;

const Confggateway = (props, ref) => {
  const { nodeChage, flowID, editMsg, flowData } = props;
  const [fieldList, setFieldList] = useState([]); // 当规则字段
  const [ruleIndex, setRuleIndex] = useState(); // 编辑当前规则索引
  const [showRule, setShowRule] = useState(false); // 是否显示节点扭转规则弹窗
  const [flag, setFlag] = useState(0); // 用于刷新界面

  const nextlinkNodes = useRef([]); // 获取后面链接的节点
  const previousLinkNodes = useRef([]); // 之前的节点
  const RuleList = useRef([]); // 规则配置列表
  const allFieldList = useRef([]); // 所有字段列表
  const talbeList = useRef([]);
  useImperativeHandle(ref, () => ({
    getParmar,
  }));
  useEffect(() => {
    nextlinkNodes.current = [];
    previousLinkNodes.current = [];
    RuleList.current = [];
    allFieldList.current = [];
    talbeList.current = [];
    // 获取网关连接的节点
    if (editMsg.NodeType === '21' || editMsg.NodeType === '20') {
      getNextLinkNodes(editMsg.key);

      // getPreviousLinkNodes(editMsg.key);

      RuleList.current = editMsg.RuleList;

      // 获取表数据
      GetFormDataSource({ flowID }).then(res => {
        let list = new Set(talbeList.current);
        allFieldList.current = [];
        res.data.forEach(item => {
          if (!allFieldList.current.some(ele => ele.TableName === item.TableName)) {
            allFieldList.current.push({
              TableFieldNames: item.TableFieldNames,
              TableName: item.TableName,
            });
          }
          list.add(item.TableName);
          // if (previousLinkNodes.current.some(ele => ele.NodeName === item.NodeName)) {
          //   list.add(item.TableName);
          // }
        });
        talbeList.current = [...list];
        console.log(nextlinkNodes.current, 'nextlinkNodes.current');
        setFlag(flag + 1);
      });
    }
  }, [editMsg]);
  const getParmar = () => ({ RuleList: RuleList.current });
  // 数字转中文
  const SectionToChinese = section => {
    let strIns = '';
    let chnStr = '';
    let unitPos = 0;
    let zero = true;
    while (section > 0) {
      let v = section % 10;
      if (v === 0) {
        if (!zero) {
          zero = true;
          chnStr = chnNumChar[v] + chnStr;
        }
      } else {
        zero = false;
        strIns = chnNumChar[v];
        strIns += chnUnitChar[unitPos];
        chnStr = strIns + chnStr;
      }
      // eslint-disable-next-line no-plusplus
      unitPos++;
      section = Math.floor(section / 10);
    }
    return chnStr;
  };
  // 数字转中文
  const NumberToChinese = num => {
    let unitPos = 0;
    let strIns = '';
    let chnStr = '';
    let needZero = false;

    if (num === 0) {
      return chnNumChar[0];
    }

    while (num > 0) {
      let section = num % 10000;
      if (needZero) {
        chnStr = chnNumChar[0] + chnStr;
      }
      strIns = SectionToChinese(section);
      strIns += section !== 0 ? chnUnitSection[unitPos] : chnUnitSection[0];
      chnStr = strIns + chnStr;
      needZero = section < 1000 && section > 0;
      num = Math.floor(num / 10000);
      // eslint-disable-next-line no-plusplus
      unitPos++;
    }

    return chnStr;
  };
  // 获取被网关连接的节点
  const getNextLinkNodes = key => {
    flowData.linkDataArray.forEach(item => {
      if (item.from === key) {
        let linkNode = flowData.nodeDataArray.find(ele => ele.key === item.to);
        if (linkNode.NodeType === '20') {
          getNextLinkNodes(linkNode.key);
        } else if (!nextlinkNodes.current.some(ele => ele.key === linkNode.key)) {
          nextlinkNodes.current.push(linkNode);
        }
      }
    });
  };
  // 获取当前网关之前所有节点
  const getPreviousLinkNodes = key => {
    flowData.linkDataArray.forEach(item => {
      // 判断节点是否为第一个节点
      let isFistNode = flowData.linkDataArray.some(ele => ele.to === item.form);
      // 当前线的指向节点是当前双击节点并且不是第一节点继续往下找
      if (item.to === key && !isFistNode) {
        // 指向当前节点的节点
        let lastNode = flowData.nodeDataArray.find(ele => ele.key === item.from);
        // 已存节点是否包含指向当前节点的节点
        let hasNode = previousLinkNodes.current.some(ele => ele.key === lastNode.key);
        // 如果没有就存入
        if (!hasNode) {
          previousLinkNodes.current.push(lastNode);
          getPreviousLinkNodes(lastNode.key);
        }
      }
    });
    let list = JSON.parse(JSON.stringify(previousLinkNodes.current));
    previousLinkNodes.current = list.filter(
      item => item.NodeType !== '20' && item.NodeType !== '21',
    );
  };
  // 网关表单配置监听
  const formChage = (e, index, field) => {
    let list = lodash.cloneDeep(RuleList.current);
    if (field === 'TableNames') {
      list[index][field] = e.join(',');
    }
    if (field === 'RuleName') {
      e.persist();
      list[index][field] = e.target.value;
    } else {
      list[index][field] = e;
    }

    // setRuleList(list);
    RuleList.current = list;
    nodeChage('RuleList', list);
    setFlag(flag + 1);
  };
  // 添加规则
  const addRule = () => {
    console.log(fieldList, 'fieldList');
    console.log(nextlinkNodes.current, RuleList.current, 'nextlinkNodes.current');
    if (nextlinkNodes.current.length === 0) {
      message.error('请连接需要添加规则的节点');
      return;
    }
    if (RuleList.current.length === nextlinkNodes.current.length) {
      message.error('请连接需要添加规则的节点');
      return;
    }
    let list = JSON.parse(JSON.stringify(RuleList.current));
    list.push({ RuleContent: '', NextNodeId: '', TableNames: '', RuleName: '' });
    // setRuleList(list);
    RuleList.current = list;
    nodeChage('RuleList', list);
    setFlag(flag + 1);
  };
  // 删除规则
  const deleRule = index => {
    let list = JSON.parse(JSON.stringify(RuleList.current));
    list.splice(index, 1);
    // setRuleList(list);
    RuleList.current = list;
    nodeChage('RuleList', list);
    setFlag(flag + 1);
  };
  // 配置当前规则
  const editRule = (msg, index) => {
    console.log(msg, 'masgasdg');
    // let listfleld = msg.TableNames.split(',');

    let listfleld = talbeList.current;
    let list = [
      {
        TableFieldNames: [
          '上报人名称',
          '上报人部门',
          '上报站点',
          '处理站点',
          '更新时间',
          '上报时间',
        ],
        TableName: '内部字段',
      },
    ];
    console.log(listfleld, allFieldList.current, 'listfleld1111');
    listfleld.forEach(item => {
      console.log(allFieldList.current.find(ele => ele.TableName === item), 'aaaaaa');
      let obj = allFieldList.current.find(ele => ele.TableName === item);
      if (obj.TableName && obj.TableFieldNames?.length > 0) {
        list.push({
          TableFieldNames: obj.TableFieldNames,
          TableName: obj.TableName,
        });
      }
    });
    console.log(list, 'listfleld');
    setFieldList(list);
    setRuleIndex(index);
    setShowRule(true);
  };
  // 规则回填
  const saveRule = e => {
    let list = JSON.parse(JSON.stringify(RuleList.current));
    console.log(e);
    list[ruleIndex].RuleContent = e;
    console.log(list, 'listlist');
    // setRuleList(list);
    RuleList.current = list;
    nodeChage('RuleList', list);
    setShowRule(false);
  };
  return (
    <div>
      <Divider
        orientation="left"
        style={{
          borderTopColor: '#99bbe8',
          color: '#15428b',
          fontWeight: 700,
          // margin: '30px 0 10px 0',
        }}
      >
        规则配置
      </Divider>
      <div className={styles.titleBox}>
        当满足规则配置时，会根据规则流转到对应的节点；
        当不设置条件时，默认需要人为选择流转到哪个节点。
      </div>
      <div className={styles.btnAddRule} onClick={addRule}>
        <PlusCircleOutlined style={{ marginRight: '10px' }} />
        添加规则
      </div>
      <div className={styles.ruleContent}>
        {RuleList.current.map((item, index) => (
          <div className={styles.ruleBox} key={index}>
            <div className={styles.ruleTitle}>
              <div className={styles.textContet}>规则{NumberToChinese(index + 1)}</div>
              <DeleteOutlined style={{ cursor: 'pointer' }} onClick={() => deleRule(index)} />
            </div>
            <div className={styles.formBox}>
              <div className={styles.label}>规则名称：</div>
              <div className={styles.item}>
                <Input
                  style={{ width: '100%' }}
                  value={item.RuleName}
                  placeholder="请输入规则名称"
                  onChange={e => {
                    formChage(e, index, 'RuleName');
                  }}
                />
              </div>
            </div>
            <div className={styles.formBox}>
              <div className={styles.label}>设置规则流转到：</div>
              <div className={styles.item}>
                <Select
                  style={{ width: '100%' }}
                  value={item.NextNodeId}
                  onChange={e => {
                    formChage(e, index, 'NextNodeId');
                  }}
                >
                  {nextlinkNodes.current.map(ele => (
                    <Option value={ele.NodeId} key={ele.NodeName}>
                      {ele.NodeName}
                    </Option>
                  ))}
                </Select>
              </div>
            </div>
            {/* <div className={styles.formBox}>
                  <div className={styles.label}>选择业务表单：</div>
                  <div className={styles.item}>
                    <Select
                      style={{ width: '100%' }}
                      onChange={e => {
                        formChage(e, index, 'TableNames');
                      }}
                      value={item.TableNames ? item.TableNames.split(',') : []}
                      mode="multiple"
                    >
                      {talbeList.current.map(ele => (
                        <Option value={ele} key={ele}>
                          {ele}
                        </Option>
                      ))}
                    </Select>
                  </div>
                </div> */}
            <div className={styles.buttonBox} onClick={() => editRule(item, index)}>
              <div
                className={styles.setButton}
                style={{ textAlign: item.RuleContent ? 'left' : 'center' }}
              >
                <Tooltip title={item.RuleContent}>
                  <span>{item.RuleContent ? item.RuleContent : '设置条件'} </span>
                  {/* <span>{item.RuleContent} </span> */}
                </Tooltip>
              </div>
              <div className={styles.addIcon}>
                <PlusOutlined />
              </div>
            </div>
          </div>
        ))}
      </div>
      <RuleConfig
        RuleContent={RuleList.current[ruleIndex]?.RuleContent}
        fieldList={fieldList}
        visible={showRule}
        handleCancel={() => setShowRule(false)}
        onSubumit={e => saveRule(e)}
        flag={1}
        flowID={flowID}
      />
    </div>
  );
};

export default forwardRef(Confggateway);
