package com.huiju.estateagents.center.taUser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.mapper.TaUserAuthMenuMapper;
import com.huiju.estateagents.center.taUser.mapper.TaUserMapper;
import com.huiju.estateagents.center.taUser.service.ITaUserAuthMenuService;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.mapper.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author weicc
 * @Title: TaUserAuthMenuServiceImpl
 * @Description: TODO
 * @date 2019/9/21
 */
@Service
public class TaUserAuthMenuServiceImpl extends ServiceImpl<TaUserAuthMenuMapper, SysMenu> implements ITaUserAuthMenuService {


    @Autowired
    private TaUserAuthMenuMapper taUserAuthMenuMapper;
    @Autowired
    private TaRoleMenuMapper taRoleMenuMapper;
    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private  TaRoleMapper taRoleMapper;

    @Autowired
    private TaRoleButtonMapper taRoleButtonMapper;

    @Autowired
    private TaAdvancedControllerMapper taAdvancedControllerMapper;

    @Autowired
    private SysAdvancedConfigRelationMapper sysAdvancedConfigRelationMapper;

    /**
     * 根据用户id获取授权菜单
     * @param pageNum
     * @param pageSize
     * @param userId
     * @param orgId
     * @return
     */
    @Override
    public ResponseBean getMenuByUserId(Integer pageNum, Integer pageSize, String userId, Integer orgId) {
        List<SysMenu> records = new ArrayList<>();
        List<SysMenu> menuList = taUserAuthMenuMapper.sysMenuListByUserId(userId);
        records.addAll(menuList);
        //添加高级配置的过滤条件
        List<TaAdvancedController> taAdvancedControllerList = taAdvancedControllerMapper.selectList(new QueryWrapper<TaAdvancedController>().eq("org_id", orgId));

        //需要过滤的菜单
        QueryWrapper<SysAdvancedConfigRelation> sysAdvancedConfigRelationQueryWrapper = new QueryWrapper<>();
        sysAdvancedConfigRelationQueryWrapper.eq("target_type",CommConstant.ADVANCED_TYPE_MENU);
        sysAdvancedConfigRelationQueryWrapper.notIn(taAdvancedControllerList.size() > 0,"advanced_config_id",taAdvancedControllerList.stream().map(TaAdvancedController::getAdvancedConfigId).collect(Collectors.toList()));
        List<SysAdvancedConfigRelation> sysAdvancedConfigRelations = sysAdvancedConfigRelationMapper.selectList(sysAdvancedConfigRelationQueryWrapper);
        menuList.forEach(e -> {
            sysAdvancedConfigRelations.forEach(s -> {
                if (e.getMenuId() == Integer.valueOf(s.getTargetId())){
                    records.remove(e);
                }
            });
        });
        return ResponseBean.success(records);
    }

    @Override
    public ResponseBean getAllMenu(Integer pageNum, Integer pageSize, Integer orgId, List<TaRole> userRoles) {
        List<SysMenu> records = new ArrayList<>();
        List<SysMenu> menuList = taUserAuthMenuMapper.sysMenuListByRoleId();
        records.addAll(menuList);
        //添加高级配置的过滤条件
        List<TaAdvancedController> taAdvancedControllerList = taAdvancedControllerMapper.selectList(new QueryWrapper<TaAdvancedController>().eq("org_id", orgId));

        //需要过滤的菜单
        QueryWrapper<SysAdvancedConfigRelation> sysAdvancedConfigRelationQueryWrapper = new QueryWrapper<>();
        sysAdvancedConfigRelationQueryWrapper.eq("target_type",CommConstant.ADVANCED_TYPE_MENU);
        sysAdvancedConfigRelationQueryWrapper.notIn(taAdvancedControllerList.size() > 0,"advanced_config_id",taAdvancedControllerList.stream().map(TaAdvancedController::getAdvancedConfigId).collect(Collectors.toList()));
        List<SysAdvancedConfigRelation> sysAdvancedConfigRelations = sysAdvancedConfigRelationMapper.selectList(sysAdvancedConfigRelationQueryWrapper);

        List<TaRoleMenu> configRelationRoleMenuList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(userRoles) && CollectionUtils.isNotEmpty(sysAdvancedConfigRelations)){
            QueryWrapper<TaRoleMenu> taRoleMenuQueryWrapper = new QueryWrapper<>();
            taRoleMenuQueryWrapper.in("role_id", userRoles.stream().map(TaRole::getRoleId).collect(Collectors.toList()));
            taRoleMenuQueryWrapper.in("menu_id", sysAdvancedConfigRelations.stream().map(SysAdvancedConfigRelation::getTargetId).collect(Collectors.toList()));
            configRelationRoleMenuList = taRoleMenuMapper.selectList(taRoleMenuQueryWrapper);
        }

