package com.mvc.service.router;

import com.mvc.constant.BaseConstant;
import com.mvc.dao.TDynamicrouteMetaMapper;
import com.mvc.dao.TDynamicrouterMapper;
import com.mvc.entity.*;
import com.mvc.model.DicCustomizeMenuModel;
import com.mvc.model.FacUserModel;
import com.mvc.model.TAffiliatedunitModel;
import com.mvc.model.router.TDynamicrouteMetaModel;
import com.mvc.model.router.TDynamicrouterModel;
import com.mvc.service.TAffiliatedunitService;
import com.mvc.service.dic.DicCustomizeMenuService;
import com.mvc.service.dic.FacUserRoleService;
import com.mvc.service.dic.FacUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Transactional
public class TDynamicrouterService {
    @Resource
    private TDynamicrouterMapper dynamicrouterMapper;

    @Resource
    private TDynamicrouteMetaMapper dynamicrouteMetaMapper;

    @Resource
    private FacUserRoleService facUserRoleService;

    @Resource
    private TAffiliatedunitService affiliatedunitService;

    @Resource
    private DicCustomizeMenuService dicCustomizeMenuService;

    @Resource
    private FacUserService facUserService;

    //public static final String CUSTOMIZ_META_TITLE_SYMBOL = "*";//用来区分路由自定义功能的标题
    public static final String CUSTOMIZ_ROUTER_PATH_SYMBOL = "2";//用来区分路由自定义功能的Path

    public List<TDynamicrouterModel> findAllDynamicrouter(String userType, String userParam) {
        boolean isFacUser = userType.equals("0");//是否是内部用户登陆(userParam = userId)
        FacUserModel facUserModel = null;
        List<Integer> ids = null;
        String unitType = "";//客户类型使用
        if (isFacUser) {
            facUserModel = facUserService.findFacUserByUserId(userParam);
            ids = facUserRoleService.findRouterByRoleId(facUserModel.getRoleId());
            if (ids == null || ids.size() == 0) {//该角色没有任何权限
                return new ArrayList<>();
            }
        } else {
            TAffiliatedunitModel affiliatedunitModel = affiliatedunitService.findTAffiliatedunit(userParam);
            if (affiliatedunitModel != null) {
                unitType = affiliatedunitModel.getUnitType();
            }
        }

        TDynamicrouterExample example = new TDynamicrouterExample();
        TDynamicrouterExample.Criteria criteria = example.createCriteria();
        criteria.andUseFlagEqualTo(1);
        example.setOrderByClause("view_order");
        List<TDynamicrouter> list = dynamicrouterMapper.selectByExample(example);
        List<TDynamicrouter> listLv1 = list.stream().filter(s -> s.getLevel() == 1).collect(Collectors.toList());

        List<TDynamicrouterModel> resList = new ArrayList<>();

        List<String> tempList = new ArrayList<>();//去重(自定义与实际的)
        if (listLv1 != null) {
            for (TDynamicrouter entity : listLv1) {
                if (isFacUser && ids.indexOf(entity.getId()) == -1) {//内部用户根据角色过滤一级菜单
                    continue;
                }

                TDynamicrouteMetaModel metaModel = findDynamicrouterMateByRouterId(entity.getId());
                if (metaModel == null) {
                    continue;
                } else {
                    if (!isFacUser) {
                        if (!metaModel.getIsCxac() || StringUtils.isEmpty(metaModel.getAllowUnitTypes()) || !metaModel.getAllowUnitTypes().contains(unitType)) {//客户无权限
                            continue;
                        }
                    }
                }

                TDynamicrouterModel model = new TDynamicrouterModel();
                BeanUtils.copyProperties(entity, model);
                model.setMeta(metaModel);
                //处理二级菜单
                List<TDynamicrouterModel> listLv2 = new ArrayList<>();
                for (TDynamicrouter entityLv2 : list) {
                    if (entityLv2.getParentId() == entity.getId()) {
                        //自定义菜单中的有,不再其它一级菜单中出现(防止前台KeepAlive因重复出现问题) 2024-07-25 guozhao
                        if(tempList.contains(entityLv2.getPath())){
                            continue;
                        }

                        TDynamicrouteMetaModel metaModel2 = findDynamicrouterMateByRouterId(entityLv2.getId());

                        if (metaModel2 == null) continue;

                        if (!isFacUser) {
                            //添加AllowUnitTypes(允许访问的单位类型控制) 2024-04-28 guozhao
                            if (!metaModel2.getIsCxac() || StringUtils.isEmpty(metaModel.getAllowUnitTypes()) || !metaModel2.getAllowUnitTypes().contains(unitType)) {//客户无权限
                                continue;
                            }
                        }
                        TDynamicrouterModel model2 = new TDynamicrouterModel();
                        BeanUtils.copyProperties(entityLv2, model2);
                        model2.setMeta(metaModel2);
                        model2.setChildren(new ArrayList<>());

                        listLv2.add(model2);
                    }
                }
                model.setChildren(listLv2);

                if (StringUtils.isEmpty(model.getRedirect())) {
                    model.setRedirect("");
                }
                if (StringUtils.isEmpty(model.getComponent())) {
                    model.setRedirect("");
                }

                if (isFacUser && entity.getId() == BaseConstant.CUSTOMIZ_ROUTER_ID) {
                    List<TDynamicrouterModel> customizeList = generateRouterByCustomizeMenu(facUserModel.getId(), list,tempList);
                    model.setChildren(customizeList);
                }

                resList.add(model);
            }
        }

        return resList;
    }


