package com.artfess.cqxy.projectManagement.manager.impl;

import com.artfess.base.conf.SaaSConfig;
import com.artfess.base.constants.TenantConstant;
import com.artfess.base.context.BaseContext;
import com.artfess.base.exception.BaseException;
import com.artfess.base.feign.UCFeignService;
import com.artfess.base.handler.MultiTenantHandler;
import com.artfess.base.handler.MultiTenantIgnoreResult;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryField;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.query.QueryOP;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.StringUtil;
import com.artfess.base.util.UniqueIdUtil;
import com.artfess.cqxy.projectManagement.dao.ProjectPersonnelMenuDao;
import com.artfess.cqxy.projectManagement.manager.ProjectManagementManager;
import com.artfess.cqxy.projectManagement.manager.ProjectPersonnelMenuManager;
import com.artfess.cqxy.projectManagement.model.ProjectManagement;
import com.artfess.cqxy.projectManagement.model.ProjectPersonnelMenu;
import com.artfess.cqxy.projectManagement.vo.ProjectPersonnelMenuVo;
import com.artfess.i18n.util.I18nUtil;
import com.artfess.sysConfig.persistence.dao.SysMethodDao;
import com.artfess.sysConfig.persistence.manager.SysMenuManager;
import com.artfess.sysConfig.persistence.model.SysMenu;
import com.artfess.sysConfig.persistence.model.SysRoleAuth;
import com.artfess.uc.api.impl.util.ContextUtil;
import com.artfess.uc.api.model.IUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 项目人员菜单中间表(BizProjectPersonnelMenu)表服务实现类
 *
 * @author baseli
 * @since 2022年5月30日12:59:19
 */
@Service
public class ProjectPersonnelMenuManagerImpl extends BaseManagerImpl<ProjectPersonnelMenuDao, ProjectPersonnelMenu> implements ProjectPersonnelMenuManager {


    @Resource
    private ProjectPersonnelMenuDao projectPersonnelMenuDao;
    @Resource
    private SysMenuManager sysMenuManager;
    @Resource
    private UCFeignService uCFeignService;
    @Value("${system.mode.demo:false}")
    protected boolean demoMode;
    @Autowired
    private SaaSConfig saaSConfig;
    @Resource
    private MultiTenantHandler multiTenantHandler;
    @Resource
    private BaseContext baseContext;
    @Resource
    private ProjectManagementManager projectManagementManager;


    @Override
    public void create(ProjectPersonnelMenuVo projectPersonnelMenuVo) {
        baseMapper.removeByProjectIdAndUserId(projectPersonnelMenuVo.getProjectId(), projectPersonnelMenuVo.getUserId());

        List<String> arrMenuAlias = projectPersonnelMenuVo.getArrMenuAlias();
        ProjectPersonnelMenu projectPersonnelMenu = new ProjectPersonnelMenu();
        projectPersonnelMenu.setProjectId(projectPersonnelMenuVo.getProjectId());
        projectPersonnelMenu.setUserlId(projectPersonnelMenuVo.getUserId());
        for (String menuAlias : arrMenuAlias) {
            projectPersonnelMenu.setId(UniqueIdUtil.getSuid());
            projectPersonnelMenu.setMenuAlias(menuAlias);
            baseMapper.insert(projectPersonnelMenu);
        }
        projectPersonnelMenu.setMenuAlias(null);

        List<String> arrMethodAlias = projectPersonnelMenuVo.getArrMethodAlias();
        Map<String, String> dataPermission = projectPersonnelMenuVo.getDataPermission();
        for (String methodAlias : arrMethodAlias) {
            projectPersonnelMenu.setId(UniqueIdUtil.getSuid());
            projectPersonnelMenu.setMethodAlias(methodAlias);
            projectPersonnelMenu.setDataPermission(dataPermission.get(methodAlias));
            baseMapper.insert(projectPersonnelMenu);
        }
    }

    @Override
    public List<Map<String, Object>> getAllMenuByProject(String projectId, String userId, String status) throws Exception{
        List<Map<String, Object>> result = sysMenuManager.getAllMenuRoleAlias(projectId, userId, status);
        // 将角色的菜单也查询出来，设置为勾选状态
//        List<SysMenu> currentUserMenu = sysMenuManager.getCurrentUserMenu();
//        if(null != currentUserMenu && currentUserMenu.size() > 0){
//            for (SysMenu sysMenu : currentUserMenu){
//                for (Map map : result){
//                    if(sysMenu.getAlias().equals(map.get("alias"))){
//                        map.put("checked", 1);
//                    }
//                }
//            }
//        }
        return result;
    }

    @Override
    public List<SysMenu> getCurrentUserMenuByProject(String projectId, String menuAlias) throws Exception {
        Boolean isAdmin = false;
        ProjectManagement project = projectManagementManager.getById(projectId);
        IUser currentUser = ContextUtil.getCurrentUser();
        if(BeanUtils.isEmpty(currentUser)) {
            throw new BaseException("未获取到当前登录用户，请刷新页面后重试！");
        }
        // 1.如果是项目负责人，设置isadmin为true，查询所有菜单
        String currentUserId = currentUser.getUserId();
        String projectManagerId = project.getProjectManagerId();
        List<String> menuList = null;
        // 如果当前用户是项目负责人，就不用过滤菜单
        if(StringUtils.isNotBlank(projectManagerId)){
            ArrayList<String> projectManagerIdList = new ArrayList<String>(Arrays.asList(projectManagerId.split(",")));
            if(projectManagerIdList.contains(currentUserId)){
                isAdmin = true;
            }
        }
        //跳过管理员，不是管理员时查询项目负责人授权的菜单别名集合
        if(!isAdmin){
            menuList = projectPersonnelMenuDao.queryAliasByProjectIdAndUserId(projectId, currentUserId);
        }
        // 2.根据当前用户的角色和别名集合查询菜单集合
        List<SysMenu> lists = sysMenuManager.getCurrentUserMenuByProject(isAdmin, menuList, currentUser);
        lists = i18nSysMenu(lists);
        List<SysMenu> result = sysMenuManager.filterByMenuAlias(menuAlias, lists);
        return result;
    }

    //  菜单资源国际化
    private List<SysMenu> i18nSysMenu(List<SysMenu> lists) {
        List<String> i18nKey = new ArrayList<String>();
        for (SysMenu sysMenu : lists) {
            i18nKey.add(sysMenu.getAlias());
        }
        Map<String, String> messages = I18nUtil.getMessages(i18nKey, LocaleContextHolder.getLocale());
        for (SysMenu sysMenu : lists) {
            String key = sysMenu.getAlias();
            if (messages.containsKey(key) && StringUtil.isNotEmpty(messages.get(key)) && !key.equals(messages.get(key))) {
                sysMenu.setName(messages.get(key));
            }
        }
        return lists;
    }
}

