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';

let checkList = [];
console.log(checkList, 'checkList');
const PushTest = props => {
  const [form] = Form.useForm();
  const { confirmModal, onCancel, visible, pushTestMsg } = props;
  const [allList, setAllist] = useState([]);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    if (visible) {
      getData();
    } else {
      checkList = [];
      setAllist([]);
    }
  }, [visible]);

  const checkCallBack = useCallback((val, index) => {
    if (val) {
      checkList[index].checkedList = val;
    }
  });

  const onFinish = () => {
    let newArr = checkList.reduce(
      (total, currentValue) => [...total, ...currentValue.checkedList],
      [],
    );
    if (pushTestMsg.ThemeName)
      TestPush({
        theme: pushTestMsg.ThemeName,
        msgType: pushTestMsg.MsgType,
        tousers: newArr,
        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);
        }
      });
    console.log(newArr, 'newArr');
  };
  const onSearch = () => {
    getData({ key: form.getFieldsValue().username });
  };
  const getData = value => {
    let obj = value ? value : {};
    setLoading(true);
    GetGroupUserTree(obj).then(res => {
      console.log(res);

      let list = res.data.map(item => {
        let options = item.users.map(val => ({
          label: val.userName,
          value: val.userId,
        }));
        return {
          groupName: item.groupName,
          groupId: item.groupId,
          indeterminate: false,
          checkAll: false,
          plainOptions: options,
          checkedList: [],
        };
      });
      checkList = list;
      setAllist(list);
      setTimeout(() => {
        setLoading(false);
      }, 0);
    });
  };
  return (
    <>
      <Modal
        title="选择推送人"
        visible={visible}
        onOk={onFinish}
        width="700px"
        onCancel={onCancel}
        maskClosable={false}
        destroyOnClose
        centered
      >
        <div className="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={() => {
                  getData();
                  form.setFieldsValue({ username: '' });
                }}
              >
                重置
              </Button>
            </Form.Item>
          </Form>
        </div>
        <Spin spinning={loading}>
          <div
            className="checkContainer"
            style={{ height: '500px', overflowY: 'scroll', margin: '20px 0' }}
          >
            {allList.map((item, index) => (
              <div
                className={styles.checkBoxContent}
                key={item.groupId}
                style={{
                  display: item.plainOptions.length > 0 ? 'block' : 'none',
                }}
              >
                <CardCheck
                  cardMsg={item}
                  cardIndex={index}
                  callback={(val, i) => checkCallBack(val, i)}
                />
              </div>
            ))}
          </div>
        </Spin>
      </Modal>
    </>
  );
};

export default PushTest;
