import React, { useEffect, useState, useRef } from 'react';
import {
  Drawer,
  Form,
  Space,
  Button,
  Input,
  Select,
  Divider,
  Table,
  Tooltip,
  Popconfirm,
  message,
} from 'antd';
import {
  DeleteOutlined,
  EditTwoTone,
  PlusCircleOutlined,
  PlusOutlined,
  SaveFilled,
} from '@ant-design/icons';
import RoalChoose from './nodeModalComponents/RoalChoose';
import Undertaker from './nodeModalComponents/Undertaker';

import RuleConfig from '@/components/RuleConfig';

import styles from './NodeModal.less';
import { GetFormDataSource } from '@/services/workflow/workflow';

const { Option } = Select;
let chnNumChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
let chnUnitSection = ['', '万', '亿', '万亿', '亿亿'];
let chnUnitChar = ['', '十', '百', '千'];
const NodeModal = props => {
  const {
    flowData,
    onSubumit,
    handleCancel,
    visible,
    modalType,
    editMsg,
    newSerialNo,
    nodeNum,
    flowID,
  } = props;
  const [form] = Form.useForm();
  const [showRoal, setShowRoal] = useState(false); // 是否显示选择角色用户弹窗
  const [showRule, setShowRule] = useState(false); // 是否显示节点扭转规则弹窗
  const [showUnderTaker, setShowUnderTaker] = useState(false); // 是否显示选择默认承办人弹窗
  const [editIndex, setEditIndex] = useState(); // 当前编辑默认承办人索引
  const [chooseUser, setChooseUser] = useState(); // 当前编辑角色或者机构的默认承办人
  const [ruleIndex, setRuleIndex] = useState(); // 编辑当前规则索引
  const [nodeMsg, setNodeMsg] = useState({
    NodeName: '',
    NodeType: '',
    SerialNo: '',
    aheadHandle: 1,
    NodeHandling: 1,
    roleList: [],
    nodeDetail: {},
    RuleList: {},
  });

  const [RuleList, setRuleList] = useState([]); // 规则配置列表
  const [flag, setFlag] = useState(0);
  const [fieldList, setFieldList] = useState([]); // 当规则字段
  const allFieldList = useRef([]);
  const nextlinkNodes = useRef([]);
  const previousLinkNodes = useRef([]);
  const talbeList = useRef([]);
  useEffect(() => {
    form.resetFields();
    if (visible) {
      console.log(editMsg, 'editMsg');
      // 获取网关连接的节点
      if (editMsg.NodeType === '21' || editMsg.NodeType === '20') {
        getNextLinkNodes(editMsg.key);
        // getPreviousLinkNodes(editMsg.key);
        setRuleList(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];
          setFlag(flag + 1);
        });
      }

      getFormData();
      console.log(form.getFieldValue(), 'getFieldValue');
    } else {
      nextlinkNodes.current = [];
      previousLinkNodes.current = [];
      talbeList.current = [];
      setRuleList([]);
    }
  }, [visible]);
  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 {
          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 getFormData = () => {
    const { NodeName, NodeType, SerialNo, aheadHandle, NodeHandling } = editMsg;
    console.log(NodeHandling, 'NodeHandling');
    form.setFieldsValue({
      NodeName,
      NodeType,
      SerialNo,
      aheadHandle: aheadHandle || aheadHandle === 0 ? aheadHandle : 1,
      NodeHandling: NodeHandling || NodeHandling === 0 ? NodeHandling : 1,
    });
    setNodeMsg(editMsg);
    setFlag(flag + 1);
  };
  // 提交表单
  const onFinish = () => {
    form.validateFields().then(validate => {
      console.log(validate, 'validate');
      if (validate) {
        validate.SerialNo = Number(validate.SerialNo);
        let nodeDetail = JSON.stringify({
          ...validate,
          NodeType: nodeMsg.NodeType,
          roleList: nodeMsg.roleList,
        });
        let obj = {
          ...validate,
          NodeType: nodeMsg.NodeType,
          roleList: nodeMsg.roleList,
          nodeDetail,
          RuleList,
        };
        onSubumit(obj);
      }
    });
  };
  // 删除角色
  const delUser = (record, index) => {
    let roleList = [...nodeMsg.roleList];
    roleList.splice(index, 1);
    let nodeDetail = JSON.stringify({ ...nodeMsg, roleList, RuleList });
    setNodeMsg({ ...nodeMsg, roleList, nodeDetail, RuleList });
  };
  // 添加角色或机构
  const addUser = selectList => {
    console.log(selectList, 'selectList');
    let nodeDetail = JSON.stringify({ ...nodeMsg, roleList: selectList, RuleList });
    setNodeMsg({ ...nodeMsg, roleList: selectList, nodeDetail, RuleList });
    setShowRoal(false);
  };
  // 添加默认承办人
  const addUnderTaker = (userName, userId) => {
    let list = JSON.parse(JSON.stringify(nodeMsg.roleList));
    console.log(list, 'list');
    console.log(editIndex, 'editIndex');
    list[editIndex].defauletUserName = userName;
    list[editIndex].defaultUserId = userId;
    let nodeDetail = JSON.stringify({ ...nodeMsg, roleList: list, RuleList });
    setNodeMsg({ ...nodeMsg, roleList: list, nodeDetail, RuleList });
    setShowUnderTaker(false);
  };
  // 编辑默认承办人
  const toEdit = (record, index) => {
    setEditIndex(index);
    setChooseUser(record);
    setShowUnderTaker(true);
  };
  // 添加规则
  const addRule = () => {
    console.log(fieldList, 'fieldList');
    let list = JSON.parse(JSON.stringify(RuleList));
    list.push({ RuleContent: '', NextNodeName: '', TableNames: '' });
    setRuleList(list);
  };
  // 删除规则
  const deleRule = index => {
    let list = JSON.parse(JSON.stringify(RuleList));
    list.splice(index, 1);
    setRuleList(list);
  };
  // 规则回填
  const saveRule = e => {
    let list = JSON.parse(JSON.stringify(RuleList));
    console.log(e);
    list[ruleIndex].RuleContent = e;
    console.log(list, 'listlist');
    setRuleList(list);
    setShowRule(false);
  };
  // 网关表单配置监听
  const formChage = (e, index, field) => {
    console.log(e, 'fasdfga');
    let list = JSON.parse(JSON.stringify(RuleList));
    if (field === 'TableNames') {
      list[index][field] = e.join(',');
    } else {
      list[index][field] = e;
    }

    setRuleList(list);
  };
  // 配置当前规则
  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');
    allFieldList.current.forEach(item => {
      if (listfleld.some(ele => ele !== item.TableName)) {
        if (item.TableName && item.TableFieldNames?.length > 0) {
          list.push({
            TableFieldNames: item.TableFieldNames,
            TableName: item.TableName,
          });
        }
      }
    });
    console.log(list, 'listfleld');
    setFieldList(list);
    setRuleIndex(index);
    setShowRule(true);
  };
  // 节点信息监听
  const changeValue = (changedFields, allFields) => {
    if (changedFields[0].name[0] === 'NodeType') {
      setNodeMsg({ ...nodeMsg, roleList: [], RuleList: [] });
      setFlag(flag + 1);
    }
    // console.log(changedFields, allFields, 'allFields');
  };
  // 定义表格
  const columns = [
    {
      title: '名称',
      dataIndex: 'roleName',
      align: 'left',
      ellipsis: {
        showTitle: false,
      },
      render: text => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      align: 'center',
      width: 80,

      filters: [
        {
          text: '角色',
          value: 2,
        },
        {
          text: '机构',
          value: 1,
        },
      ],
      onFilter: (value, record) => record.type === value,
      render: text => (text === 2 ? '角色' : '机构'),
    },
    {
      title: '默认承办人',
      dataIndex: 'defauletUserName',
      align: 'center',
      ellipsis: {
        showTitle: false,
      },
      width: 100,
      render: text => (
        <Tooltip placement="topLeft" title={text}>
          {text || '（无）'}
        </Tooltip>
      ),
    },
    {
      title: '操作',
      align: 'center',
      ellipsis: true,
      width: 60,
      render: (text, record, index) => (
        <>
          <Space>
            <Tooltip title="编辑默认承办人">
              <EditTwoTone
                onClick={() => toEdit(record, index)}
                style={{ fontSize: '16px', color: '#1890FF' }}
              />
            </Tooltip>
            <Tooltip title="删除角色或机构">
              <Popconfirm
                title="是否删除该角色或机构?"
                onConfirm={() => delUser(record, index)}
                onCancel={() => message.error('取消删除')}
                okText="是"
                cancelText="否"
              >
                <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
              </Popconfirm>
            </Tooltip>
          </Space>
        </>
      ),
    },
  ];

  return (
    <>
      <Drawer
        title="节点配置"
        width={550}
        onClose={handleCancel}
        visible={visible}
        bodyStyle={{ paddingBottom: 20 }}
        zIndex={10}
        footer={
          <Space>
            <Button onClick={handleCancel}>取消</Button>
            <Button onClick={onFinish} type="primary">
              确定
            </Button>
          </Space>
        }
      >
        <Divider
          orientation="left"
          style={{
            borderTopColor: '#99bbe8',
            color: '#15428b',
            fontWeight: 700,
            // marginBottom: '30px',
          }}
        >
          {nodeMsg.NodeType === '20' || nodeMsg.NodeType === '21' || nodeMsg.NodeType === '22'
            ? '网关'
            : '节点'}
          信息
        </Divider>
        <div className={styles.titleBox}>
          {/* 条件网关 */}
          <p style={{ display: form?.getFieldValue('NodeType') === '20' ? 'block' : 'none' }}>
            条件网关：客户端填写表单内容，根据设置的条件规则以及出口的目标节点，进行全规则匹配，确定最终流转节点。
          </p>
          {/* 汇合网关 */}
          <p style={{ display: form?.getFieldValue('NodeType') === '21' ? 'block' : 'none' }}>
            汇合网关：等待所有的入口分支流程全部完成，自动移交到下一节点，汇合网关支持规则配置。
          </p>
          {/* 并行网关 */}
          <p style={{ display: form?.getFieldValue('NodeType') === '22' ? 'block' : 'none' }}>
            并行网关：根据网关的连接情况，强制所有出口分支流程必须流转。
          </p>
        </div>
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          // onFieldsChange={changeValue}
        >
          <Form.Item
            label="排序"
            name="SerialNo"
            rules={[{ required: true, message: '请输入排序' }]}
          >
            <Input placeholder="请输入序号" />
          </Form.Item>
          <Form.Item
            label={`${
              nodeMsg.NodeType === '20' || nodeMsg.NodeType === '21' || nodeMsg.NodeType === '22'
                ? '网关'
                : '节点'
            }名称`}
            name="NodeName"
            rules={[
              { required: true, message: '请输入节点名称' },
              // {
              //   validator: (_, value) =>
              //     value.length > 12
              //       ? Promise.reject(new Error('节点名称太长啦~'))
              //       : Promise.resolve(),
              // },
            ]}
          >
            <Input
              placeholder={`请输入${
                nodeMsg.NodeType === '20' || nodeMsg.NodeType === '21' || nodeMsg.NodeType === '22'
                  ? '网关'
                  : '节点'
              }名称`}
            />
          </Form.Item>
          {/* <Form.Item
            label="节点类型"
            name="NodeType"
            rules={[{ required: true, message: '请选择节点类型' }]}
          >
            <Select placeholder="请选择节点类型" disabled={modalType === 'edit'}>
              <Option value="1">开始节点</Option>
              <Option value="0">普通节点</Option>
              <Option value="3">审批节点</Option>
              <Option value="2">结束节点</Option>
              <Option value="4">抄送节点</Option>
              <Option value="20">条件网关</Option>
              <Option value="21">汇合网关</Option>
              <Option value="22">并行网关</Option>
            </Select>
          </Form.Item> */}
          <div style={{ display: 'none' }}>
            <Form.Item label="检查前面在办" name="aheadHandle">
              <Select>
                <Option value={1}>前面有在办不能移交</Option>
                <Option value={0}>前面有在办可以移交</Option>
              </Select>
            </Form.Item>
          </div>
          <div
            style={{
              display:
                form?.getFieldValue('NodeType') === '1' ||
                form?.getFieldValue('NodeType') === '2' ||
                form?.getFieldValue('NodeType') === '20' ||
                form?.getFieldValue('NodeType') === '21' ||
                form?.getFieldValue('NodeType') === '22'
                  ? 'none'
                  : 'block',
            }}
          >
            <Form.Item label="办理方式" name="NodeHandling">
              <Select>
                <Option value={1}>多人接收，一人办理（抢占模式）</Option>
                <Option value={0}>多人接收，多人办理（会签模式）</Option>
                <Option value={2}>一人接收，一人办理</Option>
              </Select>
            </Form.Item>
          </div>
        </Form>

        <div
          style={{
            display:
              form?.getFieldValue('NodeType') === '20' ||
              form?.getFieldValue('NodeType') === '21' ||
              form?.getFieldValue('NodeType') === '22'
                ? 'none'
                : 'block',
          }}
        >
          <Divider
            orientation="left"
            style={{
              borderTopColor: '#99bbe8',
              color: '#15428b',
              fontWeight: 700,
              // margin: '30px 0 10px 0',
            }}
          >
            承办管理
          </Divider>
          <Button
            style={{ marginBottom: '10px', marginLeft: '435px' }}
            onClick={() => {
              setShowRoal(true);
            }}
            type="primary"
          >
            设置
          </Button>
          <Table
            dataSource={nodeMsg.roleList}
            columns={columns}
            rowKey={record => record.roleId}
            bordered
            size="small"
            scroll={{ y: 'calc(100vh - 630px)' }}
            onRow={(record, index) => ({
              onDoubleClick: () => {
                toEdit(record, index);
              },
            })}
            pagination={false}
          />
        </div>
        <div
          style={{
            display:
              form?.getFieldValue('NodeType') !== '20' &&
              form?.getFieldValue('NodeType') !== '21' &&
              form?.getFieldValue('NodeType')
                ? 'none'
                : 'block',
          }}
        >
          <Divider
            orientation="left"
            style={{
              borderTopColor: '#99bbe8',
              color: '#15428b',
              fontWeight: 700,
              // margin: '30px 0 10px 0',
            }}
          >
            规则配置
          </Divider>
          <div className={styles.titleBox}>
            当满足规则配置时，会根据规则流转到对应的节点；
            <br />
            当不设置条件时，默认需要人为选择流转到哪个节点。
          </div>
          <div className={styles.btnAddRule} onClick={addRule}>
            <PlusCircleOutlined style={{ marginRight: '10px' }} />
            添加规则
          </div>
          <div className={styles.ruleContent}>
            {RuleList.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}>
                    <Select
                      style={{ width: '100%' }}
                      value={item.NextNodeName}
                      onChange={e => {
                        formChage(e, index, 'NextNodeName');
                      }}
                    >
                      {nextlinkNodes.current.map(ele => (
                        <Option value={ele.NodeName} 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}>
                    <Tooltip title={item.RuleContent}>
                      {/* <span>{item.RuleContent ? '已设置条件' : '设置条件'} </span> */}
                      <span>{item.RuleContent} </span>
                    </Tooltip>
                  </div>
                  <div className={styles.addIcon}>
                    <PlusOutlined />
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </Drawer>
      <RoalChoose
        roleList={nodeMsg.roleList}
        visible={showRoal}
        handleCancel={() => setShowRoal(false)}
        onSubumit={addUser}
      />
      <Undertaker
        chooseUser={chooseUser}
        visible={showUnderTaker}
        handleCancel={() => setShowUnderTaker(false)}
        onSubumit={addUnderTaker}
      />
      <RuleConfig
        RuleContent={RuleList[ruleIndex]?.RuleContent}
        fieldList={fieldList}
        visible={showRule}
        handleCancel={() => setShowRule(false)}
        onSubumit={e => saveRule(e)}
        flag={1}
      />
    </>
  );
};
export default NodeModal;
