import React, { useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { reloadFlowNodes, removeFlowNodeExtend } from '@/services/flow/flow';
import { Space, Table, Popconfirm, Tooltip, notification, message, Button, Spin } from 'antd';
import { RollbackOutlined, EditTwoTone, ControlOutlined, DeleteOutlined } from '@ant-design/icons';
import PageContainer from '@/components/BasePageContainer';
import NodeEdit from './flowNodeComponents/NodeEdit';
import AuxiliaryView from './flowNodeComponents/AuxiliaryView';
import styles from './flowNode.less';

const FlowNode = () => {
  const history = useHistory();
  const { flowName, pickItemIndex } = history.location.state;
  const [visible, setVisible] = useState({
    nodeEdit: false,
    auxiliaryView: false,
  }); // 弹窗显示
  const [tableData, setTableData] = useState([]); // 流程对应的回显的表格
  const [expandedRowKeys, setExpandedRowKeys] = useState([]); // 展开的表格的key
  const [nodeMsg, setNodeMsg] = useState(); // 保存节点信息
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    getData();
  }, []);
  // 弹窗显示控制
  const showModal = (key, value) => {
    setVisible({ ...visible, [key]: value });
  };
  // 获取数据
  const getData = () => {
    setLoading(true);
    reloadFlowNodes({ flowName }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        setTableData(res.data);
        // 存入需要展开得节点
        setExpandedRowKeys(res.data.map(item => item.GroupName));
      }
    });
  };
  // 清除节点
  const delNode = record => {
    removeFlowNodeExtend({ flowNodeExtendID: record.extendID })
      .then(res => {
        if (res.code === 0) {
          getData();
          notification.success({
            message: '提示',
            duration: 3,
            description: '清除成功',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: res.msg,
          });
        }
      })
      .catch(() => {
        notification.error({
          message: '提示',
          duration: 3,
          description: '网络异常',
        });
      });
  };
  // 控制表格的展开跟收起
  const onUnfold = (expanded, record) => {
    const data = [...expandedRowKeys];
    let index = data.indexOf(record.GroupName);
    if (expanded) {
      data.push(record.GroupName);
    } else {
      data.splice(index, 1);
    }
    setExpandedRowKeys(data);
  };
  // 表格内文案样式
  const textStyleOne = (text, record) => {
    if (record.colorType === 2) {
      return 'red';
    }
    if (text === '(未配置)') {
      return 'grey';
    }
    return '000000D9';
  };

  // 定义展开的表格
  const createUnfoldTable = itemTable => {
    const columns = [
      {
        title: '节点名称',
        dataIndex: 'name',
        width: 149,
        align: 'left',
        render: (text, record) => (
          <div
            style={{
              paddingLeft: 60,
              color: record.colorType === 2 ? 'red' : '#000000D9',
            }}
          >
            {text}
          </div>
        ),
      },
      {
        title: '节点别名',
        dataIndex: 'aliasName',
        align: 'center',
        width: 80,
        ellipsis: {
          showTitle: true,
        },
        render: (text, record) => (
          <Tooltip placement="topLeft" title={text}>
            <span style={{ color: textStyleOne(text, record) }}>{text}</span>
          </Tooltip>
        ),
      },
      {
        title: '移交方式',
        dataIndex: 'extendHandover',
        align: 'center',
        width: 100,
        render: (text, record) => <span style={{ color: textStyleOne(text, record) }}>{text}</span>,
      },
      {
        title: '节点类型',
        dataIndex: 'extendNodeType',
        align: 'center',
        width: 80,
        render: (text, record) => <span style={{ color: textStyleOne(text, record) }}>{text}</span>,
      },
      {
        title: '工单主表',
        dataIndex: 'extendTableName',
        width: 150,
        align: 'center',
        ellipsis: {
          showTitle: true,
        },
        render: (text, record) => (
          <Tooltip placement="topLeft" title={text}>
            <span style={{ color: textStyleOne(text, record) }}>{text}</span>
          </Tooltip>
        ),
      },
      {
        title: '查看字段',
        dataIndex: 'extendSeeFields',
        align: 'center',
        width: 80,
        render: (text, record) => (
          <span style={{ color: record.colorType === 2 ? 'red' : '#000000D9' }}>{text}</span>
        ),
      },
      {
        title: '字段',
        dataIndex: 'extendFields',
        align: 'center',
        width: 80,
        render: (text, record) => (
          <span style={{ color: record.colorType === 2 ? 'red' : '#000000D9' }}>{text}</span>
        ),
      },
      {
        title: '外部字段',
        dataIndex: 'outFields',
        key: 'outFields',
        align: 'center',
        width: 100,
        render: text => (
          <span
            style={{
              display: 'inline-block',
              width: '80px',
              color: Number(text) > 0 ? 'red' : '',
              backgroundColor: Number(text) > 0 ? 'yellow' : '',
            }}
          >
            {text}
          </span>
        ),
      },

      {
        title: '补正',
        dataIndex: 'extendEditableLater',
        align: 'center',
        width: 80,
        render: (text, record) => (
          <span style={{ color: record.colorType === 2 ? 'red' : '#000000D9' }}>{text}</span>
        ),
      },
      {
        title: '可退',
        dataIndex: 'extendRollbackable',
        align: 'center',
        width: 80,
        render: (text, record) => (
          <span style={{ color: record.colorType === 2 ? 'red' : '#000000D9' }}>{text}</span>
        ),
      },
      {
        title: '退至',
        dataIndex: 'extendRollbackNode',
        align: 'center',
        width: 80,
        ellipsis: {
          showTitle: true,
        },
        render: (text, record) => (
          <Tooltip placement="topLeft" title={text}>
            <span style={{ color: record.colorType === 2 ? 'red' : '#000000D9' }}>{text}</span>
          </Tooltip>
        ),
      },
      {
        title: '评级移交',
        dataIndex: 'tranferable',
        align: 'center',
        width: 80,
        render: (text, record) => (
          <span style={{ color: record.colorType === 2 ? 'red' : '#000000D9' }}>{text}</span>
        ),
      },
      {
        title: '显示事件信息',
        dataIndex: 'eventInformation',
        align: 'center',
        width: 80,
        render: (text, record) => (
          <span style={{ color: record.colorType === 2 ? 'red' : '#000000D9' }}>{text}</span>
        ),
      },
      {
        title: '操作',
        align: 'center',
        ellipsis: true,
        width: 150,
        render: record => (
          <>
            <Space>
              {record.ID !== 0 && (
                <>
                  <Tooltip title="修改节点">
                    <EditTwoTone
                      onClick={() => {
                        showModal('nodeEdit', true);
                        setNodeMsg(record);
                      }}
                      style={{ fontSize: '16px', color: '#1890FF' }}
                    />
                  </Tooltip>
                  <Tooltip title="节点辅助视图">
                    <ControlOutlined
                      onClick={() => {
                        showModal('auxiliaryView', true);
                        setNodeMsg(record);
                      }}
                      style={{ fontSize: '16px', color: '#1890FF' }}
                    />
                  </Tooltip>
                </>
              )}
              <Tooltip title="清除节点配置">
                <Popconfirm
                  title="是否清除该节点配置?"
                  onConfirm={() => delNode(record)}
                  onCancel={() => message.error('取消清除')}
                  okText="是"
                  cancelText="否"
                >
                  <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
                </Popconfirm>
              </Tooltip>
            </Space>
          </>
        ),
      },
    ];
    return (
      <Table
        className={styles.unfoldTable}
        rowKey={record => record.name}
        columns={columns}
        bordered
        size="small"
        showHeader={false}
        dataSource={itemTable}
        pagination={false}
        onRow={record => ({
          onDoubleClick: () => {
            if (record.ID !== 0) {
              showModal('nodeEdit', true);
              setNodeMsg(record);
            }
          },
        })}
      />
    );
  };
  // 返回
  const backFlow = () => {
    history.push({
      pathname: '/bsmanger/workOrder/flow',
      state: { pickItemIndex },
    });
  };
  // 定义表格
  const columns = [
    {
      title: '节点名称',
      dataIndex: 'GroupName',
      width: 100,
      align: 'left',
      render: (text, record) => (
        <a style={{ fontWeight: 'bold' }}>
          {text}({record.Items.length ? record.Items.length : 0}个)
        </a>
      ),
    },
    {
      title: '节点别名',
      align: 'center',
      width: 80,
    },
    {
      title: '移交方式',
      align: 'center',
      width: 100,
    },
    {
      title: '节点类型',
      align: 'center',
      width: 80,
    },
    {
      title: '工单主表',
      align: 'center',
      width: 150,
    },
    {
      title: '查看字段',
      width: 80,
      align: 'center',
    },
    {
      title: '字段',
      align: 'center',
      width: 80,
    },
    {
      title: '外部字段',
      dataIndex: 'outFields',
      key: 'outFields',
      align: 'center',
      width: 100,
    },
    {
      title: '补正',
      align: 'center',
      width: 80,
    },
    {
      title: '可退',
      align: 'center',
      width: 80,
    },
    {
      title: '退至',
      align: 'center',
      width: 80,
    },
    {
      title: '评级移交',
      align: 'center',
      width: 80,
    },
    {
      title: '显示事件信息',
      align: 'center',
      width: 80,
    },
    {
      title: '操作',
      align: 'center',
      width: 150,
    },
  ];

  return (
    <PageContainer>
      <div className={styles.NodeContent}>
        <div className={styles.header}>
          <div className={styles.nodeTitle}>{flowName}-流程节点配置</div>
          <div className={styles.buttonBox}>
            <Button type="primary" onClick={() => backFlow()}>
              <RollbackOutlined />
              返回
            </Button>
          </div>
        </div>
        <Spin spinning={loading} tip="loading...">
          <Table
            dataSource={tableData}
            columns={columns}
            rowKey={record => record.GroupName}
            size="small"
            showHeader
            scroll={{ y: '100vh-150px' }}
            expandable={{
              expandedRowRender: record => createUnfoldTable(record.Items),
            }}
            expandedRowKeys={expandedRowKeys}
            onExpand={onUnfold}
            pagination={false}
          />
        </Spin>

        <NodeEdit
          visible={visible.nodeEdit}
          msg={nodeMsg}
          handleCancel={() => showModal('nodeEdit', false)}
          onSubumit={() => {
            showModal('nodeEdit', false);
            getData();
          }}
        />
        <AuxiliaryView
          visible={visible.auxiliaryView}
          msg={nodeMsg}
          handleCancel={() => showModal('auxiliaryView', false)}
        />
      </div>
    </PageContainer>
  );
};

export default FlowNode;
