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

const PushTest = props => {
  const [form] = Form.useForm();
  const { confirmModal, onCancel, visible, pushTestMsg } = 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);
  useEffect(() => {
    if (visible) {
      let username = form.getFieldValue('username');
      setCurrentPage(1);
      getData(username, 1, pageSize);
    } else {
      setCheckList([]);
      setAllist([]);
      form.setFieldsValue({ username: '' });
    }
  }, [visible]);
  // 选中后得回调函数
  const checkCallBack = useCallback((val, newCheckList) => {
    if (val) {
      setCheckList(newCheckList);
    }
  });
  // 监听分页
  const paginationChange = (page, pageSizes) => {
    setCurrentPage(page);
    setPageSize(pageSizes);
    let username = form.getFieldValue('username');
    getData(username, page, pageSizes);
  };
  const onFinish = () => {
    TestPush({
      theme: pushTestMsg.ThemeName,
      msgType: pushTestMsg.MsgType,
      tousers: checkList,
      pushPath: pushTestMsg.item.AgentConfig
        ? pushTestMsg.item.AgentConfig.Url
        : '',
      msgTypeId: pushTestMsg.ID.toString(),
    })
      .then(res => {
        if (res.code === 0) {
          confirmModal();
          message.success('测试推送成功');
        } else {
          message.error(res.msg);
        }
      })
      .catch(() => {
        message.error('网络异常，请稍后再试');
      });
  };
  // 搜索
  const onSearch = () => {
    let username = form.getFieldValue('username');
    setCurrentPage(1);
    getData(username, 1, pageSize);
  };
  // 重置
  const onReset = () => {
    setCurrentPage(1);
    getData('', 1, pageSize);
    form.setFieldsValue({ username: '' });
  };
  // 获取数据
  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.forEach(ele => {
                if (val.userId === ele) {
                  checkedList.push(ele);
                }
              });
              return {
                label: val.userName,
                value: val.userId,
              };
            });
            console.log(item.groupName, '名称');
            console.log(checkList, '所有选择得列表');
            console.log(checkedList, '当前组件勾选');

            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('网络异常，请稍后再试');
      });
  };
  return (
    <>
      <Modal
        title="选择推送人"
        visible={visible}
        onOk={onFinish}
        width="700px"
        onCancel={onCancel}
        maskClosable={false}
        destroyOnClose
        centered
      >
        {/* 头部搜索框 */}
        <div className={styles.searchHeader}>
          <Form form={form} layout="inline">
            <Form.Item name="username">
              <Input placeholder="请输入用户名称" />
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                onClick={onSearch}
                style={{ marginRight: '10px' }}
              >
                搜索
              </Button>
              <Button type="primary" htmlType="submit" onClick={onReset}>
                重置
              </Button>
            </Form.Item>
          </Form>
        </div>
        {/* 复选框模块 */}
        <Spin spinning={loading}>
          <div className={styles.checkContainer}>
            {allList.map((item, index) => (
              <div className={styles.checkBoxContent} key={item.groupId}>
                <CardCheck
                  cardMsg={item}
                  cardIndex={index}
                  callback={(val, newCheckList) =>
                    checkCallBack(val, newCheckList)
                  }
                  checkList={checkList}
                />
              </div>
            ))}
          </div>
        </Spin>
        {/* 分页 */}
        <Pagination
          total={total}
          showTotal={(totals, range) =>
            `第${range[0]}-${range[1]} 条/共 ${totals} 条`
          }
          defaultPageSize={pageSize}
          defaultCurrent={1}
          current={currentPage}
          onChange={paginationChange}
          style={{ marginBottom: '10px' }}
          size="small"
          showQuickJumper
        />
      </Modal>
    </>
  );
};

export default PushTest;
