package cn.stylefeng.team.portal.modular.front.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.roses.kernel.auth.api.context.LoginContext;
import cn.stylefeng.roses.kernel.sys.modular.login.pojo.IndexUserAppInfo;
import cn.stylefeng.roses.kernel.sys.modular.login.pojo.IndexUserMenuInfo;
import cn.stylefeng.roses.kernel.sys.modular.login.pojo.UserIndexInfo;
import cn.stylefeng.roses.kernel.sys.modular.login.service.UserIndexInfoService;
import cn.stylefeng.team.portal.api.enums.LinkRedirectTypeEnum;
import cn.stylefeng.team.portal.modular.front.factory.AppCenterFactory;
import cn.stylefeng.team.portal.modular.front.pojo.appcenter.AppCenterCategory;
import cn.stylefeng.team.portal.modular.front.pojo.appcenter.AppCenterLink;
import cn.stylefeng.team.portal.modular.front.pojo.request.AppCenterRequest;
import cn.stylefeng.team.portal.modular.front.service.AppCenterService;
import cn.stylefeng.team.portal.modular.management.entity.CommonAppLink;
import cn.stylefeng.team.portal.modular.management.entity.CommonAppLinkCategory;
import cn.stylefeng.team.portal.modular.management.entity.CommonAppLinkUserConfig;
import cn.stylefeng.team.portal.modular.management.mapper.CommonAppLinkUserConfigMapper;
import cn.stylefeng.team.portal.modular.management.service.CommonAppLinkCategoryService;
import cn.stylefeng.team.portal.modular.management.service.CommonAppLinkService;
import cn.stylefeng.team.portal.modular.management.service.CommonAppLinkUserConfigService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class AppCenterServiceImpl implements AppCenterService {

    @Resource
    private CommonAppLinkCategoryService commonAppLinkCategoryService;

    @Resource
    private CommonAppLinkService commonAppLinkService;

    @Resource
    private UserIndexInfoService userIndexInfoService;

    @Resource
    private CommonAppLinkUserConfigMapper commonAppLinkUserConfigMapper;

    @Resource
    private CommonAppLinkUserConfigService commonAppLinkUserConfigService;

    @Override
    public List<AppCenterCategory> getTotalCategoryAndLink(AppCenterRequest appCenterRequest) {

        List<AppCenterCategory> result = new ArrayList<>();

        LambdaQueryWrapper<CommonAppLinkCategory> commonAppLinkCategoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        commonAppLinkCategoryLambdaQueryWrapper.select(CommonAppLinkCategory::getCategoryId, CommonAppLinkCategory::getCategoryName, CommonAppLinkCategory::getIconType,
                CommonAppLinkCategory::getIconCode, CommonAppLinkCategory::getCategoryIconFileId);
        commonAppLinkCategoryLambdaQueryWrapper.orderByAsc(CommonAppLinkCategory::getFldSort);
        List<CommonAppLinkCategory> categoryList = commonAppLinkCategoryService.list(commonAppLinkCategoryLambdaQueryWrapper);
        if (ObjectUtil.isEmpty(categoryList)) {
            return result;
        }

        LambdaQueryWrapper<CommonAppLink> commonAppLinkLambdaQueryWrapper = new LambdaQueryWrapper<>();
        commonAppLinkLambdaQueryWrapper.select(CommonAppLink::getAppLinkId, CommonAppLink::getLinkCategoryId, CommonAppLink::getLinkName, CommonAppLink::getIconType, CommonAppLink::getIconCode,
                CommonAppLink::getLinkIconFileId, CommonAppLink::getRedirectType, CommonAppLink::getRedirectUrl, CommonAppLink::getOpenType);
        commonAppLinkLambdaQueryWrapper.orderByAsc(CommonAppLink::getFldSort);
        List<CommonAppLink> commonAppLinkList = commonAppLinkService.list(commonAppLinkLambdaQueryWrapper);

        Set<String> userPermissionRouterList = this.getUserPermissionRouterList();

        for (CommonAppLinkCategory commonAppLinkCategory : categoryList) {
            AppCenterCategory appCenterCategory = new AppCenterCategory();
            appCenterCategory.setCategoryId(commonAppLinkCategory.getCategoryId());
            appCenterCategory.setCategoryName(commonAppLinkCategory.getCategoryName());
            appCenterCategory.setIconType(commonAppLinkCategory.getIconType());
            appCenterCategory.setIconCode(commonAppLinkCategory.getIconCode());
            appCenterCategory.setCategoryIconFileId(commonAppLinkCategory.getCategoryIconFileId());
            appCenterCategory.setAppLinkList(new ArrayList<>());

            for (CommonAppLink commonAppLink : commonAppLinkList) {
                if (ObjectUtil.equal(commonAppLinkCategory.getCategoryId(), commonAppLink.getLinkCategoryId())) {

                    AppCenterLink appCenterLink = AppCenterFactory.buildAppLink(commonAppLink);


                    if (LinkRedirectTypeEnum.ITEM_2.getCode().equals(commonAppLink.getRedirectType())) {
                        appCenterLink.setCanUseFlag(true);
                    } else {
                        appCenterLink.setCanUseFlag(userPermissionRouterList.contains(appCenterLink.getRedirectUrl()));
                    }

                    appCenterCategory.getAppLinkList().add(appCenterLink);
                }
            }

            result.add(appCenterCategory);
        }

        return result;
    }

    @Override
    public List<AppCenterLink> getCurrentUserLinkList() {
        Long userId = LoginContext.me().getLoginUser().getUserId();
        return commonAppLinkUserConfigMapper.getUserAppLinkList(userId);
    }

    @Override
    public List<AppCenterCategory> getUserConfigList() {

        List<AppCenterCategory> totalCategoryAndLink = this.getTotalCategoryAndLink(null);
        if (ObjectUtil.isEmpty(totalCategoryAndLink)) {
            return new ArrayList<>();
        }

        Long userId = LoginContext.me().getLoginUser().getUserId();
        Set<Long> userSelectedAppLinkIdList = commonAppLinkUserConfigService.getUserSelectedAppLinkIdList(userId);
        if (ObjectUtil.isEmpty(userSelectedAppLinkIdList)) {
            return totalCategoryAndLink;
        }
        for (AppCenterCategory appCenterCategory : totalCategoryAndLink) {
            for (AppCenterLink appCenterLink : appCenterCategory.getAppLinkList()) {
                if (userSelectedAppLinkIdList.contains(appCenterLink.getAppLinkId())) {
                    appCenterLink.setSelectFlag(true);
                }
            }
        }

        return totalCategoryAndLink;
    }

    @Override
    public void updateUserConfigList(AppCenterRequest appCenterRequest) {

        Long userId = LoginContext.me().getLoginUser().getUserId();
        commonAppLinkUserConfigService.cleanUserBindLinks(userId);

        List<AppCenterLink> currentUserAppLinkList = appCenterRequest.getCurrentUserAppLinkList();
        for (int i = 0; i < currentUserAppLinkList.size(); i++) {
            AppCenterLink appCenterLink = currentUserAppLinkList.get(i);
            appCenterLink.setFldSort(BigDecimal.valueOf(i));
        }

        List<CommonAppLinkUserConfig> configList = new ArrayList<>();
        for (AppCenterLink appCenterLink : currentUserAppLinkList) {
            CommonAppLinkUserConfig commonAppLinkUserConfig = new CommonAppLinkUserConfig();
            commonAppLinkUserConfig.setUserId(userId);
            commonAppLinkUserConfig.setLinkCategoryId(appCenterLink.getLinkCategoryId());
            commonAppLinkUserConfig.setAppLinkId(appCenterLink.getAppLinkId());
            commonAppLinkUserConfig.setFldSort(appCenterLink.getFldSort());
            configList.add(commonAppLinkUserConfig);
        }
        this.commonAppLinkUserConfigService.saveBatch(configList);
    }

    private Set<String> getUserPermissionRouterList() {
        UserIndexInfo userIndexInfo = userIndexInfoService.getUserIndexInfo();
        if (ObjectUtil.isEmpty(userIndexInfo)) {
            return new HashSet<>();
        }

        List<IndexUserAppInfo> userAppInfoList = userIndexInfo.getUserAppInfoList();
        if (ObjectUtil.isEmpty(userAppInfoList)) {
            return new HashSet<>();
        }

        HashSet<String> userAllRouters = new HashSet<>();
        for (IndexUserAppInfo indexUserAppInfo : userAppInfoList) {
            List<IndexUserMenuInfo> menuList = indexUserAppInfo.getMenuList();
            getUserPermissionRouterList(menuList, userAllRouters);
        }

        return userAllRouters;
    }

    private void getUserPermissionRouterList(List<IndexUserMenuInfo> menuList, HashSet<String> userAllRouters) {
        for (IndexUserMenuInfo indexUserMenuInfo : menuList) {
            if (ObjectUtil.isNotEmpty(indexUserMenuInfo.getChildren())) {
                getUserPermissionRouterList(indexUserMenuInfo.getChildren(), userAllRouters);
            } else {
                userAllRouters.add(indexUserMenuInfo.getPath());
            }
        }
    }

}
