import React from 'react';
import { Modal, Select, Form, TreeSelect } from 'antd';
import { RoleType } from '@/Project/constants/index';
const { Option } = Select;
const { TreeNode } = TreeSelect;

function RoleModal(props: any) {
  const { onOk, onCancel, visible, values, roleList, depUserTree } = props;

  const [form] = Form.useForm();

  const handleOk = () => {
    form.validateFields().then((fieldsValue: any) => {
      onOk(fieldsValue);
    });
  };
  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };
  const renderName = (role: any) => {
    let type = RoleType.find(item => item.value == role.role_type)?.name;
    return `${role.name}-${type}`;
  };
  const renderUserSelectTreeNodes = (data: any): React.ReactElement => {
    return data?.map((item: any) => {
      if (item.children) {
        return (
          <TreeNode
            title={item.title}
            key={item.key}
            value={item.value}
            dataRef={item}
            selectable={item.selectable}
          >
            {renderUserSelectTreeNodes(item.children)
            }
          </TreeNode>
        );
      }
      return (
        <TreeNode
          title={item.title}
          key={item.ID}
          value={item.value}
          selectable={item.selectable}
        />
      );
    });
  };

  return (
    <>
      <Modal
        title="设置角色"
        maskClosable={false}
        destroyOnClose={true}
        open={visible}
        onCancel={handleCancel}
        onOk={handleOk}
      >
        <Form labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} form={form}>
          <Form.Item
            label="成员"
            name='user_id'
            initialValue={values?.ID}
            rules={[{ required: true, message: '请选择用户' },
            ]}>
            <TreeSelect
              disabled={Boolean(values?.ID)}
              showSearch
              allowClear
              style={{ width: '100%' }}
              placeholder="请选择用户"
              multiple={false}
              filterTreeNode={(input, option) => { return option.props.title === input }}
              dropdownStyle={{ maxHeight: 348, overflow: 'auto' }}>
              {renderUserSelectTreeNodes(depUserTree)}
            </TreeSelect>
          </Form.Item>
          <Form.Item
            label="角色"
            name='role_ids'
            initialValue={(values?.Role || []).map((item: any) => item.ID).filter((id: any) => id != '0')}
          >
            <Select
              mode="multiple"
              filterOption={(input, option: any) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {roleList?.map((item: any) => (
                <Option key={item.id} value={item.id} >
                  {renderName(item)}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}
export default RoleModal;
