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.getAccountType() == 1) {
            // 主账号登录，判断是否有子账号
            // 通过 store_platform_user_role 表中的关联记录判断
            // 查询该门店下是否有其他账号（子账号）在 store_platform_user_role 表中有关联记录
            LambdaQueryWrapper<StorePlatformUserRole> roleWrapper = new LambdaQueryWrapper<>();
            roleWrapper.eq(StorePlatformUserRole::getUserId, storeUser.getId()) // 排除当前账号自己
                    .eq(StorePlatformUserRole::getDeleteFlag, 0);
            long subAccountCount = storePlatformUserRoleMapper.selectCount(roleWrapper);
            if (subAccountCount > 0) {
                storeUserVo.setHasSubAccount(true);
            } else {
                storeUserVo.setHasSubAccount(false);
            }
            log.info("主账号登录，检查子账号 - userId: {}, storeId: {}, hasSubAccount: {}, subAccountCount: {}",
                    storeUser.getId(), storeUserVo.getStoreId(), false, subAccountCount);
        } else {
            // 子账号切换如果有storeId 则为子账号切换无感登录 否则为正常登录
            if (storeUser.getStoreId() != null) {
                LambdaQueryWrapper<StorePlatformUserRole> roleWrapper = new LambdaQueryWrapper<>();
                roleWrapper.eq(StorePlatformUserRole::getUserId, storeUser.getId())
                        .eq(StorePlatformUserRole::getStoreId, storeUser.getStoreId())
                        .eq(StorePlatformUserRole::getDeleteFlag, 0);
                StorePlatformUserRole userRole = storePlatformUserRoleMapper.selectOne(roleWrapper);

                if (userRole == null) {
                    log.warn("子账号未关联目标门店 - userId: {}, storeId: {}", storeUser.getId(), storeUser.getStoreId());
                    return R.fail("切换失败，请确认子账号是否关联了该门店");
                }

                int finalStoreId = userRole.getStoreId(); // 从关联表获取门店ID
                StoreInfo storeInfo = storeInfoMapper.selectById(finalStoreId);
                // 查询角色名称
                if (userRole.getRoleId() != null) {
                    StorePlatformRole role = storePlatformRoleMapper.selectById(userRole.getRoleId());
                    if (role != null) {
                        storeUserVo.setRoleName(role.getRoleName());
                    }
                }
                storeUserVo.setRoleId(userRole.getRoleId());
                storeUserVo.setStoreId(storeInfo.getId());
                storeUserVo.setHasSubAccount(true);
                storeUserVo.setRoleName(userRole.getAccountName());
            } else {

                // 子账号登录，查询当前子账号权限最多的那个门店和角色id
                log.info("子账号登录，storeId为空，查询权限最多的门店 - userId: {}", storeUser.getId());
                // 查询子账号关联的所有门店和角色
                LambdaQueryWrapper<StorePlatformUserRole> roleWrapper = new LambdaQueryWrapper<>();
                roleWrapper.eq(StorePlatformUserRole::getUserId, storeUser.getId())
                        .eq(StorePlatformUserRole::getStatus, 0)
                        .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) {
                        if(maxPermissionRole.getStatus() == 1){
                            return R.fail("子账号已被禁用无法登录");
                        }
                        // 设置门店ID和角色ID
                        storeUserVo.setStoreId(maxPermissionRole.getStoreId());
                        storeUserVo.setRoleId(maxPermissionRole.getRoleId());
                        storeUserVo.setHasSubAccount(true);

                        // 查询角色名称
                        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());
                    return R.fail("子账号已被禁用无法登录");
                }
            }
        }

        // 查询门店信息（如果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, Integer accountType) {
        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("账号被禁用");
        }
        if (storeUser.getLogoutFlag() != null && StoreUser.LOGOUT_FLAG_DONE == storeUser.getLogoutFlag()
                && !Integer.valueOf(-1).equals(storeUser.getStatus())) {
            log.warn("账号已注销 - userId: {}", userId);
            return R.fail("账号已注销");
        }

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

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

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

        StoreUserVo storeUserVo = tokenResult.getData();
        return R.data(storeUserVo);
    }

}
