import React, { useState, useEffect } from 'react';
import { Modal, Form, Select, Input, Checkbox } from 'antd';
import lodash from 'lodash';
import styles from './HomeConfigModal.less';
import { GetRoleGroups } from '@/services/webConfig/api';
const { Option } = Select;
const HomeConfigModal = props => {
  const { handleCancel, productList, visible, onFinish, currentPageConfig, client } = props;
  const [form] = Form.useForm();

  const [checkList, setCheckList] = useState([]);
  useEffect(() => {
    if (visible) {
      form.setFieldsValue(currentPageConfig);
      getCheckList();
    } else {
      setCheckList([]);
      form.resetFields();
    }
  }, [visible]);

  // 保存配置
  const onSubmit = () => {
    let roleName = [];
    let roleId = [];
    const getArr = arr => {
      arr.forEach(item => {
        if (item.roleGroups) {
          getArr(item.roleGroups);
        } else if (item.isCheck) {
          roleName.push(item.roleName);
          roleId.push(item.roleId);
        }
      });
    };

    getArr(checkList);
    console.log(checkList, { ...form.getFieldsValue(), roleName, roleId });
    onFinish({
      ...form.getFieldsValue(),
      roleName: roleName.join(','),
      roleId,
      keyIndex: currentPageConfig.keyIndex,
    });
    handleCancel();
  };
  const getCheckList = () => {
    console.log(client, 'client');
    if (!client) {
      return;
    }
    GetRoleGroups({ client }).then(res => {
      if (res.code === 0) {
        let childList = [];
        let defaultList = [];
        const chekMap = new Set(currentPageConfig.roleId);
        res.data.forEach(item => {
          if (item.groupName !== '默认') {
            childList.push(item);
            let checks = [];
            item.roleGroups.forEach(ele => {
              if (chekMap.has(ele.roleId)) {
                checks.push(ele);
              }
            });
            if (checks.length === item.roleGroups.length) {
              item.indeterminate = false;
              item.isCheck = true;
            } else if (checks.length === 0) {
              item.indeterminate = false;
              item.isCheck = false;
            } else {
              item.indeterminate = true;
              item.isCheck = false;
            }
          } else {
            defaultList = item.roleGroups;
          }
        });

        console.log(chekMap, currentPageConfig, 'chekMap');

        let list = [
          {
            groupName: '关联角色',
            isCheck: false,
            index: [0],
            roleGroups: [...defaultList, ...childList].map((item, index) => {
              let obj = {
                groupName: item.groupName,
                isCheck: item.isCheck,
                indeterminate: item.indeterminate,
                index: [0, index],
                roleGroups: item.roleGroups?.map((ele, i) => ({
                  ...ele,
                  isCheck: chekMap.has(ele.roleId),
                  index: [0, index, i],
                })),
              };
              let ojbChild = { ...item, isCheck: chekMap.has(item.roleId), index: [0, index] };

              return item.roleGroups ? obj : ojbChild;
            }),
          },
        ];
        console.log(list, 'list');
        setCheckList(list);
      }
    });
  };
  // 多选
  const changeAll = (e, item) => {
    let list = lodash.cloneDeep(checkList);
    let current = item.index.reduce(
      (acc, cur) =>
        acc[cur].roleGroups && cur !== item.index[item.index.length - 1]
          ? acc[cur].roleGroups
          : acc[cur],
      list,
    );
    console.log(current);
    current.isCheck = e.target.checked;
    checkAll(e.target.checked, current.roleGroups);
    current.indeterminate = false;
    setCheckList(list);
  };
  const checkAll = (checked, list) => {
    list.forEach(item => {
      if (item.roleGroups) {
        checkAll(checked, item.roleGroups);
      }
      item.isCheck = checked;
    });
  };
  const onChange = (e, item) => {
    let list = lodash.cloneDeep(checkList);

    let current = item.index.reduce(
      (acc, cur) => (acc[cur].roleGroups ? acc[cur].roleGroups : acc[cur]),
      list,
    );
    current.isCheck = e.target.checked;
    let parentIndex = [...item.index];
    parentIndex.pop();

    let allCurrent = parentIndex.reduce(
      (acc, cur) =>
        acc[cur].roleGroups && cur !== parentIndex[parentIndex.length - 1]
          ? acc[cur].roleGroups
          : acc[cur],
      list,
    );
    let num = allCurrent?.roleGroups?.filter(ele => ele.isCheck).length;

    if (num === allCurrent.roleGroups.length) {
      allCurrent.indeterminate = false;
      allCurrent.isCheck = true;
    } else if (num === 0) {
      allCurrent.indeterminate = false;
      allCurrent.isCheck = false;
    } else {
      allCurrent.indeterminate = true;
    }

    setCheckList(list);
  };
  const checkRender = list => (
    <>
      <div className={styles.checkList}>
        {list.map(item => {
          let num = item.roleGroups?.filter(ele => ele.isCheck || ele.indeterminate).length;

          return (
            <div className={styles.checkBox} key={item.groupName}>
              {item.groupName && (
                <div className={styles.title}>
                  <Checkbox
                    onChange={e => changeAll(e, item)}
                    checked={num === item.roleGroups.length}
                    indeterminate={num > 0 && num < item.roleGroups.length}
                  >
                    {item.groupName}
                  </Checkbox>
                </div>
              )}
              {item.roleGroups &&
                item.roleGroups.map(ele => (
                  <>
                    {ele.roleGroups ? (
                      checkRender(item.roleGroups)
                    ) : (
                      <Checkbox
                        onChange={e => onChange(e, ele)}
                        style={{ width: '150px', marginLeft: '0px', marginBottom: '10px' }}
                        checked={ele.isCheck}
                      >
                        {ele.roleName}
                      </Checkbox>
                    )}
                  </>
                ))}
            </div>
          );
        })}
      </div>
    </>
  );
  return (
    <Modal
      width={800}
      title="主页配置"
      visible={visible}
      onCancel={handleCancel}
      maskClosable={false}
      onOk={onSubmit}
      destroyOnClose
    >
      <div className={styles.monitorContent}>
        <Form
          form={form}
          labelCol={{ span: 3 }}
          wrapperCol={{ span: 21 }}
          initialValues={{ remember: true }}
        >
          <Form.Item label="产品类型" name="productType">
            <Select placeholder="请选择主页产品类型">
              {productList.map(item => (
                <Option value={item.PackageName} key={item.PackageName}>
                  {`${item.ProductName}（${item.PackageName}）`}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="主页Url" name="homePage">
            <Input placeholder="请输入主页路径" autoComplete="off" />
          </Form.Item>
        </Form>
        <div className={styles.roleCheck}>{checkRender(checkList)}</div>
      </div>
    </Modal>
  );
};

export default HomeConfigModal;
