package shop.alien.gateway.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreInfo;
import shop.alien.entity.store.StorePlatformRole;
import shop.alien.entity.store.StorePlatformUserRole;
import shop.alien.entity.store.StoreUser;
import shop.alien.entity.store.vo.StoreUserVo;
import shop.alien.gateway.config.BaseRedisService;
import shop.alien.gateway.mapper.StoreInfoGatewayMapper;
import shop.alien.gateway.mapper.StorePlatformRoleGatewayMapper;
import shop.alien.gateway.mapper.StorePlatformRoleMenuGatewayMapper;
import shop.alien.gateway.mapper.StorePlatformUserRoleGatewayMapper;
import shop.alien.gateway.mapper.StoreUserGatewayMapper;
import shop.alien.gateway.service.StoreUserService;
import shop.alien.util.common.JwtUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 二期-门店用户 服务实现类
 *
 * @author ssk
 * @since 2024-12-11
 */
@Slf4j
@Transactional
@Service
@RequiredArgsConstructor
public class StoreUserServiceImpl extends ServiceImpl<StoreUserGatewayMapper, StoreUser> implements StoreUserService {

    @Value("${jwt.expiration-time}")
    private String effectiveTime;

    /**
     * 设定初始化默认密码
     */

    private final StoreInfoGatewayMapper storeInfoMapper;

    private final BaseRedisService baseRedisService;

    private final StorePlatformUserRoleGatewayMapper storePlatformUserRoleMapper;
    
    private final StorePlatformRoleMenuGatewayMapper storePlatformRoleMenuMapper;
    
    private final StorePlatformRoleGatewayMapper storePlatformRoleMapper;

    /**
     * token
     *
     * @param storeUser
     * @return
     */
    @Override
    public R<StoreUserVo> createToKen(StoreUser storeUser) {
        int effectiveTimeInt = Integer.parseInt(effectiveTime.substring(0, effectiveTime.length() - 1));
        String effectiveTimeUnit = effectiveTime.substring(effectiveTime.length() - 1);
        long effectiveTimeIntLong = 0L;
        switch (effectiveTimeUnit) {
            case "s": {
                effectiveTimeIntLong = effectiveTimeInt * 1000L;
                break;
            }
            case "m": {
                effectiveTimeIntLong = effectiveTimeInt * 60L * 1000L;
                break;
            }
            case "h": {
                effectiveTimeIntLong = effectiveTimeInt * 60L * 60L * 1000L;
                break;
            }
            case "d": {
                effectiveTimeIntLong = effectiveTimeInt * 24L * 60L * 60L * 1000L;
                break;
            }
        }

        StoreUserVo storeUserVo = new StoreUserVo();
        BeanUtils.copyProperties(storeUser, storeUserVo);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("phone", storeUser.getPhone());
        tokenMap.put("userName", storeUser.getName());
        tokenMap.put("userId", storeUser.getId().toString());
        tokenMap.put("userType", "store");
        storeUserVo.setToken(JwtUtil.createJWT("store_" + storeUser.getPhone(), storeUser.getName(), JSONObject.toJSONString(tokenMap), effectiveTimeIntLong));
        baseRedisService.setString("store_" + storeUser.getPhone(), storeUserVo.getToken());
        if(storeUserVo.getStoreId() == null){
            // 子账号登录，查询当前子账号权限最多的那个门店和角色id
            log.info("子账号登录，storeId为空，查询权限最多的门店 - userId: {}", storeUser.getId());
            
            // 查询子账号关联的所有门店和角色
            LambdaQueryWrapper<StorePlatformUserRole> roleWrapper = new LambdaQueryWrapper<>();
            roleWrapper.eq(StorePlatformUserRole::getUserId, storeUser.getId())
                    .eq(StorePlatformUserRole::getDeleteFlag, 0);
            List<StorePlatformUserRole> userRoles = storePlatformUserRoleMapper.selectList(roleWrapper);
            
            if (userRoles != null && !userRoles.isEmpty()) {
                // 计算每个角色的菜单权限数量，选择权限最多的门店
                StorePlatformUserRole maxPermissionRole = null;
                int maxPermissionCount = -1;
                
                for (StorePlatformUserRole userRole : userRoles) {
                    if (userRole.getRoleId() != null) {
                        // 查询该角色的菜单权限数量
                        Integer permissionCount = storePlatformRoleMenuMapper.countMenuByRoleId(userRole.getRoleId());
                        if (permissionCount == null) {
                            permissionCount = 0;
                        }
                        
                        // 如果权限数量更多，或者权限数量相同但角色ID更大，则更新
                        if (permissionCount > maxPermissionCount || 
                            (permissionCount == maxPermissionCount && 
                             (maxPermissionRole == null || userRole.getRoleId() > maxPermissionRole.getRoleId()))) {
                            maxPermissionCount = permissionCount;
                            maxPermissionRole = userRole;
                        }
                    }
                }
                
                if (maxPermissionRole != null) {
                    // 设置门店ID和角色ID
                    storeUserVo.setStoreId(maxPermissionRole.getStoreId());
                    storeUserVo.setRoleId(maxPermissionRole.getRoleId());
                    
                    // 查询角色名称
                    if (maxPermissionRole.getRoleId() != null) {
                        StorePlatformRole role = storePlatformRoleMapper.selectById(maxPermissionRole.getRoleId());
                        if (role != null) {
                            storeUserVo.setRoleName(role.getRoleName());
                        }
                    }
                    
                    log.info("子账号权限最多的门店查询成功 - userId: {}, storeId: {}, roleId: {}, roleName: {}, 权限数量: {}", 
                            storeUser.getId(), maxPermissionRole.getStoreId(), maxPermissionRole.getRoleId(), 
                            storeUserVo.getRoleName(), maxPermissionCount);
                } else {
                    log.warn("子账号关联的门店都没有角色ID - userId: {}", storeUser.getId());
                }
            } else {
                log.warn("子账号未关联任何门店 - userId: {}", storeUser.getId());
            }
        }
        // 查询门店信息（如果storeId不为空）
        StoreInfo storeInfo = null;
        if (storeUserVo.getStoreId() != null) {
            storeInfo = storeInfoMapper.selectById(storeUserVo.getStoreId());
        }
        if (storeInfo != null) {
            storeUserVo.setBusinessSection(storeInfo.getBusinessSection());
            storeUserVo.setBusinessTypesName(storeInfo.getBusinessTypesName());
        }
        return R.data(storeUserVo);
    }

