package com.artfess.sysConfig.persistence.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.util.BeanUtils;
import com.artfess.base.util.StringUtil;
import com.artfess.sysConfig.persistence.dao.SysSwiftMenuDao;
import com.artfess.sysConfig.persistence.manager.SysMenuManager;
import com.artfess.sysConfig.persistence.manager.SysSwiftMenuManager;
import com.artfess.sysConfig.persistence.model.SysMenu;
import com.artfess.sysConfig.persistence.model.SysSwiftMenu;
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.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <pre>
 * 描述：用户自定义菜单 处理实现类
 * 构建组：x6
 * 作者:liyg
 * 邮箱:liygui@jee-soft.cn
 * 日期:2018-06-29 14:27:46
 * 版权：广州宏天软件有限公司
 * </pre>
 */
@Service("sysSwiftMenuAuthManager")
public class SysSwiftMenuManagerImpl extends BaseManagerImpl<SysSwiftMenuDao, SysSwiftMenu> implements SysSwiftMenuManager {

    @Resource
    UCFeignService uCFeignService;
    @Autowired
    SaaSConfig saaSConfig;
    @Autowired
    SysMenuManager sysMenuManager;
    @Resource
    BaseContext baseContext;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertSwiftMenus(String menuAlias) {
        Assert.hasText(menuAlias, "菜单别名不能为空！");
        String userId = ContextUtil.getCurrentUserId();
        SysSwiftMenu sysSwiftMenu = new SysSwiftMenu();
        sysSwiftMenu.setMenuAlias(menuAlias);
        sysSwiftMenu.setUserId(userId);
        Map<String, Object> param = new HashMap<>();
        param.put("user_id_", userId);
        Integer sn = this.getNextSequence(param);
        sysSwiftMenu.setSn(sn);
        this.baseMapper.insert(sysSwiftMenu);
        return sysSwiftMenu.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer removeSwiftMenus(String menuAlias) {
        Assert.hasText(menuAlias, "菜单别名不能为空！");
        String userId = ContextUtil.getCurrentUserId();
        QueryWrapper<SysSwiftMenu> delwrapper = new QueryWrapper<>();
        delwrapper.eq("user_id_", userId);
        delwrapper.eq("menu_alias_", menuAlias);
        int num = this.baseMapper.delete(delwrapper);

        return num;
    }

    @Override
    public List<SysMenu> getSwiftMenus(String userId,String parentMenuPath) {
        IUser currentUser = ContextUtil.getCurrentUser();
        List<SysMenu> dbMenus = null;
        if (BeanUtils.isEmpty(currentUser)) {
            throw new BaseException("未获取到当前登录用户");
        }
        if (StringUtil.isEmpty(userId)) {
            userId = ContextUtil.getCurrentUserId();
        }
        if (currentUser.isAdmin()) {
            dbMenus = this.baseMapper.getSwiftMenuByAdmin(userId,parentMenuPath);
        } else {
            List<ObjectNode> roles = uCFeignService.getRoleListByAccount(currentUser.getAccount());
            List<String> roleCodes = new ArrayList<String>();
            if (BeanUtils.isNotEmpty(roles)) {
                // 1.构建角色别名列表
                for (ObjectNode role : roles) {
                    if (1 == role.get("enabled").asInt()) {
                        roleCodes.add(role.get("code").asText());
                    }
                }
                if (BeanUtils.isNotEmpty(roleCodes)) {
                    String tenantId = saaSConfig.isEnable() ? baseContext.getCurrentTenantId() : null;
                    try (MultiTenantIgnoreResult setThreadLocalIgnore = MultiTenantHandler.setThreadLocalIgnore()) {
                        List<String> ignoreMenus = null;
                        // 3.是否需要添加忽略的菜单（非平台租户需要忽略一些菜单目录）
                        if (saaSConfig.isEnable() && !TenantConstant.PLATFORM_TENANT_ID.equals(currentUser.getTenantId())) {
                            ignoreMenus = uCFeignService.getIgnoreMenuCodes(currentUser.getTenantId());
                        }
                        // 4.根据角色列表查询角色对应的菜单目录
                        dbMenus = baseMapper.getSwiftMenuByUserId(userId, roleCodes,parentMenuPath, tenantId, BeanUtils.isEmpty(ignoreMenus) ? null : ignoreMenus);
                    } catch (Exception e) {
                        throw new BaseException(e);
                    }
                }
            }
        }
        makeUpMenu(dbMenus);
        return dbMenus;
    }

    //拼接自定义菜单的路由地址
    private void makeUpMenu(List<SysMenu> dbMenus) {
        //获取前台所有菜单
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status_", "1");
        queryWrapper.like("path_", "%.3.%");
        List<SysMenu> all = sysMenuManager.list(queryWrapper);

        Map<String, SysMenu> menuMap = all.stream().collect(Collectors.toMap(item -> item.getId(), item -> item));
        if (CollectionUtils.isEmpty(menuMap) ) {
            return ;
        }
        for (SysMenu sysMenu : dbMenus) {
            String path = sysMenu.getPath();
            String[] paths = path.split("\\.");
            StringBuffer routrtPathsb = new StringBuffer();
            //从normal开始拼接返回
            for (int i = 2; i < paths.length; i++) {
                String menuId = paths[i];
                if ( !menuMap.containsKey(menuId)) {
                    continue;
                }
                SysMenu menu = menuMap.get(menuId);
                routrtPathsb.append("/");
                routrtPathsb.append(menu.getAlias());
            }

            if (routrtPathsb.length() > 1) {
                sysMenu.setRouterPath(routrtPathsb.substring(1));
            }

        }
    }
}