    /**
     * 根据自定义菜单生成路由
     *
     * @param userId
     * @param dynamicrouterList
     * @return
     */
    private List<TDynamicrouterModel> generateRouterByCustomizeMenu(int userId, List<TDynamicrouter> dynamicrouterList,List<String> tempList) {
        List<DicCustomizeMenuModel> list = dicCustomizeMenuService.findAllDicCustomizeMenuByUserId(userId);
        Map<Integer, TDynamicrouter> dynamicrouterMap = dynamicrouterList.stream()
                .collect(Collectors.toMap(
                        TDynamicrouter::getId,
                        Function.identity(),
                        (existing, replacement) -> existing)); // 处理键冲突的情况

        List<TDynamicrouterModel> resList = new ArrayList<>();
        for (DicCustomizeMenuModel model : list) {
            if (!dynamicrouterMap.containsKey(model.getRouterId())) {
                continue;
            }
            TDynamicrouter dynamicrouter = dynamicrouterMap.get(model.getRouterId());
            TDynamicrouteMetaModel metaModel2 = findDynamicrouterMateByRouterId(dynamicrouter.getId());
            TDynamicrouterModel model2 = new TDynamicrouterModel();
            BeanUtils.copyProperties(dynamicrouter, model2);

            //自定义的菜单和原始菜单现在可以打开两个了,标题上做区分
            //metaModel2.setTitle(metaModel2.getTitle() + CUSTOMIZ_META_TITLE_SYMBOL);
            metaModel2.setTitle(metaModel2.getTitle());
            model2.setMeta(metaModel2);
            model2.setChildren(new ArrayList<>());
            //path要与原始的做区分,不然会发生激活错误的情况
            //model2.setName(model2.getName() + CUSTOMIZ_ROUTER_PATH_SYMBOL);
            //model2.setPath(model2.getPath() + CUSTOMIZ_ROUTER_PATH_SYMBOL);
            resList.add(model2);
            tempList.add(model2.getPath());
        }

        return resList;
    }

    /**
     * 根据RouterId获取meta
     *
     * @param id
     * @return
     */
    public TDynamicrouteMetaModel findDynamicrouterMateByRouterId(int id) {
        TDynamicrouteMetaExample example = new TDynamicrouteMetaExample();
        TDynamicrouteMetaExample.Criteria criteria = example.createCriteria();
        criteria.andRouterIdEqualTo(id);
        List<TDynamicrouteMeta> list = dynamicrouteMetaMapper.selectByExample(example);

        if (list != null && list.size() > 0) {
            TDynamicrouteMetaModel model = new TDynamicrouteMetaModel(list.get(0));
            return model;
        }
        return null;
    }

    /**
     * 根据path获取TDynamicrouter
     *
     * @param path
     * @return
     */
    public TDynamicrouter findDynamicrouterMateByPath(String path) {
        TDynamicrouterExample example = new TDynamicrouterExample();
        TDynamicrouterExample.Criteria criteria = example.createCriteria();
        criteria.andPathEqualTo(path);
        criteria.andLevelEqualTo(2);//必须是二级菜单
        List<TDynamicrouter> list = dynamicrouterMapper.selectByExample(example);

        return list.isEmpty() ? null : list.get(0);
    }
}
