import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Modal, Input, Button, message, Spin, Pagination, Table } from 'antd';
import { GetGroupUserTree, TestPush } from '@/services/messagemanage/messagemanage';
import styles from './index.less';

import CardCheck from './CardCheck';

const PeopleSelector = props => {
  const { confirmModal, onCancel, visible, onSubumit, personList } = props;
  const [allList, setAllist] = useState([]); // 用于展示得数据
  // const [checkList, setCheckList] = 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([]);

  useEffect(() => {
    if (visible) {
      setCurrentPage(1);
      // setCheckList(personList);
      checkList.current = personList;
      getData(searchName, 1, pageSize);
    } else {
      // setCheckList([]);
      checkList.current = [];
      setAllist([]);
      setSearchName('');
    }
  }, [visible]);
  // 选中后得回调函数
  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 = () => {
    console.log(checkList.current, 'checkList');
    onSubumit(checkList.current);
  };
  // 搜索
  const onSearch = () => {
    setCurrentPage(1);
    getData(searchName, 1, pageSize);
  };
  // 重置
  const onReset = () => {
    setCurrentPage(1);
    getData('', 1, pageSize);
    setSearchName('');
  };
  // 搜索框监听
  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) {
          console.log(checkList.current, 'checkList.current');
          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 => {
                console.log(ele, 'elel');
                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,
            };
          });
          console.log(list, 'list');
          setAllist(list);
        } else {
          message.error(res.msg);
        }
      })
      .catch(() => {
        setLoading(false);
        message.error('网络异常,请稍后再试');
      });
  };

  const columns = [
    {
      title: '已选人员',
      dataIndex: 'label',
      key: 'label',
      width: 300,
    },
  ];
  return (
    <>
      <Modal
        title="选择抄送人"
        visible={visible}
        onOk={onFinish}
        width="900px"
        onCancel={onCancel}
        maskClosable={false}
        destroyOnClose
        centered
      >
        <div className={styles.pushTestContent}>
          <div className={styles.leftContent}>
            {/* 头部搜索框 */}
            <div className={styles.searchHeader}>
              <Input.Search
                value={searchName}
                placeholder="请输入部门或用户"
                onChange={searchChange}
                onSearch={onSearch}
                enterButton
                style={{ width: '300px', marginRight: '15px' }}
              />
              <Button type="primary" htmlType="submit" onClick={onReset}>
                重置
              </Button>
            </div>
            {/* 复选框模块 */}

            <div className={styles.checkContainer}>
              <Spin spinning={loading}>
                {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>
                ))}
              </Spin>
            </div>
          </div>
          <div className={styles.tableRight}>
            <Table
              bordered
              style={{ width: '350px', overflowX: 'hidden' }}
              rowKey={record => record.value}
              columns={columns}
              dataSource={checkList.current}
              pagination={false}
              size="small"
              scroll={{ y: 530 }}
              ItemTypes="pushTest"
            />
          </div>
        </div>
        <div>
          {/* 分页 */}
          <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;