package com.sckw.auth.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.sckw.auth.model.vo.req.RoleChangeVo;
import com.sckw.core.model.constant.Global;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.model.LoginUserInfo;
import com.sckw.redis.utils.RedissonUtils;
import com.sckw.system.api.RemoteUserService;
import com.sckw.system.api.model.dto.res.EntCacheResDto;
import com.sckw.system.api.model.dto.res.KwsUserResDto;
import com.sckw.system.api.model.dto.res.UserAccessMenuInfoResDto;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author xucaiqin
 * @date 2025-11-15 10:28:35
 */
@Slf4j
public class UserService {
    private final RoleChangeVo loginBase;

    private final KwsUserResDto user;


    private final EntCacheResDto enterprise;

    private final RemoteUserService remoteUserService;

    public UserService(RoleChangeVo loginBase, KwsUserResDto user, EntCacheResDto enterprise,
                       RemoteUserService remoteUserService) {
        this.loginBase = loginBase;
        this.user = user;
        this.enterprise = enterprise;
        this.remoteUserService = remoteUserService;
    }

    public void run() {
        if (user == null) {
            return;
        }
        //存用户登录信息
        LoginUserInfo loginUserInfo = new LoginUserInfo();
        loginUserInfo.setId(user.getId());
        loginUserInfo.setSystemType(loginBase.getSystemType());
        loginUserInfo.setClientType(loginBase.getClientType());
        loginUserInfo.setAccount(user.getPhone());
        loginUserInfo.setUserName(user.getName());
        loginUserInfo.setPhone(user.getPhone());
        loginUserInfo.setStatus(user.getStatus());
        loginUserInfo.setIsMain(user.getIsMain());
        loginUserInfo.setEntId(user.getEntId());
        loginUserInfo.setUseRoleId(loginBase.getRoleId());
        loginUserInfo.setUseEntId(loginBase.getEntId());
        loginUserInfo.setEntName(enterprise != null ? enterprise.getFirmName() : null);

        //普通用户需要填充数据权限 //11.15 用户id数据权限已经去掉
//        if (user.getIsMain().equals(Global.NO)) {
//            loginUserInfo.setAuthUserIdList(remoteUserService.queryAuthUserList(user.getId()));
//        } else {
//            List<FindEntUserResDto> entUser = remoteUserService.findEntUser(user.getEntId());
//            if (CollectionUtils.isNotEmpty(entUser)) {
//                loginUserInfo.setAuthUserIdList(entUser.stream().map(FindEntUserResDto::getUserId).distinct().toList());
//            }
//        }
        saveEntList(loginUserInfo);
        String key = Global.getFullUserLoginKey(loginUserInfo.getSystemType(), loginUserInfo.getId());
        RedissonUtils.putString(key, JSON.toJSONString(loginUserInfo), Global.APP_TOKEN_EXPIRE);
        //存缓存请求地址
        saveMenusToCache(user.getId(), loginUserInfo.getSystemType(), loginBase.getRoleId());
    }


    private void saveEntList(LoginUserInfo loginUserInfo) {
        List<Long> childEntList = remoteUserService.findChildEntList(loginUserInfo.getUseEntId());
        if (CollUtil.isNotEmpty(childEntList)) {
            loginUserInfo.setChildEntList(childEntList);
        }
    }

    private void saveMenusToCache(Long userId, Integer systemType, Long roleId) {
        //存权限菜单
        List<UserAccessMenuInfoResDto> userAccessMenuInfo = remoteUserService.queryRoleMenu(roleId);
        if (CollectionUtils.isEmpty(userAccessMenuInfo)) {
            RedissonUtils.delete(Global.REDIS_SYS_MENU_PREFIX + systemType + Global.COLON + userId);
            log.error("未查询到用户 [{}] 角色 [{}] 的菜单权限", userId, roleId);
            return;
        }

        List<String> menus = new ArrayList<>();
        for (UserAccessMenuInfoResDto userAccessMenuInfoResDto : userAccessMenuInfo) {
            String links = userAccessMenuInfoResDto.getLinks();
            if (StringUtils.isNotBlank(links)) {
                menus.addAll(Arrays.asList(userAccessMenuInfoResDto.getLinks().split(",")));
            }
        }
        RedissonUtils.putSet(Global.REDIS_SYS_MENU_PREFIX + userId, menus);
    }
}
