import React, { useEffect, useState } from 'react';
import { GetRoleUser, GetRoleUserNew } from '@/services/workflow/workflow';
import { Modal, Input, Checkbox, Pagination, Spin, notification, Empty, Tabs, Tag } from 'antd';
import {
  CaretDownOutlined,
  DesktopOutlined,
  MobileOutlined,
  WindowsOutlined,
} from '@ant-design/icons';
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 [roleArr, setRoleArr] = 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()); // 删除了的元素
  const [shrink, setShrink] = useState([]);

  const showTypeIcon = item => {
    if (item.type === 'mobile') {
      return <MobileOutlined />;
    }
    if (item.visibleValue == 'CS') {
      return <WindowsOutlined />;
    }
    if (item.visibleTitle.indexOf('手持') !== -1) {
      return <MobileOutlined />;
    }
    return <DesktopOutlined />;
  };
  // 初始化
  useEffect(() => {
    if (visible) {
      setCurrentPage(1);
      // getData('', 1, pageSize, 0, 2);
      getRoleData();
      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 getRoleData = (roleName, pageIndex, pageSizes, roleId, Type) => {
    roleName = roleName || '';
    setLoading(true);
    GetRoleUserNew({
      roleName,
    }).then(res => {
      setLoading(false);
      if (res.code === 0 && res.data.length) {
        let list = JSON.parse(JSON.stringify(res.data));
        list.forEach(item => {
          if (item.child.length) {
            item.child[0].roleList.forEach(v => {
              v.roleID = Number(v.roleID);
              if (selected.has(v.roleID)) {
                v.isChecked = true;
              } else {
                v.isChecked = false;
              }
            });
          }
          item.roleList.forEach(v => {
            v.roleID = Number(v.roleID);
            if (selected.has(v.roleID)) {
              v.isChecked = true;
            } else {
              v.isChecked = false;
            }
          });
        });
        setRoleArr(list);
        // setRoleArr(res.data);

        // 处理勾选角色或部门回显
        // res.data.data.forEach(item => {
        //   if (selected.has(item.id)) {
        //     item.isChecked = true;
        //   }
        // });
        // setPlainOptions(res.data.data);
        // setTotal(res.data.count);
      } else {
        setRoleArr([]);
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };
  // 查询角色
  const onSearch = value => {
    setCurrentPage(1);
    setSearchName(value);
    // getData(value, 1, pageSize, 0, roleType);
    getRoleData(value);
  };
  // 监听分页
  const paginationChange = (page, pageSizes) => {
    setCurrentPage(page);
    setPageSize(pageSizes);
    getData(searchName, page, pageSizes, 0, roleType);
  };
  // 复选框监听事件
  const selectChange = (e, index, value) => {
    console.log(e, index, value, '666');
    let list = JSON.parse(JSON.stringify(roleArr));
    list.forEach(item => {
      if (item.child.length) {
        item.child[0].roleList.forEach(v => {
          if (v.roleID === value.roleID) {
            v.isChecked = e.target.checked;
          }
        });
      }
      item.roleList.forEach(v => {
        if (v.roleID === value.roleID) {
          v.isChecked = e.target.checked;
        }
      });
    });
    // list[index].isChecked = e.target.checked;
    console.log(list);
    // 存储勾选角色或站点信息
    if (e.target.checked) {
      // 存储已选角色或站点的默认承办人
      if (delArr.has(value.roleID)) {
        selected.set(value.roleID, delArr.get(value.roleID));
        delArr.delete(value.roleID);
      } else {
        selected.set(value.roleID, {
          roleName: value.roleName,
          type: 2,
          roleId: value.roleID,
          defauletUserName: '',
          defaultUserId: [],
        });
      }
    } else {
      delArr.set(value.roleID, selected.get(value.roleID));
      selected.delete(value.roleID);
    }
    console.log(list);
    console.log(selected);
    console.log(list);
    setDelArr(delArr);
    setSelected(selected);
    setRoleArr(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);
    let list = JSON.parse(JSON.stringify(roleArr));
    list.forEach(item => {
      if (item.child.length) {
        item.child[0].roleList.forEach(v => {
          if (v.roleID === value) {
            v.isChecked = false;
          }
        });
      }
      item.roleList.forEach(v => {
        if (v.roleID === value) {
          v.isChecked = false;
        }
      });
    });
    setRoleArr(list);
  };

  const shirnk = name => {
    if (shrink.includes(name)) {
      let type = shrink.filter(s => s !== name);
      setShrink(type);
    } else {
      setShrink([...shrink, name]);
    }
  };
  // 角色列表样式
  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> */}

      <div className={styles.checkContainer}>
        <Spin spinning={loading}>
          {roleArr.length ? (
            <div className={styles.checkContents}>
              {roleArr.map((v, i) => (
                <div className={styles.list} key={v.visibleTitle}>
                  <div className={styles.parent}>
                    <span
                      className={styles.imgDown}
                      onClick={() => shirnk(v.visibleTitle)}
                      style={{ transform: shrink.includes(v.visibleTitle) ? 'rotate(270deg)' : '' }}
                    >
                      <CaretDownOutlined />
                    </span>
                    <span style={{ color: '#1890ff', marginRight: '10px' }}>{showTypeIcon(v)}</span>
                    <span>{v.visibleTitle}</span>
                  </div>
                  <div
                    className={styles.childs}
                    style={{ display: shrink.includes(v.visibleTitle) ? 'none' : 'block' }}
                  >
                    {v.child.length
                      ? v.child.map(item => (
                        <div className={styles.checkGroupContent}>
                          <div className={styles.topCheckbox}>
                            <span>{item.visibleTitle}</span>
                          </div>
                          <div className={styles.bottomCheckbox}>
                            {item.roleList.length
                              ? item.roleList.map((items, index) => (
                                <div
                                  key={items.roleID}
                                  className={styles.check}
                                  title={items.name}
                                >
                                  <Checkbox
                                    checked={items.isChecked}
                                    onChange={e => {
                                      selectChange(e, index, items);
                                    }}
                                  >
                                    {items.roleName}
                                  </Checkbox>
                                </div>
                              ))
                              : null}
                          </div>
                        </div>
                      ))
                      : null}
                    <div className={styles.checkContent}>
                      {v.roleList.length
                        ? v.roleList.map((item, index) => (
                          <div key={item.roleID} className={styles.check} title={item.name}>
                            <Checkbox
                              checked={item.isChecked}
                              onChange={e => {
                                selectChange(e, index, item);
                              }}
                            >
                              {item.roleName}
                            </Checkbox>
                          </div>
                        ))
                        : null}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="未有查找到角色" />
          )}
        </Spin>
      </div>
    </>
  );
  return (
    <div className={styles.modalContainer}>
      <Modal
        title="节点承办管理配置"
        visible={visible}
        onOk={onSave}
        width="900px"
        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'}
                        color="cyan"
                        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;
