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

const { Option } = Select;

const NodeModal = props => {
  const { onSubumit, handleCancel, visible, modalType, editMsg, newSerialNo, nodeNum } = props;
  const [form] = Form.useForm();
  const [showRoal, setShowRoal] = useState(false); // 是否显示选择角色用户弹窗
  const [showUnderTaker, setShowUnderTaker] = useState(false); // 是否显示选择默认承办人弹窗
  const [editIndex, setEditIndex] = useState(); // 当前编辑默认承办人索引
  const [chooseUser, setChooseUser] = useState(); // 当前编辑角色或者机构的默认承办人
  const [nodeMsg, setNodeMsg] = useState({
    NodeName: '',
    NodeType: '',
    SerialNo: '',
    aheadHandle: 1,
    NodeHandling: 1,
    roleList: [],
  });
  useEffect(() => {
    form.resetFields();
    if (visible) {
      if (modalType === 'edit') {
        getFormData();
      } else {
        console.log(nodeNum, 'nodeNum');
        let type;
        if (nodeNum > 0) {
          type = '0';
        } else {
          type = '1';
        }
        setNodeMsg({ ...nodeMsg, newSerialNo, NodeType: type, roleList: [] });
        form.setFieldsValue({
          SerialNo: newSerialNo,
          NodeType: type,
          aheadHandle: 1,
          NodeHandling: 1,
        });
      }
    }
  }, [visible]);
  // 获取表单回显
  const getFormData = () => {
    setNodeMsg(editMsg);
    console.log(editMsg, 'editMsg');
    const { NodeName, NodeType, SerialNo, aheadHandle, NodeHandling } = editMsg;
    form.setFieldsValue({ NodeName, NodeType, SerialNo, aheadHandle, NodeHandling });
  };
  // 提交表单
  const onFinish = () => {
    form.validateFields().then(validate => {
      if (validate) {
        validate.SerialNo = Number(validate.SerialNo);
        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 = selectList => {
    console.log(selectList, 'selectList');
    setNodeMsg({ ...nodeMsg, roleList: selectList });
    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;
    setNodeMsg({ ...nodeMsg, roleList: list });
    setShowUnderTaker(false);
  };
  // 编辑默认承办人
  const toEdit = (record, index) => {
    setEditIndex(index);
    setChooseUser(record);
    setShowUnderTaker(true);
  };
  // 定义表格
  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={450}
        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',
          }}
        >
          节点信息
        </Divider>
        <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 17 }}>
          <Form.Item
            label="序号"
            name="SerialNo"
            rules={[{ required: true, message: '请输入序号' }]}
          >
            <Input placeholder="请输入序号" />
          </Form.Item>
          <Form.Item
            label="节点名称"
            name="NodeName"
            rules={[
              { required: true, message: '请输入节点名称' },
              // {
              //   validator: (_, value) =>
              //     value.length > 12
              //       ? 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.Item label="检查前面在办" name="aheadHandle">
            <Select>
              <Option value={1}>前面有在办不能移交</Option>
              <Option value={0}>前面有在办也能移交</Option>
            </Select>
          </Form.Item>
          <Form.Item label="节点办理方式" name="NodeHandling">
            <Select>
              <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', marginLeft: '335px' }}
          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}
        />
      </Drawer>
      <RoalChoose
        roleList={nodeMsg.roleList}
        visible={showRoal}
        handleCancel={() => setShowRoal(false)}
        onSubumit={addUser}
      />
      <Undertaker
        chooseUser={chooseUser}
        visible={showUnderTaker}
        handleCancel={() => setShowUnderTaker(false)}
        onSubumit={addUnderTaker}
      />
    </>
  );
};
export default NodeModal;
