import React, { useEffect, useState } from 'react';
import { reloadFlowTimers, removeFlowTimer, reloadFlowNodes } from '@/services/flow/flow';
import {
  Table,
  Modal,
  Space,
  Tooltip,
  Popconfirm,
  Button,
  notification,
  message,
  Spin,
} from 'antd';
import { EditTwoTone, PlusOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import AddModal from './timelimitComponents/AddModal';
import styles from '../flow.less';

const Timelimit = props => {
  const { handleCancel, visible, msg, allDisabled } = props;
  const [tableData, setTableData] = useState([]); // 回显的表格
  const [viewModal, setViewModal] = useState(false); // 编辑模态框
  const [modalType, setModalType] = useState(''); // 模态框是编辑还是修改的状态
  const [editMsg, setEditMsg] = useState({}); // 保存编辑的信息
  const [title, setTitle] = useState('');
  const [finishNodes, setFinishNodes] = useState([]);
  const [flowId, setFlowId] = useState('');
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    if (visible) {
      console.log(msg);
      setFlowId(msg.ID);
      setTitle(`${msg.name}`);
      getData();
    }
  }, [visible]);
  // 数据初始化
  const getData = () => {
    setLoading(true);
    reloadFlowTimers({ flowName: msg.name }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        setTableData(res.data);

        setFinishNodes(res.data.map(item => item.EndNode));
      }
    });
  };
  // 编辑
  const toEdit = val => {
    setViewModal(true);
    setModalType('edit');
    setEditMsg(val);
  };
  // 删除
  const delRow = record => {
    removeFlowTimer({ flowTimerID: record.ID })
      .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 columns = [
    {
      title: '规则名称',
      dataIndex: 'Name',
      align: 'center',
    },
    {
      title: '开始节点',
      dataIndex: 'StartNode',
      align: 'center',
    },
    {
      title: '结束节点',
      dataIndex: 'EndNode',
      align: 'center',
    },
    {
      title: '默认时限',
      dataIndex: 'TimeLimit',
      align: 'center',
    },
    {
      title: '时限指派字段',
      dataIndex: 'TimeLimitField',
      align: 'center',
      render: text => (
        <span style={{ color: text === '(未配置)' ? 'grey' : '#0000009D' }}>{text}</span>
      ),
    },
    {
      title: '超时记录字段',
      dataIndex: 'TimeoutField',
      align: 'center',
      render: text => (
        <span style={{ color: text === '(未配置)' ? 'grey' : '#0000009D' }}>{text}</span>
      ),
    },
    {
      title: '操作',
      align: 'center',
      ellipsis: true,
      render: record => (
        <>
          <Space>
            <Tooltip title={allDisabled ? '查看流程时限配置' : '修改流程时限配置'}>
              {allDisabled ? (
                <EyeOutlined
                  onClick={() => toEdit(record)}
                  style={{ fontSize: '16px', color: '#1890FF' }}
                />
              ) : (
                <EditTwoTone
                  onClick={() => toEdit(record)}
                  style={{ fontSize: '16px', color: '#1890FF' }}
                />
              )}
            </Tooltip>
            {allDisabled ? null : (
              <Tooltip title="删除流程时限配置">
                <Popconfirm
                  title="是否删除改流程时限配置?"
                  onConfirm={() => delRow(record)}
                  onCancel={() => message.error('取消清除')}
                  okText="是"
                  cancelText="否"
                >
                  <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
                </Popconfirm>
              </Tooltip>
            )}
          </Space>
        </>
      ),
    },
  ];
  return (
    <Modal
      title={`${title}-流程时限配置`}
      visible={visible}
      width="1200px"
      onCancel={handleCancel}
      maskClosable={false}
      centered
      footer={null}
      destroyOnClose
    >
      <div className={styles.timelimitBox}>
        <div className={styles.buttonList}>
          {allDisabled ? null : (
            <Button
              type="primary"
              onClick={() => {
                setViewModal(true);
                setModalType('add');
              }}
              icon={<PlusOutlined />}
            >
              新增流程时限配置
            </Button>
          )}
        </div>
        <Spin spinning={loading} tip="loading...">
          <Table
            dataSource={tableData}
            columns={columns}
            rowKey={record => record.ID}
            bordered
            size="small"
            scroll={{ y: '400px' }}
            onRow={record => ({
              onDoubleClick: () => {
                toEdit(record);
              },
            })}
            pagination={{
              showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
              pageSizeOptions: [10, 20, 50, 100],
              defaultPageSize: 10,
              showQuickJumper: true,
              showSizeChanger: true,
            }}
          />
        </Spin>
      </div>

      <AddModal
        visible={viewModal}
        msg={editMsg}
        title={title}
        flowId={flowId}
        modalType={modalType}
        finishNodes={finishNodes}
        handleCancel={() => setViewModal(false)}
        onSubumit={() => {
          setViewModal(false);
          getData();
        }}
        allDisabled
      />
    </Modal>
  );
};
export default Timelimit;