package com.zd.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.zd.common.core.constant.UserConstants;
import com.zd.common.core.exception.PreAuthorizeException;
import com.zd.common.core.exception.ServiceException;
import com.zd.system.api.domain.SysPermitInfo;
import com.zd.system.api.domain.SysUser;
import com.zd.system.domain.SysPermitMenuDept;
import com.zd.system.mapper.SysPermitMenuDeptMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zd.system.mapper.SysPermitMenuMapper;
import com.zd.system.domain.SysPermitMenu;
import com.zd.system.service.ISysPermitMenuService;

/**
 * 权限和菜单关联Service业务层处理
 *
 * @author liubo
 * @date 2022-03-21
 */
@Service
public class SysPermitMenuServiceImpl implements ISysPermitMenuService {
    @Autowired
    private SysPermitMenuMapper sysPermitMenuMapper;
    @Autowired
    private SysPermitMenuDeptMapper sysPermitMenuDeptMapper;

    /**
     * 查询权限和菜单关联
     *
     * @param menuId 权限和菜单关联主键
     * @return 权限和菜单关联
     */
    @Override
    public SysPermitMenu selectSysPermitMenuByMenuId(Long menuId) {
        return sysPermitMenuMapper.selectSysPermitMenuByMenuId(menuId);
    }

    /**
     * 查询权限和菜单关联列表
     *
     * @param sysPermitMenu 权限和菜单关联
     * @return 权限和菜单关联
     */
    @Override
    public List<SysPermitMenu> selectSysPermitMenuList(SysPermitMenu sysPermitMenu) {
        return sysPermitMenuMapper.selectSysPermitMenuList(sysPermitMenu);
    }

    /**
     * 新增权限和菜单关联
     *
     * @param sysPermitMenu 权限和菜单关联
     * @return 结果
     */
    @Override
    public int insertSysPermitMenu(SysPermitMenu sysPermitMenu) {
        return sysPermitMenuMapper.insertSysPermitMenu(sysPermitMenu);
    }

    /**
     * 修改权限和菜单关联
     *
     * @param sysPermitMenu 权限和菜单关联
     * @return 结果
     */
    @Override
    public int updateSysPermitMenu(SysPermitMenu sysPermitMenu) {
        return sysPermitMenuMapper.updateSysPermitMenu(sysPermitMenu);
    }

    /**
     * 批量删除权限和菜单关联
     *
     * @param menuIds 需要删除的权限和菜单关联主键
     * @return 结果
     */
    @Override
    public int deleteSysPermitMenuByMenuIds(Long[] menuIds) {
        return sysPermitMenuMapper.deleteSysPermitMenuByMenuIds(menuIds);
    }

    /**
     * 删除权限和菜单关联信息
     *
     * @param menuId 权限和菜单关联主键
     * @return 结果
     */
    @Override
    public int deleteSysPermitMenuByMenuId(Long menuId) {
        return sysPermitMenuMapper.deleteSysPermitMenuByMenuId(menuId, null, null);
    }

    @Override
    public List<SysPermitInfo> selectPerMitByUserId(SysUser sysUser) {
        List<SysPermitInfo> list;
        if(UserConstants.USER_TYPE_SUPPLIER.equals(sysUser.getUserType())){
            return null;
        }else if(UserConstants.USER_TYPE_STUDENT.equals(sysUser.getUserType())){
            list = sysPermitMenuMapper.selectPerMitByStudent();
        }else {
            list = sysPermitMenuMapper.selectPerMitByUserId(sysUser.getUserId());

            if(list.size() == 0 && UserConstants.USER_TYPE_TEACHER.equals(sysUser.getUserType())){
                list = sysPermitMenuMapper.selectPerMitByTeacher();
            }
        }

        if(CollectionUtils.isEmpty(list) && !sysUser.isAdmin()){
//            throw new PreAuthorizeException();
            throw new ServiceException("用户未配置菜单权限，请联系管理员！", 530);
        }

        for (SysPermitInfo sysPermitInfo : list) {
            if(sysPermitInfo.getDataScope() == 3 && sysUser.getDept().getDeptId() != null){
                sysPermitInfo.getDeptIds().add(sysUser.getDept().getDeptId());
            }
        }
        return list;
    }

    /**
     * 批量添加、修改权限
     * 此处不做事务- 需注意添加【事务传播】触发
     * @param permitId 权限模板ID 二选一
     * @param userId 用户ID 二选一
     * @param permitMenus 权限数据
     */
    @Override
    public void insertSysPermitMenuList(Long permitId, Long userId, List<SysPermitMenu> permitMenus) {
        List<Long> permitMenuIds;
        if(permitId != null){
            permitMenuIds = sysPermitMenuMapper.selectIdByRelation(permitId, null);
            sysPermitMenuMapper.deleteSysPermitMenuByMenuId(null, permitId, null);
            if(CollectionUtils.isNotEmpty(permitMenus)){
                permitMenus.forEach(p -> {
                    if(p.getMenuId() == null || p.getDataScope() == null){
                        throw new ServiceException("数据异常，菜单ID或者权限类型错误！");
                    }
                    if(p.getDataScope() == 3 && CollectionUtils.isEmpty(p.getDeptIds())){
                        throw new ServiceException("权限数据异常，未选择指定部门！");
                    }

                    p.setType(1);
                    p.setPermitId(permitId);

                    p.setUserId(0L);
                });
            }
        }else if(userId != null){
            permitMenuIds = sysPermitMenuMapper.selectIdByRelation(null, userId);
            sysPermitMenuMapper.deleteSysPermitMenuByMenuId(null, null, userId);
            if(CollectionUtils.isNotEmpty(permitMenus)){
                permitMenus.forEach(p -> {
                    if(p.getMenuId() == null || p.getDataScope() == null){
                        throw new ServiceException("数据异常，菜单ID或者权限类型错误！");
                    }

                    if(p.getDataScope() == 3 && CollectionUtils.isEmpty(p.getDeptIds())){
                        throw new ServiceException("权限数据异常，未选择指定部门！");
                    }

                    p.setType(2);
                    p.setUserId(userId);

                    p.setPermitId(0L);

                });
            }
        }else {
            throw new ServiceException("参数异常：数据来源不明确！");
        }

        if(permitMenuIds.size() > 0){
            sysPermitMenuDeptMapper.deleteSysPermitMenuDeptByPermitMenuIds(permitMenuIds.toArray(new Long[permitMenuIds.size()]));
        }
        if(CollectionUtils.isNotEmpty(permitMenus)){
            sysPermitMenuMapper.insertBatch(permitMenus);

            List<SysPermitMenuDept> permitMenuDeptList = new ArrayList<>();
            for (SysPermitMenu permitMenu : permitMenus) {
                if(permitMenu.getDataScope() == 3){
                    for (Long deptId : permitMenu.getDeptIds()) {
                        SysPermitMenuDept permitMenuDept = new SysPermitMenuDept();
                        permitMenuDept.setPermitMenuId(permitMenu.getId());
                        permitMenuDept.setDeptId(deptId);
                        permitMenuDeptList.add(permitMenuDept);
                    }
                }
            }
            if(permitMenuDeptList.size() > 0){
                sysPermitMenuDeptMapper.insertBatch(permitMenuDeptList);
            }
        }

    }
}
