import React, { useEffect, useState, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import classnames from 'classnames';
import { Tabs, Input, message, Modal } from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import FlowModal from './workFlowComponents/FlowModal';
import FlowGroupModal from './workFlowComponents/FlowGroupModal';
import styles from './WorkflowHomePage.less';
import { WFGetAllFlow, GetFlowNode, DeleteFlow } from '@/services/workflow/workflow';

const { Search } = Input;
const { confirm } = Modal;

const WorkflowHomePage = () => {
  const history = useHistory();
  const [flowList, setFlowList] = useState([]); // 流程列表
  const [currentList, setCurrentList] = useState([]); // 当前tab显示列表

  const [modalType, setModalType] = useState(''); // 弹窗类型是编辑还是新增
  const [editMsg, setEditMsg] = useState({}); // 弹窗编辑回显
  const [editIndex, setEditIndex] = useState(); // 编辑流程组得索引
  const [flowNames, setFlowNames] = useState([]);
  const [visible, setVisible] = useState({
    FlowModal: false,
    FlowGroupModal: false,
  }); // 弹窗显示
  const [flag, setFlag] = useState(0);
  const activeKey = useRef(null);
  useEffect(() => {
    console.log(history.location.state, 'history.location.state');
    if (history.location.state) {
      activeKey.current = history.location.state.activeKey;
    }
    getFlowList();
  }, []);
  // 获取所有数据
  const getFlowList = () => {
    WFGetAllFlow().then(res => {
      if (res.code === 0) {
        let flowNameList = [];
        let list = res.data.map(item => {
          item.children.forEach(ele => {
            flowNameList.push(ele.FlowName);
          });
          item.isOld = true;
          return item;
        });
        setFlowList(list);
        console.log(activeKey.current, 'activeKey');
        if (activeKey.current) {
          setCurrentList(list.filter(item => item.name === activeKey.current));
        } else {
          setCurrentList(list);
        }
        console.log(flowNameList, 'flowNameList');
        setFlowNames(flowNameList);
      }
    });
  };

  // 弹窗显示控制
  const showModal = (key, value) => {
    setVisible({ ...visible, [key]: value });
  };
  // 查看所有
  const chageAll = () => {
    // setActiveKey(null);
    activeKey.current = null;
    setCurrentList(flowList);
  };
  // 搜索
  const onSearch = val => {
    let copyList = JSON.parse(JSON.stringify(flowList));
    let list = activeKey.current
      ? copyList.filter(item => item.name === activeKey.current)
      : copyList;
    if (val) {
      list.forEach(item => {
        item.children = item.children.filter(ele => ele.FlowName.includes(val));
      });
    }
    setCurrentList(list);
    setFlag(flag + 1);
  };
  // 切换tab
  const onChange = val => {
    let copyList = JSON.parse(JSON.stringify(flowList));
    let list = copyList.filter(item => item.name === val);
    activeKey.current = val;
    setCurrentList(list);

    // setActiveKey(val);
  };
  // 编辑流程
  const editFlow = (val, e) => {
    e.stopPropagation();
    showModal('FlowModal', true);
    setModalType('edit');
    setEditMsg(val);
  };
  // 新增流程
  const addFlow = val => {
    showModal('FlowModal', true);
    setEditMsg(val);
    setModalType('add');
  };
  // 添加流程组
  const addFlowGroup = () => {
    showModal('FlowGroupModal', true);
    setModalType('add');
  };
  // 编辑流程组
  const eiditFlowGroup = (val, index) => {
    setEditIndex(index);
    showModal('FlowGroupModal', true);
    setModalType('edit');
    setEditMsg(val);
  };
  // 编辑组回调
  const groupCallBack = val => {
    activeKey.current = val;
    showModal('FlowGroupModal', false);
    // 编辑老数据需要掉接口更新新数据手动修改数据，新增插入一条数据
    if (modalType === 'edit' && editMsg.isOld) {
      getFlowList();
    } else if (modalType === 'edit') {
      let newflowList = [...flowList];
      newflowList[editIndex].name = val;
      setFlowList(newflowList);
      setCurrentList(newflowList.filter(item => item.name === activeKey.current));
    } else {
      setCurrentList([{ name: val, children: [] }]);
      setFlowList([...flowList, { name: val }]);
    }
  };
  const chooseNode = val => {
    console.log(val, 'val');
    GetFlowNode({ flowID: val.FlowID }).then(res => {
      if (res.code === 0) {
        res.data.Nodes.forEach(item => {
          item.nodeDetail = JSON.stringify(item);
        });
        history.push({
          pathname: '/biz/workflow/flowBoard',
          state: {
            flowData: { ...res.data, flowName: val.FlowName },
            flowID: val.FlowID,
            chartLoading: false,
            activeKey: activeKey.current,
          },
        });
      } else {
        message.error(res.msg);
      }
    });
  };
  // 删除流程
  const delFlow = (val, e) => {
    e.stopPropagation();
    confirm({
      title: '确定要删除吗？',
      icon: <ExclamationCircleOutlined />,
      content: '',
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk() {
        DeleteFlow({ FlowId: val.FlowID })
          .then(res => {
            if (res.code === 0) {
              getFlowList();
              message.success('删除成功');
            } else {
              message.error(res.msg);
            }
          })
          .catch(() => {
            message.error('网络异常请稍后再试');
          });
      },
      onCancel() {},
    });
  };
  // tab栏选项渲染
  const tabRender = (val, index) => (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-around' }}>
      {val.name}({val.count})
      {val.name === activeKey.current ? (
        <EditOutlined onClick={() => eiditFlowGroup(val, index)} style={{ marginLeft: '5px' }} />
      ) : (
        ''
      )}
    </div>
  );
  return (
    <div className={styles.pageContent}>
      <div className={styles.headerBox}>
        <div className={styles.left}>
          <div
            className={classnames(styles.allFlows, { [styles.allFlowsChoose]: !activeKey.current })}
            onClick={chageAll}
          />
          <div className={styles.flows}>
            <Tabs activeKey={activeKey.current} type="card" onChange={onChange} animated={false}>
              {flowList.map((item, index) => (
                <Tabs.TabPane tab={tabRender(item, index)} key={item.name} />
              ))}
            </Tabs>
          </div>
        </div>
        <div className={styles.right} onClick={addFlowGroup}>
          <div className={styles.icon} />
          <div>新增分组</div>
        </div>
      </div>
      <div className={styles.controlBox}>
        <div className={styles.left}>
          总计：
          <span>{currentList.reduce((sum, p) => p.children.length + sum, 0)}</span>
        </div>
        <div className={styles.right}>
          <div className={styles.btn} onClick={() => addFlow(currentList[0])}>
            <PlusOutlined style={{ marginLeft: '5px' }} />
            新增流程
          </div>
          <Search
            placeholder="输入关键字搜索"
            allowClear
            onSearch={onSearch}
            style={{
              width: 490,
            }}
          />
        </div>
      </div>
      <div className={styles.flowTable}>
        {currentList.map((item, index) => (
          <div className={styles.flowGroup} key={item.name}>
            <div
              className={styles.header}
              style={{ display: item.children.length > 0 ? 'flex' : 'none' }}
            >
              <div className={styles.line} />
              <div className={styles.name}>{item.name}</div>
            </div>
            <div className={styles.groupBox}>
              {item.children.map(ele => (
                <div
                  className={styles.flowBox}
                  type={(index + 1) % 5}
                  key={ele.Code}
                  onClick={() => chooseNode(ele)}
                >
                  <div className={styles.header}>
                    <div className={styles.title}>{ele.FlowName}</div>
                    <div className={styles.delete}>
                      <DeleteOutlined onClick={e => delFlow(ele, e)} />
                    </div>
                    <div className={styles.editBtn} onClick={e => editFlow(ele, e)}>
                      <EditOutlined />
                      编辑
                    </div>
                  </div>
                  <div className={styles.imgBox}>
                    <img
                      src={`http://192.168.12.178:8085/${
                        ele.PreviewImage
                      }?v=${new Date().getTime()}`}
                      alt=""
                    />
                  </div>
                  <div className={styles.bottom}>
                    <div className={styles.left}>创建人：{ele.CreateUser || '--'}</div>
                    <div className={styles.right}>更新于{ele.UpdateTime || '--'}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
      {/* 添加流程弹窗 */}
      <FlowModal
        visible={visible.FlowModal}
        msg={editMsg}
        modalType={modalType}
        handleCancel={() => showModal('FlowModal', false)}
        keep={flowNames}
        treeData={flowList}
        onSubumit={() => {
          showModal('FlowModal', false);
          getFlowList();
        }}
      />
      {/* 创建分组弹窗 */}
      <FlowGroupModal
        visible={visible.FlowGroupModal}
        msg={editMsg}
        modalType={modalType}
        handleCancel={() => showModal('FlowGroupModal', false)}
        treeData={flowList}
        keep={flowNames}
        onSubumit={val => groupCallBack(val)}
      />
    </div>
  );
};

export default WorkflowHomePage;
