/* eslint-disable no-else-return */
/* eslint-disable indent */
import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  Modal,
  Input,
  Button,
  message,
  Spin,
  Pagination,
  Tag,
  Empty,
  Checkbox,
  notification,
} from 'antd';
import { DesktopOutlined, MobileOutlined, WindowsOutlined } from '@ant-design/icons';
import { GetRoleUser, GetRoleUserNew } from '@/services/workflow/workflow';
import { GetGroupUserTree, TestPush } from '@/services/messagemanage/messagemanage';
import classnames from 'classnames';
import lodash from 'lodash';
import styles from './index.less';

import CardCheck from './CardCheck';

const PeopleSelector = props => {
  const { confirmModal, onCancel, visible, onSubumit, userIds, roleIds } = props;
  const [allList, setAllist] = useState([]); // 用于展示得数据
  const [checkListRoles, setCheckListRoles] = useState([]); // 选中得数据集合
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState();
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchName, setSearchName] = useState();
  const [flag, setFlag] = useState(0);
  const checkList = useRef([]);
  const [type, setType] = useState('人员');
  const [roleArr, setRoleArr] = useState([]); // 新角色机构选择列表
  const [delArr, setDelArr] = useState(new Map()); // 删除了的元素
  const [selected, setSelected] = useState(new Map()); // 已勾选角色列表

  useEffect(() => {
    if (visible) {
      setType('人员');
      setCurrentPage(1);
      checkList.current = userIds;
      getData(searchName, 1, pageSize);
      if (roleIds.length > 0) {
        roleIds.forEach(item => {
          selected.set(item.value, {
            roleName: item.label,
            roleId: item.value,
            type: 2,
            defauletUserName: '',
            defaultUserId: [],
          });
        });
        setSelected(selected);
        let arr = [];
        selected.forEach((val, key) => {
          arr.push({ label: val.roleName, value: val.roleId });
        });
        setCheckListRoles(arr);
      }
    } else {
      checkList.current = [];
      setCheckListRoles([]);
      setAllist([]);
      setSearchName('');
      setSelected(new Map());
      setDelArr(new Map());
    }
  }, [visible]);

  const showTypeIcon = item => {
    if (item.type === 'mobile') {
      return <MobileOutlined />;
    }
    if (item.visibleValue == 'CS') {
      return <WindowsOutlined />;
    }
    if (item.visibleTitle.indexOf('手持') !== -1) {
      return <MobileOutlined />;
    }
    return <DesktopOutlined />;
  };

  // 选中后得回调函数
  const checkCallBack = useCallback(newCheckList => {
    if (newCheckList) {
      checkList.current = newCheckList;
      setFlag(flag + 1);
      // setCheckList(newCheckList);
    }
  });
  // 监听分页
  const paginationChange = (page, pageSizes) => {
    setCurrentPage(page);
    setPageSize(pageSizes);
    getData(searchName, page, pageSizes);
  };
  // 提交勾选的测试人员
  const onFinish = () => {
    let role = [];
    selected.forEach((val, key) => {
      role.push({ label: val.roleName, value: val.roleId });
    });
    let person = checkList.current;
    onSubumit({ person, role });
  };
  // 搜索
  const onSearch = () => {
    setCurrentPage(1);
    if (type === '人员') {
      getData(searchName, 1, pageSize);
    } else {
      getRoleData(searchName);
    }
  };

  // 搜索框监听
  const searchChange = e => {
    setSearchName(e.target.value);
  };
  // 获取人员数据
  const getData = (username, page, pageSizes) => {
    setLoading(true);
    GetGroupUserTree({
      key: username,
      pageSize: pageSizes,
      PageIndex: page,
    })
      .then(res => {
        setLoading(false);
        if (res.code === 0) {
          setTotal(res.data.count);
          // 数据处理成checkbox组件需要得形式
          let list = res.data.data.map(item => {
            let indeterminate = false;
            let checkedList = [];
            let checkAll = false;
            let options = item.users.map(val => {
              checkList.current.forEach(ele => {
                if (val.userId === ele.value) {
                  checkedList.push(ele.value);
                }
              });
              return {
                label: val.userName,
                value: val.userId,
              };
            });
            if (checkedList.length === options.length && checkedList.length > 0) {
              checkAll = true;
            }
            if (checkedList.length < options.length && checkedList.length > 0) {
              indeterminate = true;
            }
            return {
              groupName: item.groupName,
              groupId: item.groupId,
              indeterminate,
              checkAll,
              checkedList,
              plainOptions: options,
            };
          });
          setAllist(list);
        } else {
          message.error(res.msg);
        }
      })
      .catch(() => {
        setLoading(false);
        message.error('网络异常，请稍后再试');
      });
  };

  // 获取角色选择数据
  const getRoleData = roleName => {
    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.forEach(v => {
              v.roleList.forEach(vv => {
                vv.roleID = Number(vv.roleID);
                if (selected.has(vv.roleID)) {
                  vv.isChecked = true;
                } else {
                  vv.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);
      } else {
        setRoleArr([]);
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  // 删除已选中列表
  const delSelected = (value, name) => {
    if (name === '人员') {
      let list = lodash.cloneDeep(checkList.current);
      let newList = list.filter(i => i.value != value.value);
      checkList.current = newList;
      let newData = allList.map(item => {
        let indeterminate = false;
        let checkedList = [];
        let checkAll = false;
        let options = item.plainOptions.map(val => {
          newList.forEach(ele => {
            if (val.value === ele.value) {
              checkedList.push(ele.value);
            }
          });
          return {
            label: val.label,
            value: val.value,
          };
        });
        if (checkedList.length === options.length && checkedList.length > 0) {
          checkAll = true;
        }
        if (checkedList.length < options.length && checkedList.length > 0) {
          indeterminate = true;
        }
        return {
          groupName: item.groupName,
          groupId: item.groupId,
          indeterminate,
          checkAll,
          checkedList,
          plainOptions: options,
        };
      });
      setAllist(newData);
    } else {
      let id = value.value;
      delArr.set(id, selected.get(id));
      selected.delete(id);
      setDelArr(delArr);
      setSelected(selected);
      let arr = [];
      selected.forEach((val, key) => {
        arr.push({ label: val.roleName, value: val.roleId });
      });
      setCheckListRoles(arr);
      let list = JSON.parse(JSON.stringify(roleArr));
      list.forEach(item => {
        if (item.child.length) {
          let newArr = [];
          item.child[0].roleList.forEach(v => {
            if (v.roleID === id) {
              v.isChecked = false;
            }
            if (v.isChecked) {
              newArr.push(v.isChecked);
            }
          });
          item.child[0].isChecked = getState(item.child[0].roleList, newArr);
          item.child[0].indeterminate = getIndeterminate(item.child[0].roleList, newArr);
        }
        item.roleList.forEach(v => {
          if (v.roleID === id) {
            v.isChecked = false;
          }
        });
      });
      setRoleArr(list);
    }
  };

  const getState = (list, check) => {
    if (list.length === check.length && check.length !== 0) {
      return true;
    } else if (list.length > check.length && check.length !== 0) {
      return false;
    } else {
      return false;
    }
  };

  const getIndeterminate = (list, check) => {
    if (list.length > check.length && check.length !== 0) {
      return true;
    }
    return false;
  };

  // 复选框监听事件
  const selectChange = (e, index, value, name, i, j) => {
    let list = JSON.parse(JSON.stringify(roleArr));
    if (name === 'child') {
      list[i].child[j].roleList[index].isChecked = e.target.checked;
    } else {
      list[i].roleList[index].isChecked = e.target.checked;
    }
    list.forEach(item => {
      if (item.child.length) {
        item.child.forEach(ele => {
          let arr = [];
          ele.roleList.forEach(v => {
            if (v.isChecked) {
              arr.push(v.isChecked);
            }
          });
          ele.isChecked = getState(ele.roleList, arr);
          ele.indeterminate = getIndeterminate(ele.roleList, arr);
        });
      }
      let arrList = [];
      item.roleList.forEach(v => {
        if (v.isChecked) {
          arrList.push(v.isChecked);
        }
      });
      item.checkAll = getState(item.roleList, arrList);
      item.indeterminate = getIndeterminate(item.roleList, arrList);
    });
    // 存储勾选角色
    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);
    }
    let arr = [];
    selected.forEach((val, key) => {
      arr.push({ label: val.roleName, value: val.roleId });
    });
    setCheckListRoles(arr);
    setDelArr(delArr);
    setSelected(selected);
    setRoleArr(list);
  };

  // 全选复选框监听事件
  const selectChangeAll = (e, index, value, num, i) => {
    let list = JSON.parse(JSON.stringify(roleArr));
    list[i].child[index].checkAll = e.target.checked;
    list[i].child[index].indeterminate = false;
    list[i].child[index].roleList.map(item => {
      item.isChecked = e.target.checked;
    });
    value.roleList.map(val => {
      if (e.target.checked) {
        // 存储已选角色或站点的默认承办人
        if (delArr.has(val.roleID)) {
          selected.set(val.roleID, delArr.get(val.roleID));
          delArr.delete(val.roleID);
        } else {
          selected.set(val.roleID, {
            roleName: val.roleName,
            type: 2,
            roleId: val.roleID,
            defauletUserName: '',
            defaultUserId: [],
          });
        }
      } else {
        delArr.set(val.roleID, selected.get(val.roleID));
        selected.delete(val.roleID);
      }
    });
    let arr = [];
    selected.forEach((val, key) => {
      arr.push({ label: val.roleName, value: val.roleId });
    });
    setCheckListRoles(arr);
    setDelArr(delArr);
    setSelected(selected);
    setRoleArr(list);
  };

  // 角色列表样式
  const roleDom = () => (
    <>
      <div className={styles.checkContainer1}>
        {roleArr.length ? (
          <div className={styles.checkContents}>
            {roleArr.map((v, i) => {
              return (
                <div className={styles.list} key={v.visibleTitle}>
                  <div className={styles.parent}>
                    {/* <Checkbox
                        checked={v.checkAll}
                        indeterminate={v.indeterminate}
                        onChange={e => {
                          selectChangeAll(e, i, v, '1');
                        }}
                      >
                        <>
                          <span style={{ color: '#1890ff', marginRight: '10px' }}>
                            {showTypeIcon(v)}
                          </span>
                          <span>{v.visibleTitle}</span>
                        </>
                      </Checkbox> */}
                    <span>
                      <span style={{ color: '#1890ff', marginRight: '10px' }}>
                        {showTypeIcon(v)}
                      </span>
                      <span>{v.visibleTitle}</span>
                    </span>
                  </div>
                  <div className={styles.childs}>
                    {v.child.length
                      ? v.child.map((item, index) => (
                        <div className={styles.checkGroupContent}>
                          <div className={styles.topCheckbox}>
                            <Checkbox
                              checked={item.isChecked}
                              indeterminate={item.indeterminate}
                              onChange={e => {
                                selectChangeAll(e, index, item, '2', i);
                              }}
                            >
                              {item.visibleTitle}
                            </Checkbox>
                          </div>
                          <div className={styles.bottomCheckbox}>
                            {item.roleList.length
                              ? item.roleList.map((items, indexC) => (
                                <div
                                  key={items.roleID}
                                  className={styles.check}
                                  title={items.name}
                                >
                                  <Checkbox
                                    checked={items.isChecked}
                                    onChange={e => {
                                      selectChange(e, indexC, items, 'child', i, index);
                                    }}
                                  >
                                    {items.roleName}
                                  </Checkbox>
                                </div>
                              ))
                              : null}
                          </div>
                        </div>
                      ))
                      : null}
                    <div className={styles.checkContent1}>
                      {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, '', i);
                              }}
                            >
                              {item.roleName}
                            </Checkbox>
                          </div>
                        ))
                        : null}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="未有查找到角色" />
        )}
      </div>
    </>
  );

  return (
    <>
      <Modal
        title="选择抄送人"
        visible={visible}
        onOk={onFinish}
        width="900px"
        className={styles.pushTestContent}
        onCancel={onCancel}
        maskClosable={false}
        destroyOnClose
        centered
      >
        <div>
          <div className={styles.searchHeader}>
            <div
              className={classnames({
                [styles.people]: true,
                [styles.peoplePick]: type === '人员',
              })}
              onClick={() => {
                setType('人员');
                setSearchName('');
                getData('', 1, pageSize);
              }}
            >
              人员
            </div>
            <div
              className={classnames({
                [styles.people]: true,
                [styles.peoplePick]: type === '角色',
              })}
              onClick={() => {
                setType('角色');
                setSearchName('');
                getRoleData();
              }}
            >
              角色
            </div>
            <Input.Search
              value={searchName}
              placeholder={type === '人员' ? '请输入部门或用户' : '请输入角色'}
              onChange={searchChange}
              onSearch={onSearch}
              className={styles.searchInput}
              style={{
                marginLeft: '165px',
                marginBottom: '4px',
              }}
            />
            <div className={styles.list}>已选列表</div>
            <div className={styles.checkList}>
              <div className={styles.person} /> 人员
              <div className={styles.role} />
              角色
            </div>
          </div>
          <div className={styles.content}>
            <div className={styles.leftContent}>
              <div className={styles.checkContainer}>
                <Spin spinning={loading}>
                  {type === '人员' ? (
                    <>
                      {' '}
                      {allList.map((item, index) => (
                        <div className={styles.checkBoxContent} key={item.groupId}>
                          <CardCheck
                            cardMsg={item}
                            cardIndex={index}
                            callback={(val, newCheckList) => checkCallBack(val, newCheckList)}
                            checkList={checkList.current}
                          />
                        </div>
                      ))}
                    </>
                  ) : (
                    <>{roleDom()}</>
                  )}
                </Spin>
              </div>
            </div>
            <div className={styles.tableRight}>
              {[...checkList.current].length > 0 || checkListRoles.length > 0 ? (
                <div className={styles.selectContent}>
                  {[...checkList.current].map(item => (
                    <div className={styles.selectValue} key={item.value}>
                      <Tag closable color="cyan" onClose={() => delSelected(item, '人员')}>
                        {item.label}
                      </Tag>
                    </div>
                  ))}
                  {checkListRoles.map(val => {
                    return (
                      <div className={styles.selectValue} key={val.value}>
                        <Tag closable color="purple" onClose={() => delSelected(val)}>
                          {val.label}
                        </Tag>
                      </div>
                    );
                  })}
                </div>
              ) : (
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description={type === '人员' ? '请选择人员' : '请选择角色'}
                />
              )}
            </div>
          </div>
        </div>
        <div
          style={{
            display: type === '人员' ? 'block' : 'none',
            position: 'absolute',
            bottom: 15,
            left: 15,
          }}
        >
          {/* 分页 */}
          <Pagination
            total={total}
            showTotal={(totals, range) => `共 ${totals} 条`}
            defaultPageSize={pageSize}
            defaultCurrent={1}
            current={currentPage}
            onChange={paginationChange}
            style={{ width: '100%' }}
            size="small"
            // showQuickJumper
            showSizeChanger
          />
        </div>
      </Modal>
    </>
  );
};

export default PeopleSelector;