        QueryWrapper<TaRoleMenu> queryWrapper = new QueryWrapper();
        List<TaRoleMenu> taRoleMenus = taRoleMenuMapper.selectList(queryWrapper);

        for (SysMenu sysMenu : records){
            ArrayList<Integer> roles = new ArrayList<>();
            for (TaRoleMenu taRoleMenu : taRoleMenus){
                if (taRoleMenu.getMenuId().equals(sysMenu.getMenuId()) && !roles.contains(taRoleMenu.getRoleId())){
                    roles.add(taRoleMenu.getRoleId());
                }
            }
            for (TaRoleMenu taRoleMenu : configRelationRoleMenuList){
                if (sysMenu.getMenuId().equals(taRoleMenu.getMenuId())){
                    roles.remove(taRoleMenu.getRoleId());
                }
            }
            sysMenu.setRoles(roles);
        }

        return ResponseBean.success(records);
    }

    @Override
    public ResponseBean updateUserAuthMenu(Integer roleId, List<SysMenu> sysMenuList,String name,Integer orgId,List<SysButtonInMenu> sysButtonInMenuList) {
        ResponseBean responseBean = new ResponseBean();
        if (null == roleId){
            addUserAuthMenu( sysMenuList,name,orgId,sysButtonInMenuList);
            return responseBean;
        }
        try {
            //授权菜单，先删除在新增
            taRoleMenuMapper.deleteCurrentMenu(roleId);
            for (SysMenu sysMenu: sysMenuList) {
                TaRoleMenu taRoleMenu = new TaRoleMenu();
                taRoleMenu.setRoleId(roleId);
                taRoleMenu.setMenuId(sysMenu.getMenuId());
                taRoleMenuMapper.insert(taRoleMenu);
            }
            // 更新Role
            TaRole taRole = new TaRole();
            taRole.setRoleId(roleId);
            taRole.setRoleName(name);
            taRoleMapper.updateById(taRole);

            // 当前角色的所有按钮再重新插入

            taRoleButtonMapper.deleteCurrentBut(roleId);
            for (SysButtonInMenu sysButtonInMenu :sysButtonInMenuList) {
                TaRoleButton taRoleButton = new TaRoleButton();
                taRoleButton.setRoleId(taRole.getRoleId());
                taRoleButton.setBtnId(sysButtonInMenu.getBtnId());
                taRoleButtonMapper.insert(taRoleButton);
            }
                responseBean.addSuccess("操作成功");
            return responseBean;
        } catch (Exception e) {
            responseBean.addSuccess("操作失败");
            e.printStackTrace();
            return responseBean;
        }
    }

    public Boolean addUserAuthMenu(List<SysMenu> sysMenuList,String name,Integer orgId,List<SysButtonInMenu> sysButtonInMenuList) {
        ResponseBean responseBean = new ResponseBean();
        try{
            // 新增角色
            TaRole taRole = new TaRole();
            taRole.setRoleName(name);
            taRole.setOrgId(orgId);
            taRole.setStatus(1);
            taRole.setCreateDate(LocalDateTime.now());
            taRoleMapper.insert(taRole);

            // 新增角色需要的菜单
          for (SysMenu sysMenu: sysMenuList){
              TaRoleMenu taRoleMenu = new TaRoleMenu();
              taRoleMenu.setRoleId(taRole.getRoleId());
              taRoleMenu.setMenuId(sysMenu.getMenuId());
              taRoleMenuMapper.insert(taRoleMenu);
          }
          // 新增角色按钮
          for (SysButtonInMenu sysButtonInMenu :sysButtonInMenuList){
              TaRoleButton  taRoleButton = new TaRoleButton();
              taRoleButton.setRoleId(taRole.getRoleId());
              taRoleButton.setBtnId(sysButtonInMenu.getBtnId());
              taRoleButtonMapper.insert(taRoleButton);
          }
            responseBean.addSuccess("操作成功");
            return  true;
        }catch (Exception e){
            responseBean.addSuccess("操作失败");
            e.printStackTrace();
            return false;
        }
    }
}