    @Override
    public R<StoreUserVo> switchSubAccountStore(Integer userId, Integer storeId) {
        log.info("StoreUserServiceImpl.switchSubAccountStore?userId={}, storeId={}", userId, storeId);

        if (userId == null || storeId == null) {
            log.warn("用户ID或门店ID为空 - userId: {}, storeId: {}", userId, storeId);
            return R.fail("用户ID或门店ID不能为空");
        }

        // 1. 查询用户信息（类似登录接口，验证用户是否存在）
        StoreUser storeUser = this.getById(userId);
        if (storeUser == null) {
            log.warn("用户不存在 - userId: {}", userId);
            return R.fail("当前账号不存在，请先去注册账号！");
        }

        // 2. 验证账号状态
        if (storeUser.getStatus() == 1) {
            log.warn("账号被禁用 - userId: {}", userId);
            return R.fail("账号被禁用");
        }

        // 3. 判断是主账号还是子账号，并验证门店关联
        Long roleId = null;
        Integer finalStoreId = null; // 最终要回显的门店ID
        StoreInfo storeInfo = new StoreInfo();
        if (storeUser.getStoreId() != null && storeUser.getStoreId().equals(storeId)) {
            // 主账号：直接回显 store_user 的门店 id
//            if (storeUser.getStoreId() == null || !storeUser.getStoreId().equals(storeId)) {
//                log.warn("主账号门店ID不匹配 - userId: {}, 传入storeId: {}, 实际storeId: {}",
//                        userId, storeId, storeUser.getStoreId());
//                return R.fail("切换失败，门店ID不匹配");
//            }
            finalStoreId = storeUser.getStoreId();
            roleId = null; // 主账号没有角色id
        } else {
            // 子账号：查询角色关联表，回显子账号关联的门店 id
            LambdaQueryWrapper<StorePlatformUserRole> roleWrapper = new LambdaQueryWrapper<>();
            roleWrapper.eq(StorePlatformUserRole::getUserId, userId)
                    .eq(StorePlatformUserRole::getStoreId, storeId)
                    .eq(StorePlatformUserRole::getDeleteFlag, 0);
            StorePlatformUserRole userRole = storePlatformUserRoleMapper.selectOne(roleWrapper);
            
            if (userRole == null) {
                log.warn("子账号未关联目标门店 - userId: {}, storeId: {}", userId, storeId);
                return R.fail("切换失败，请确认子账号是否关联了该门店");
            }
            
            finalStoreId = userRole.getStoreId(); // 从关联表获取门店ID
            storeInfo = storeInfoMapper.selectById(finalStoreId);
            roleId = userRole.getRoleId() != null ? userRole.getRoleId() : null;
        }

        // 4. 删除旧的token（参考switchingStates逻辑）
        baseRedisService.delete("store_" + storeUser.getPhone());
        baseRedisService.delete("storePlatform_" + storeUser.getPhone());
        log.info("删除用户token - phone: {}", storeUser.getPhone());

        // 5. 创建临时用户对象用于生成token（设置正确的门店ID）
        StoreUser tempUser = new StoreUser();
        BeanUtils.copyProperties(storeUser, tempUser);
        tempUser.setStoreId(finalStoreId);

        // 6. 生成token（类似登录接口）
        R<StoreUserVo> tokenResult = createToKen(tempUser);
        if (tokenResult.getCode() != 200 || tokenResult.getData() == null) {
            log.error("生成token失败 - userId: {}", userId);
            return R.fail("切换失败，token生成失败");
        }

        // 7. 设置角色ID和门店ID（如果没有角色id，该字段为null）
        StoreUserVo storeUserVo = tokenResult.getData();
        storeUserVo.setRoleId(roleId);
        storeUserVo.setStoreId(finalStoreId); // 确保回显正确的门店ID
        
        // 查询并设置角色名称
        if (roleId != null) {
            StorePlatformRole role = storePlatformRoleMapper.selectById(roleId);
            if (role != null) {
                storeUserVo.setRoleName(role.getRoleName());
            }
        }
        
        if(storeInfo != null){
            storeUserVo.setName(storeInfo.getStoreName());
        }

        log.info("切换门店成功 - userId: {}, storeId: {}, roleId: {}", userId, finalStoreId, roleId);
        return R.data(storeUserVo);
    }

}
