import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import {
  Modal,
  Input,
  Button,
  message,
  Spin,
  Pagination,
  Table,
  Tooltip,
  Space,
  Checkbox,
  notification,
} from 'antd';
import { getRolePermission, updateRolePermission } from '@/services/RoleManage/api';
import styles from './SelectUser.less';

const CheckboxGroup = Checkbox.Group;

const OpePermissions = props => {
  const { confirmModal, onCancel, visible, itemObj, roleID } = props;
  const [checkedList, setCheckedList] = useState();
  const [indeterminate, setIndeterminate] = useState(true);
  const [checkAll, setCheckAll] = useState(false);
  const [loading, setLoading] = useState(false);
  const [option, setOption] = useState([]);
  const [groupList, setGroupList] = useState([]);
  const [keepGroupList, setKeepGroupList] = useState([]);

  useEffect(() => {
    getInitialData();
  }, [itemObj]);

  // 获取初始数据
  const getInitialData = () => {
    setLoading(true);
    getRolePermission({ roleId: roleID })
      .then(res => {
        setLoading(false);
        if (res.code === 0) {
          setOption(res.data.dicPermissions);
          setGroupList(res.data.projectPermission);
          setKeepGroupList(res.data.projectPermission);
        } else {
          setOption([]);
          setGroupList([]);
        }
      })
      .catch(err => {
        setLoading(false);
      });
  };

  const onChange = (list, id) => {
    let newData = JSON.parse(JSON.stringify(groupList));
    let item = newData.find(i => i.projeectId === id);
    let index = newData.findIndex(i => i.projeectId === id);
    item.permission = list;
    newData[index] = item;
    setGroupList(newData);
  };
  const onCheckAllChange = (e, id) => {
    let newData = JSON.parse(JSON.stringify(groupList));
    let item = newData.find(i => i.projeectId === id);
    let index = newData.findIndex(i => i.projeectId === id);
    item.permission = e.target.checked ? option : [];
    newData[index] = item;
    setGroupList(newData);
  };
  // 提交勾选人员
  const onFinish = () => {
    let arrList = [];
    groupList.forEach(item => {
      let data = keepGroupList.find(i => i.projeectId === item.projeectId);
      if (item.permission.length !== data.permission.length) {
        arrList.push(item);
      }
    });
    console.log(arrList);
    debugger;
    let arr = [];
    if (arrList.length > 0) {
      arrList.forEach(item => {
        arr.push({
          projectId: item.projeectId,
          permission: item.permission.toString(),
        });
      });
      updateRolePermission({ roleId: roleID, permissons: arr }).then(res => {
        if (res.code === 0) {
          notification.success({
            message: '提示',
            duration: 3,
            description: '设置成功',
          });
          getInitialData();
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: res.msg,
          });
        }
      });
    } else {
      message.warning('请更改后再保存！');
    }
  };

  return (
    <>
      {/* 头部搜索框 */}
      <div className={styles.headerLeft}>
        <Button onClick={onFinish} type="primary" htmlType="submit">
          提交
        </Button>
      </div>
      <div className={styles.pushTestContent}>
        <div className={styles.leftContent}>
          {/* 复选框模块 */}
          <div className={styles.checkScrollBox}>
            <Spin spinning={loading}>
              <div className={styles.checkContainer}>
                {groupList?.map((item, index) => (
                  <div className={styles.checkBoxContent} key={item.projeectId}>
                    <div className={styles.checkContent}>
                      <div className={styles.topCheckbox}>
                        <Checkbox
                          indeterminate={
                            item.permission.length > 0 && item.permission.length < option?.length
                          }
                          onChange={e => onCheckAllChange(e, item.projeectId)}
                          checked={item.permission.length === option?.length}
                        >
                          {`${item.projeectId}-${item.projectName}`}
                        </Checkbox>
                      </div>
                      <div className={styles.bottomCheckbox}>
                        <CheckboxGroup
                          value={item.permission}
                          onChange={list => onChange(list, item.projeectId)}
                          style={{ display: 'flex', flexWrap: 'wrap' }}
                        >
                          {option.map(i => (
                            <Checkbox key={i} value={i}>
                              <span className={styles.fontlabel}>{i}</span>
                            </Checkbox>
                          ))}
                        </CheckboxGroup>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </Spin>
          </div>
        </div>
      </div>
    </>
  );
};

export default OpePermissions;
