import React, { useEffect, useState } from 'react';
import { GetRoleUser } from '@/services/platform/workflow';
import {
  Form,
  Modal,
  Input,
  Checkbox,
  Button,
  Pagination,
  Spin,
  Divider,
  notification,
  Empty,
  Tabs,
} from 'antd';
import Tree from '@/components/ExpendableTree';
import { UserOutlined } from '@ant-design/icons';
import styles from '../../../workflow.less';

const CheckboxGroup = Checkbox.Group;
const { TabPane } = Tabs;

const RoalChoose = props => {
  const { onSubumit, handleCancel, visible, modalType, chooseUser } = props;
  const [form] = Form.useForm();
  const [currentSelectId, setCurrentSelectId] = useState(''); // 当前选择节点Id
  const [currentRoalName, setCurrentRoalName] = useState(''); // 当前选择节点名称
  const [treeData, setTreeData] = useState([]); // 左侧树数据
  const [checkedList, setCheckedList] = useState([]); // 选中的数据
  const [plainOptions, setPlainOptions] = useState([]); // 默认的的数据
  const [indeterminate, setIndeterminate] = useState(false); // 全选框的有选择但是没有全选的样式
  const [checkAll, setCheckAll] = useState(false); // 全选框全选样式
  const [total, setTotal] = useState(); // 角色人员条数
  const [loading, setLoading] = useState(false); // 加载时的loading
  const [userList, setUserList] = useState([]); // 编辑选中的用户信息
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [roleType, setRoleType] = useState('2'); // 角色类型
  // 初始化
  useEffect(() => {
    form.resetFields();
    if (visible) {
      setCurrentPage(1);
      if (modalType === 'edit') {
        console.log(chooseUser);
        setRoleType(chooseUser.type.toString());
        form.setFieldsValue({ roleName: chooseUser.roleName });
        setUserList(chooseUser.defaultUserId);
        getData('', 1, pageSize, chooseUser.roleId, chooseUser.type);
      } else {
        getData('', 1, pageSize, 0, 2);
        setRoleType('2');
      }
    } else {
      setUserList([]);
      setTreeData([]);
      setPlainOptions([]);
      setCheckedList([]);
      setIndeterminate(false);
      setCheckAll(false);
    }
  }, [visible]);
  // 默认选中第一个
  useEffect(() => {
    if (treeData.length > 0) {
      setCurrentSelectId(treeData[0].id);
      setCurrentRoalName(treeData[0].name);
      let options = treeData[0].userList.map(item => ({
        label: item.name,
        value: item.id,
      }));
      setPlainOptions(options);
    }
  }, [treeData]);
  // 对默认选中的进行处理
  useEffect(() => {
    if (userList.length > 0 && modalType === 'edit') {
      onChange(userList);
    } else {
      setCheckedList([]);
      setIndeterminate(false);
      setCheckAll(false);
    }
  }, [plainOptions]);

  // 获取左侧树回显
  const getData = (roleName, pageIndex, pageSizes, roleId, Type) => {
    roleName = roleName || '';
    setLoading(true);
    GetRoleUser({
      roleName,
      pageIndex,
      pageSize: pageSizes,
      roleId,
      Type: Number(Type),
    }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        setTreeData(res.data.data);
        setTotal(res.data.count);
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };
  // 查询角色
  const onFinish = () => {
    form.validateFields().then(validate => {
      if (validate) {
        setCurrentSelectId('');
        setPlainOptions([]);
        setCheckedList([]);
        setIndeterminate(false);
        setCheckAll(false);
        setCurrentPage(1);
        getData(validate.roleName, 1, pageSize, 0, roleType);
      }
    });
  };
  // 处理属性结构
  const mapTree = item => {
    const obj = { ...item };
    return {
      title: obj.name,
      key: obj.id,
      disabled: modalType === 'edit' && obj.name !== chooseUser.roleName,
      userList: obj.userList,
    };
  };
  // 选择树
  const onSelect = (selectedKeys, e) => {
    setCurrentRoalName(e.node.title);
    if (selectedKeys[0]) {
      // 选择后对复选框的用户进行重新赋值
      let userLists = [...e.node.userList];
      let options = userLists.map(item => ({
        label: item.name,
        value: item.id,
      }));
      setCurrentSelectId(selectedKeys[0]);
      setPlainOptions(options);
    }
  };
  // 监听分页
  const paginationChange = (page, pageSizes) => {
    // 分页时清空复选框
    setCurrentSelectId('');
    setPlainOptions([]);
    setCheckedList([]);
    setIndeterminate(false);
    setCheckAll(false);
    setCurrentPage(page);
    setPageSize(pageSizes);
    let roleName = form.getFieldValue('roleName');
    getData(roleName, page, pageSizes, 0, roleType);
  };
  // 复选框全选监听
  const onCheckAllChange = e => {
    let allOptions = plainOptions.map(item => item.value);
    setCheckedList(e.target.checked ? allOptions : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };
  // 复选框监听事件
  const onChange = list => {
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < plainOptions.length);
    setCheckAll(list.length === plainOptions.length);
  };
  // tab栏切换回调
  const tabCallback = val => {
    if (val === roleType) {
      return;
    }
    setRoleType(val);
    setPlainOptions([]);
    setCheckedList([]);
    setIndeterminate(false);
    setCheckAll(false);
    setCurrentPage(1);
    getData(form.getFieldValue('roleName'), 1, pageSize, 0, val);
  };
  // 保存选择的角色列表
  const onSave = () => {
    // 默认承办人字符串拼接
    let DeafaultUserName = '';
    checkedList.forEach((item, index) => {
      plainOptions.forEach(element => {
        if (item === element.value) {
          if (index === checkedList.length - 1) {
            DeafaultUserName += `${element.label}`;
          } else {
            DeafaultUserName += `${element.label},`;
          }
        }
      });
    });
    // 存入要插入的数据
    let obj = {
      roleName: currentRoalName,
      roleId: currentSelectId,
      defaultUserId: checkedList,
      defauletUserName: DeafaultUserName,
      type: Number(roleType),
    };
    onSubumit(obj, treeData.length);
  };
  // 角色列表样式
  const roleDom = () =>
    treeData.length > 0 ? (
      <Tree
        blockNode
        autoExpandParent
        onSelect={onSelect}
        selectedKeys={[currentSelectId]}
        treeData={treeData.map(item => mapTree(item))}
      />
    ) : (
      <Empty
        image={Empty.PRESENTED_IMAGE_SIMPLE}
        description="未有查找到角色"
      />
    );
  return (
    <Modal
      title="角色用户列表"
      visible={visible}
      onOk={onSave}
      width="860px"
      onCancel={handleCancel}
      maskClosable={false}
      destroyOnClose
    >
      <div className={styles.pageContent}>
        {/* 角色选择树 */}
        <div className={styles.roleContent}>
          {/* 角色搜索 */}
          <div className={styles.header}>
            <Form form={form} layout="inline" onFinish={onFinish}>
              <Form.Item name="roleName">
                <Input
                  prefix={<UserOutlined className="site-form-item-icon" />}
                  placeholder="请输入机构或角色名称"
                  disabled={modalType === 'edit'}
                  allowClear
                />
              </Form.Item>
              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  disabled={modalType === 'edit'}
                >
                  搜索
                </Button>
              </Form.Item>
            </Form>
          </div>
          {/* 角色树 */}
          <Spin spinning={loading}>
            <div className={styles.treeContent}>
              <Tabs activeKey={roleType} onChange={tabCallback}>
                <TabPane
                  tab="角色列表"
                  key="2"
                  disabled={modalType === 'edit' && chooseUser.type === 1}
                >
                  {roleDom()}
                </TabPane>
                <TabPane
                  tab="机构列表"
                  key="1"
                  disabled={modalType === 'edit' && chooseUser.type === 2}
                >
                  {roleDom()}
                </TabPane>
              </Tabs>
            </div>
          </Spin>
          {/* 分页 */}
          <div className={styles.footer}>
            <Pagination
              size="small"
              total={total}
              showSizeChanger
              defaultCurrent={1}
              current={currentPage}
              onChange={paginationChange}
            />
          </div>
        </div>
        {/* 用户列表 */}
        <div className={styles.userContent}>
          <div className={styles.userCheckBox}>
            <Checkbox
              indeterminate={indeterminate}
              onChange={onCheckAllChange}
              checked={checkAll}
            >
              <span style={{ fontWeight: 700 }}>用户列表</span>
            </Checkbox>
            <Divider style={{ margin: '10px 0' }} />
            <div className={styles.checkContent}>
              {plainOptions.length > 0 ? (
                <CheckboxGroup
                  options={plainOptions}
                  value={checkedList}
                  onChange={onChange}
                />
              ) : (
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description="未有查找到用户"
                />
              )}
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
};
export default RoalChoose;
