import React, { useEffect, useState } from 'react';
import { GetRoleUser } from '@/services/workflow/workflow';
import { Modal, Input, Checkbox, Pagination, Spin, notification, Empty, Tabs, Tag } from 'antd';
import styles from './RoalChoose.less';
const { Search } = Input;
const { TabPane } = Tabs;
const RoalChoose = props => {
  const { onSubumit, handleCancel, visible, roleList } = props;
  const [plainOptions, setPlainOptions] = useState([]); // 角色机构选择列表
  const [total, setTotal] = useState(); // 角色人员条数
  const [loading, setLoading] = useState(false); // 加载时的loading
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(33);
  const [roleType, setRoleType] = useState('2'); // 角色类型
  const [selected, setSelected] = useState(new Map()); // 已勾选角色列表
  const [searchName, setSearchName] = useState(); // 搜索名称
  const [delArr, setDelArr] = useState(new Map()); // 删除了的元素
  // 初始化
  useEffect(() => {
    if (visible) {
      setCurrentPage(1);
      getData('', 1, pageSize, 0, 2);
      setRoleType('2');
      // 对已选的角色进行回显
      if (roleList.length > 0) {
        roleList.forEach(item => {
          selected.set(item.roleId, {
            roleName: item.roleName,
            defauletUserName: item.defauletUserName,
            defaultUserId: item.defaultUserId,
            roleId: item.roleId,
            type: item.type,
          });
        });
        setSelected(selected);
      }
    } else {
      setPlainOptions([]);
      setSelected(new Map());
      setDelArr(new Map());
    }
  }, [visible]);

  // 获取左侧树回显
  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) {
        // 处理勾选角色或部门回显
        res.data.data.forEach(item => {
          if (selected.has(item.id)) {
            item.isChecked = true;
          }
        });
        setPlainOptions(res.data.data);
        setTotal(res.data.count);
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };
  // 查询角色
  const onSearch = value => {
    setCurrentPage(1);
    setSearchName(value);
    getData(value, 1, pageSize, 0, roleType);
  };
  // 监听分页
  const paginationChange = (page, pageSizes) => {
    setCurrentPage(page);
    setPageSize(pageSizes);
    getData(searchName, page, pageSizes, 0, roleType);
  };
  // 复选框监听事件
  const selectChange = (e, index, value) => {
    console.log(plainOptions);
    let list = JSON.parse(JSON.stringify(plainOptions));
    list[index].isChecked = e.target.checked;
    console.log(list);
    // 存储勾选角色或站点信息
    if (e.target.checked) {
      // 存储已选角色或站点的默认承办人
      if (delArr.has(value.id)) {
        selected.set(value.id, delArr.get(value.id));
        delArr.delete(value.id);
      } else {
        selected.set(value.id, {
          roleName: value.name,
          type: value.type,
          roleId: value.id,
          defauletUserName: '',
          defaultUserId: [],
        });
      }
    } else {
      delArr.set(value.id, selected.get(value.id));
      selected.delete(value.id);
    }
    console.log(list);
    console.log(selected);
    console.log(list);
    setDelArr(delArr);
    setSelected(selected);
    setPlainOptions(list);
  };
  // tab栏切换回调
  const tabCallback = val => {
    if (val === roleType) {
      return;
    }
    setRoleType(val);
    setCurrentPage(1);
    getData(searchName, 1, pageSize, 0, val);
  };
  // 保存选择的角色列表
  const onSave = () => {
    let selectData = [];
    selected.forEach((val, key) => {
      selectData.push(val);
    });
    onSubumit(selectData);
  };
  // 删除已选中列表
  const delSelected = value => {
    delArr.set(value, selected.get(value));
    selected.delete(value);
    setDelArr(delArr);
    setSelected(selected);
    let arr = JSON.parse(JSON.stringify(plainOptions));
    arr.forEach(item => {
      if (item.id === value) {
        item.isChecked = false;
      }
    });
    setPlainOptions(arr);
  };
  // 角色列表样式
  const roleDom = () => (
    <>
      <div className={styles.checkContainer}>
        <Spin spinning={loading}>
          {plainOptions.length > 0 ? (
            <div className={styles.checkContent}>
              {plainOptions.map((item, index) => (
                <div key={item.id} className={styles.check} title={item.name}>
                  <Checkbox
                    checked={item.isChecked}
                    onChange={e => {
                      selectChange(e, index, item);
                    }}
                  >
                    {item.name}
                  </Checkbox>
                </div>
              ))}
            </div>
          ) : (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={`未有查找到${roleType === '2' ? '角色' : '机构'}`}
            />
          )}
        </Spin>
      </div>
    </>
  );
  return (
    <div className={styles.modalContainer}>
      <Modal
        title="办理配置"
        visible={visible}
        onOk={onSave}
        width="860px"
        onCancel={handleCancel}
        maskClosable={false}
        destroyOnClose
        getContainer={false}
        zIndex={20}
      >
        <div className={styles.pageContent}>
          {/* 可选列表 */}
          <div className={styles.optionalList}>
            <div className={styles.header}>
              <Search
                className={styles.searchInput}
                allowClear
                placeholder="请输入机构或角色"
                onSearch={onSearch}
                onChange={e => {
                  setSearchName(e.target.value);
                }}
              />
              <div className={styles.tabContent}>
                <Tabs type="card" activeKey={roleType} onChange={tabCallback}>
                  <TabPane tab="角色" key="2">
                    {roleDom()}
                  </TabPane>
                  <TabPane tab="机构" key="1">
                    {roleDom()}
                  </TabPane>
                </Tabs>
              </div>
              {/* 分页 */}
              <div className={styles.footer}>
                <Pagination
                  size="small"
                  total={total}
                  showSizeChanger
                  defaultCurrent={1}
                  current={currentPage}
                  onChange={paginationChange}
                  defaultPageSize={33}
                  pageSizeOptions={[33, 45, 60, 90]}
                />
              </div>
            </div>
          </div>
          {/* 已选列表 */}
          <div className={styles.selectedList}>
            <div className={styles.header}>
              <div className={styles.title}>已选列表</div>
              <div className={styles.tagHead}>
                <div className={styles.tagContent}>
                  <div className={styles.tagRol} />
                  <div>角色</div>
                </div>
                <div className={styles.tagContent}>
                  <div className={styles.tagOrg} />
                  <div>机构</div>
                </div>
              </div>
            </div>
            <div className={styles.selectBox}>
              {[...selected].length > 0 ? (
                <div className={styles.selectContent}>
                  {[...selected].map(item => (
                    <div className={styles.selectValue} key={item[0]}>
                      <Tag
                        closable
                        color={item[1].type === 2 ? 'cyan' : 'orange'}
                        onClose={() => delSelected(item[0])}
                      >
                        {item[1].roleName}
                      </Tag>
                    </div>
                  ))}
                </div>
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="请选择角色或机构" />
              )}
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
};
export default RoalChoose;
