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 [checkAll, setCheckAll] = useState({});
  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);
          getAllData(res.data.projectPermission);
        } else {
          setOption([]);
          setGroupList([]);
          getAllData({});
        }
      })
      .catch(err => {
        setLoading(false);
      });
  };

  const getAllData = val => {
    let obj = { 预览: [], 编辑: [], 发布: [], 删除: [], 导出: [] };
    val.map(i => {
      if (i.permission.indexOf('预览') !== -1) {
        obj.预览 = [...obj.预览, i.projectName];
      }
      if (i.permission.indexOf('编辑') !== -1) {
        obj.编辑 = [...obj.编辑, i.projectName];
      }
      if (i.permission.indexOf('发布') !== -1) {
        obj.发布 = [...obj.发布, i.projectName];
      }
      if (i.permission.indexOf('删除') !== -1) {
        obj.删除 = [...obj.删除, i.projectName];
      }
      if (i.permission.indexOf('导出') !== -1) {
        obj.导出 = [...obj.导出, i.projectName];
      }
    });
    if (
      obj.预览.length === val.length &&
      obj.编辑.length === val.length &&
      obj.发布.length === val.length &&
      obj.删除.length === val.length &&
      obj.导出.length === val.length
    ) {
      obj.全选 = true;
    }
    setCheckAll(obj);
  };

  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);
    getAllData(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);
    getAllData(newData);
  };

  const onCheckAll = (e, val) => {
    let newData = JSON.parse(JSON.stringify(groupList));
    newData.map(i => {
      if (e.target.checked) {
        if (val === '预览') {
          if (i.permission.indexOf('预览') === -1) {
            i.permission.push('预览');
          }
        } else if (val === '编辑') {
          if (i.permission.indexOf('编辑') === -1) {
            i.permission.push('编辑');
          }
        } else if (val === '发布') {
          if (i.permission.indexOf('发布') === -1) {
            i.permission.push('发布');
          }
        } else if (val === '删除') {
          if (i.permission.indexOf('删除') === -1) {
            i.permission.push('删除');
          }
        } else if (val === '导出') {
          if (i.permission.indexOf('导出') === -1) {
            i.permission.push('导出');
          }
        }
      } else {
        if (val === '预览') {
          i.permission = i.permission.filter(item => item !== '预览');
        } else if (val === '编辑') {
          i.permission = i.permission.filter(item => item !== '编辑');
        } else if (val === '发布') {
          i.permission = i.permission.filter(item => item !== '发布');
        } else if (val === '删除') {
          i.permission = i.permission.filter(item => item !== '删除');
        } else if (val === '导出') {
          i.permission = i.permission.filter(item => item !== '导出');
        }
      }
    });
    setGroupList(newData);
    getAllData(newData);
  };

  const onAll = e => {
    let newData = JSON.parse(JSON.stringify(groupList));
    newData.map(i => {
      i.permission = e.target.checked ? option : [];
    });
    setGroupList(newData);
    getAllData(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);
    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.header}>
        <div>
          <Checkbox
            style={{ marginRight: '20px' }}
            checked={checkAll?.全选}
            onChange={e => onAll(e)}
          >
            全选
          </Checkbox>
          <Checkbox
            checked={checkAll?.预览?.length === groupList?.length}
            onChange={e => onCheckAll(e, '预览')}
          >
            预览全选
          </Checkbox>
          <Checkbox
            checked={checkAll?.编辑?.length === groupList?.length}
            onChange={e => onCheckAll(e, '编辑')}
          >
            编辑全选
          </Checkbox>
          <Checkbox
            checked={checkAll?.发布?.length === groupList?.length}
            onChange={e => onCheckAll(e, '发布')}
          >
            发布全选
          </Checkbox>
          <Checkbox
            checked={checkAll?.删除?.length === groupList?.length}
            onChange={e => onCheckAll(e, '删除')}
          >
            删除全选
          </Checkbox>
          <Checkbox
            checked={checkAll?.导出?.length === groupList?.length}
            onChange={e => onCheckAll(e, '导出')}
          >
            导出全选
          </Checkbox>
        </div>
        <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;