import React, { useEffect, useState } from 'react';
import {
  Drawer,
  Form,
  Space,
  Button,
  Input,
  notification,
  Select,
  Divider,
  Table,
  Tooltip,
  Popconfirm,
  message,
} from 'antd';
import { DeleteOutlined, EditTwoTone } from '@ant-design/icons';
import RoalChoose from './nodeModalComponents/RoalChoose';
const { Option } = Select;

const NodeModal = props => {
  const { onSubumit, handleCancel, visible, modalType, editMsg } = props;
  const [form] = Form.useForm();
  const [showRoal, setShowRoal] = useState(false); // 是否显示选择角色用户弹窗
  const [isEdit, setIsEdit] = useState(); // 是编辑角色还是添加角色
  const [chooseUser, setChooseUser] = useState(); // 当前编辑角色或者机构的默认承办人
  const [nodeMsg, setNodeMsg] = useState({
    NodeName: '',
    NodeType: '',
    roleList: [],
  });
  useEffect(() => {
    form.resetFields();
    if (visible) {
      if (modalType === 'edit') {
        getFormData();
      } else {
        setNodeMsg({ ...nodeMsg, roleList: [] });
      }
    }
  }, [visible]);
  // 获取表单回显
  const getFormData = () => {
    setNodeMsg(editMsg);
    const { NodeName, NodeType } = editMsg;
    form.setFieldsValue({ NodeName, NodeType });
  };
  // 提交表单
  const onFinish = () => {
    form.validateFields().then(validate => {
      if (validate) {
        let obj = { ...validate, roleList: nodeMsg.roleList };
        onSubumit(obj);
      }
    });
  };
  // 删除角色
  const delUser = (record, index) => {
    let roleList = [...nodeMsg.roleList];
    roleList.splice(index, 1);
    setNodeMsg({ ...nodeMsg, roleList });
  };
  // 添加用户
  const addUser = (obj, treeLength) => {
    if (obj.roleId === '' || obj.roleName === '' || treeLength === 0) {
      notification.error({
        message: '提示',
        duration: 3,
        description: '请选择角色',
      });
      return;
    }
    // 如果已经有角色就提示
    if (
      nodeMsg.roleList.some(item => item.roleId === obj.roleId) &&
      isEdit === 'add'
    ) {
      notification.error({
        message: '提示',
        duration: 3,
        description: '机构(角色)已存在',
      });
      return;
    }
    // 编辑角色覆盖原有
    let chooseIndex = nodeMsg.roleList.findIndex(
      item => item.roleId === obj.roleId,
    );
    let newList;
    if (chooseIndex === -1) {
      // 添加表格
      setNodeMsg({ ...nodeMsg, roleList: [...nodeMsg.roleList, obj] });
    } else {
      newList = [...nodeMsg.roleList];
      newList[chooseIndex] = obj;
      // 修改表格
      setNodeMsg({ ...nodeMsg, roleList: [...newList] });
    }
    setShowRoal(false);
  };
  // 编辑默认承办人
  const toEdit = record => {
    setIsEdit('edit');
    setChooseUser(record);
    setShowRoal(true);
  };
  // 定义表格
  const columns = [
    {
      title: '机构(角色)名称',
      dataIndex: 'roleName',
      align: 'center',
      ellipsis: {
        showTitle: false,
      },
      render: text => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '默认承办人',
      dataIndex: 'defauletUserName',
      align: 'center',
      ellipsis: {
        showTitle: false,
      },
      render: text => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '操作',
      align: 'center',
      ellipsis: true,
      render: (text, record, index) => (
        <>
          <Space>
            <Tooltip title="删除角色">
              <Popconfirm
                title="是否删除该角色?"
                onConfirm={() => delUser(record, index)}
                onCancel={() => message.error('取消删除')}
                okText="是"
                cancelText="否"
              >
                <DeleteOutlined
                  style={{ fontSize: '16px', color: '#e86060' }}
                />
              </Popconfirm>
            </Tooltip>
            <Tooltip title="修改默认承办人">
              <EditTwoTone
                onClick={() => toEdit(record)}
                style={{ fontSize: '16px', color: '#1890FF' }}
              />
            </Tooltip>
          </Space>
        </>
      ),
    },
  ];
  return (
    <>
      <Drawer
        title="节点配置"
        width={450}
        onClose={handleCancel}
        visible={visible}
        bodyStyle={{ paddingBottom: 20 }}
        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',
          }}
        >
          编辑节点
        </Divider>
        <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 18 }}>
          <Form.Item
            label="节点名称"
            name="NodeName"
            rules={[
              { required: true, message: '请输入节点名称' },
              {
                validator: (_, value) =>
                  value.length > 6
                    ? Promise.reject(new Error('节点名称太长啦~'))
                    : Promise.resolve(),
              },
            ]}
          >
            <Input placeholder="请输入节点名称（最多6个字）" />
          </Form.Item>
          <Form.Item
            label="节点类型"
            name="NodeType"
            rules={[{ required: true, message: '请选择节点类型' }]}
          >
            <Select placeholder="请选择节点类型">
              <Option value="1">开始节点</Option>
              <Option value="0">普通节点</Option>
              <Option value="2">结束节点</Option>
            </Select>
          </Form.Item>
        </Form>
        <Divider
          orientation="left"
          style={{
            borderTopColor: '#99bbe8',
            color: '#15428b',
            fontWeight: 700,
            margin: '30px 0 10px 0',
          }}
        >
          角色用户列表
        </Divider>
        <Button
          style={{ marginBottom: '10px' }}
          onClick={() => {
            setShowRoal(true);
            setIsEdit('add');
          }}
          type="primary"
        >
          添加
        </Button>
        <Table
          dataSource={nodeMsg.roleList}
          columns={columns}
          rowKey={record => record.roleId}
          bordered
          size="small"
          scroll={{ y: 'calc(100vh - 550px)' }}
          onRow={record => ({
            onDoubleClick: () => {
              toEdit(record);
            },
          })}
          pagination={false}
        />
      </Drawer>
      <RoalChoose
        visible={showRoal}
        modalType={isEdit}
        chooseUser={chooseUser}
        handleCancel={() => setShowRoal(false)}
        onSubumit={addUser}
      />
    </>
  );
};
export default NodeModal;
