package shop.alien.storeplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.config.redis.BaseRedisService;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StorePlatformMenu;
import shop.alien.entity.store.StorePlatformRole;
import shop.alien.entity.store.StorePlatformUserRole;
import shop.alien.entity.store.StoreUser;
import shop.alien.entity.store.vo.PermissionItemVo;
import shop.alien.entity.store.vo.SubAccountDetailVo;
import shop.alien.entity.store.vo.SubAccountListVo;
import shop.alien.entity.store.vo.SubAccountVo;
import shop.alien.mapper.StorePlatformMenuMapper;
import shop.alien.mapper.StorePlatformRoleMapper;
import shop.alien.mapper.StorePlatformUserRoleMapper;
import shop.alien.mapper.StoreUserMapper;
import shop.alien.storeplatform.service.StorePlatformRoleMenuService;
import shop.alien.storeplatform.service.StorePlatformUserRoleService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色关联表 服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class StorePlatformUserRoleServiceImpl extends ServiceImpl<StorePlatformUserRoleMapper, StorePlatformUserRole> implements StorePlatformUserRoleService {

    private final StorePlatformUserRoleMapper storePlatformUserRoleMapper;
    private final StoreUserMapper storeUserMapper;
    private final StorePlatformRoleMenuService storePlatformRoleMenuService;
    private final StorePlatformRoleMapper storePlatformRoleMapper;
    private final StorePlatformMenuMapper storePlatformMenuMapper;
    private final BaseRedisService baseRedisService;

    @Override
    public List<Long> getRoleIdsByUserId(Integer userId, Integer storeId) {
        LambdaQueryWrapper<StorePlatformUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StorePlatformUserRole::getUserId, userId)
                .eq(StorePlatformUserRole::getStoreId, storeId);
        List<StorePlatformUserRole> list = storePlatformUserRoleMapper.selectList(queryWrapper);
        return list.stream().map(StorePlatformUserRole::getRoleId).collect(Collectors.toList());
    }

    @Override
    public List<Integer> getUserIdsByRoleId(Long roleId, Integer storeId) {
        LambdaQueryWrapper<StorePlatformUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StorePlatformUserRole::getRoleId, roleId)
                .eq(StorePlatformUserRole::getStoreId, storeId);
        List<StorePlatformUserRole> list = storePlatformUserRoleMapper.selectList(queryWrapper);
        return list.stream().map(StorePlatformUserRole::getUserId).collect(Collectors.toList());
    }

    @Override
    public boolean assignRoles(Integer userId, List<Long> roleIds, Integer storeId) {
        if (userId == null || roleIds == null || roleIds.isEmpty() || storeId == null) {
            log.error("参数不能为空");
            return false;
        }
        // 先删除用户的所有角色
        removeAllRoles(userId, storeId);
        // 批量插入新角色
        List<StorePlatformUserRole> userRoles = roleIds.stream()
                .map(roleId -> {
                    StorePlatformUserRole userRole = new StorePlatformUserRole();
                    userRole.setUserId(userId);
                    userRole.setRoleId(roleId);
                    userRole.setStoreId(storeId);
                    return userRole;
                })
                .collect(Collectors.toList());
        return this.saveBatch(userRoles);
    }

    @Override
    public boolean removeAllRoles(Integer userId, Integer storeId) {
        LambdaQueryWrapper<StorePlatformUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StorePlatformUserRole::getUserId, userId)
                .eq(StorePlatformUserRole::getStoreId, storeId);
        return storePlatformUserRoleMapper.delete(queryWrapper) >= 0;
    }

//    @Override
//    public boolean removeRole(Integer userId, Long roleId, Integer storeId) {
//        if (userId == null || roleId == null || storeId == null) {
//            log.error("参数不能为空: userId={}, roleId={}, storeId={}", userId, roleId, storeId);
//            return false;
//        }
//
//        try {
//            // 1. 先查询该用户在所有店铺下的子账号数量（未删除的）
//            LambdaQueryWrapper<StorePlatformUserRole> countWrapper = new LambdaQueryWrapper<>();
//            countWrapper.eq(StorePlatformUserRole::getUserId, userId)
//                    .eq(StorePlatformUserRole::getDeleteFlag, 0);
//            long subAccountCount = storePlatformUserRoleMapper.selectCount(countWrapper);
//
//            log.info("用户在所有店铺下的子账号数量: userId={}, count={}", userId, subAccountCount);
//
//            // 2. 逻辑删除 store_platform_user_role 表的记录
//            LambdaUpdateWrapper<StorePlatformUserRole> updateWrapper = new LambdaUpdateWrapper<>();
//            updateWrapper.eq(StorePlatformUserRole::getUserId, userId)
//                    .eq(StorePlatformUserRole::getRoleId, roleId)
//                    .eq(StorePlatformUserRole::getStoreId, storeId)
//                    .eq(StorePlatformUserRole::getDeleteFlag, 0)
//                    .set(StorePlatformUserRole::getDeleteFlag, 1); // 1代表删除
//            int updateResult = storePlatformUserRoleMapper.update(null, updateWrapper);
//
//            if (updateResult <= 0) {
//                log.error("逻辑删除 store_platform_user_role 记录失败: userId={}, roleId={}, storeId={}", userId, roleId, storeId);
//                return false;
//            }
//
//            // 3. 如果只是一个账号的子账号（删除前只有1个），则同时逻辑删除 store_user 表
//            if (subAccountCount == 1) {
//                LambdaUpdateWrapper<StoreUser> userUpdateWrapper = new LambdaUpdateWrapper<>();
//                userUpdateWrapper.eq(StoreUser::getId, userId)
//                        .eq(StoreUser::getDeleteFlag, 0)
//                        .set(StoreUser::getDeleteFlag, 1); // 1代表删除
//                int userUpdateResult = storeUserMapper.update(null, userUpdateWrapper);
//
//                if (userUpdateResult > 0) {
//                    log.info("用户只有一个子账号，已同时逻辑删除 store_user 记录: userId={}", userId);
//                } else {
//                    log.warn("逻辑删除 store_user 记录失败或记录不存在: userId={}", userId);
//                }
//            } else {
//                log.info("用户有多个子账号（count={}），仅删除 store_platform_user_role 记录，不删除 store_user 记录: userId={}", subAccountCount, userId);
//            }
//
//            return true;
//        } catch (Exception e) {
//            log.error("移除用户角色失败: userId={}, roleId={}, storeId={}", userId, roleId, storeId, e);
//            return false;
//        }
//    }


    @Override
    public boolean removeRole(Integer userId, Long roleId, Integer storeId) {
        if (userId == null || roleId == null || storeId == null) {
            log.error("参数不能为空: userId={}, roleId={}, storeId={}", userId, roleId, storeId);
            return false;
        }

        try {
            // 1. 先查询该用户在所有店铺下的子账号数量（未删除的）
            LambdaQueryWrapper<StorePlatformUserRole> countWrapper = new LambdaQueryWrapper<>();
            countWrapper.eq(StorePlatformUserRole::getUserId, userId)
                    .eq(StorePlatformUserRole::getDeleteFlag, 0);
            long subAccountCount = storePlatformUserRoleMapper.selectCount(countWrapper);

            log.info("用户在所有店铺下的子账号数量: userId={}, count={}", userId, subAccountCount);

            // 2. 逻辑删除 store_platform_user_role 表的记录
            LambdaUpdateWrapper<StorePlatformUserRole> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(StorePlatformUserRole::getUserId, userId)
                    .eq(StorePlatformUserRole::getRoleId, roleId)
                    .eq(StorePlatformUserRole::getStoreId, storeId)
                    .eq(StorePlatformUserRole::getDeleteFlag, 0)
                    .set(StorePlatformUserRole::getDeleteFlag, 1); // 1代表删除
            int updateResult = storePlatformUserRoleMapper.update(null, updateWrapper);

            if (updateResult <= 0) {
                log.error("逻辑删除 store_platform_user_role 记录失败: userId={}, roleId={}, storeId={}", userId, roleId, storeId);
                return false;
            }


            StoreUser storeUser = storeUserMapper.selectById(userId);
            if (storeUser != null && storeUser.getPhone() != null) {
                // 删除Redis中的token，key格式：storePlatform_手机号
                String tokenKey = "store_" + storeUser.getPhone();
                String existingToken = baseRedisService.getString(tokenKey);
                if (existingToken != null) {
                    baseRedisService.delete(tokenKey);
                    log.info("清除角色编辑后的用户token成功， userId={}, phone={}, tokenKey={}",
                             userId, storeUser.getPhone(), tokenKey);
                } else {
                    log.warn("用户token不存在或已过期， userId={}, phone={}, tokenKey={}",
                             userId, storeUser.getPhone(), tokenKey);
                }
            }

            // 3. 如果只是一个账号的子账号（删除前只有1个），则需要进一步判断是否为主账号，再决定是否同时逻辑删除 store_user 表
            if (subAccountCount == 1) {
                // 查询用户信息以判断是否为主账号

                if (storeUser != null) {
                    // 如果用户有 storeId 字段值，说明是主账号，不应删除
                    if (storeUser.getStoreId() != null && storeUser.getStoreId() > 0 || storeUser.getAccountType()==1) {
                        log.info("用户是主账号，不删除 store_user 记录: userId={}, storeId={}", userId, storeUser.getStoreId());
                    } else {
                        // 不是主账号，可以安全删除
                        LambdaUpdateWrapper<StoreUser> userUpdateWrapper = new LambdaUpdateWrapper<>();
                        userUpdateWrapper.eq(StoreUser::getId, userId)
                                .eq(StoreUser::getDeleteFlag, 0)
                                .set(StoreUser::getDeleteFlag, 1); // 1代表删除
                        int userUpdateResult = storeUserMapper.update(null, userUpdateWrapper);

                        if (userUpdateResult > 0) {
                            log.info("用户只有一个子账号且不是主账号，已同时逻辑删除 store_user 记录: userId={}", userId);
                        } else {
                            log.warn("逻辑删除 store_user 记录失败或记录不存在: userId={}", userId);
                        }
                    }
                } else {
                    log.warn("未找到用户信息: userId={}", userId);
                }
            } else {
                log.info("用户有多个子账号（count={}），仅删除 store_platform_user_role 记录，不删除 store_user 记录: userId={}", subAccountCount, userId);
            }

            return true;
        } catch (Exception e) {
            log.error("移除用户角色失败: userId={}, roleId={}, storeId={}", userId, roleId, storeId, e);
            return false;
        }
    }



    @Override
    public R<String> createAccountAndAssignRole(String phone, String accountName, Integer storeId, Long roleId) {
        if (phone == null || phone.isEmpty() || storeId == null || roleId == null) {
            log.error("参数不能为空: phone={}, storeId={}, roleId={}", phone, storeId, roleId);
            return R.fail("参数不能为空");
        }

        try {
            // 0. 校验当前店铺中是否已存在相同手机号或用户名的子账号
            // 先根据手机号查询用户
            LambdaQueryWrapper<StoreUser> checkUserWrapper = new LambdaQueryWrapper<>();
            checkUserWrapper.eq(StoreUser::getPhone, phone)
                    .eq(StoreUser::getDeleteFlag, 0);
            StoreUser checkUser = storeUserMapper.selectOne(checkUserWrapper);
            
            if (checkUser != null) {
                // 如果用户存在，检查该用户在当前店铺是否已有子账号记录
                LambdaQueryWrapper<StorePlatformUserRole> checkRoleWrapper = new LambdaQueryWrapper<>();
                checkRoleWrapper.eq(StorePlatformUserRole::getUserId, checkUser.getId())
                        .eq(StorePlatformUserRole::getStoreId, storeId)
                        .eq(StorePlatformUserRole::getDeleteFlag, 0);
                StorePlatformUserRole existingSubAccount = storePlatformUserRoleMapper.selectOne(checkRoleWrapper);
                
                if (existingSubAccount != null) {
                    log.error("该手机号在当前店铺已存在子账号，不支持创建: phone={}, storeId={}", phone, storeId);
                    return R.fail("当前手机号已经在该店铺存在请勿重复添加");
                }
            }
            
            // 如果提供了账号名称，检查当前店铺中是否已存在相同账号名称的子账号
            if (accountName != null && !accountName.trim().isEmpty()) {
                LambdaQueryWrapper<StorePlatformUserRole> checkAccountNameWrapper = new LambdaQueryWrapper<>();
                checkAccountNameWrapper.eq(StorePlatformUserRole::getAccountName, accountName)
                        .eq(StorePlatformUserRole::getStoreId, storeId)
                        .eq(StorePlatformUserRole::getDeleteFlag, 0);
                StorePlatformUserRole existingAccountName = storePlatformUserRoleMapper.selectOne(checkAccountNameWrapper);
                
                if (existingAccountName != null) {
                    log.error("该账号名称在当前店铺已存在子账号，不支持创建: accountName={}, storeId={}", accountName, storeId);
                    return R.fail("当前账号名称已在该店铺存在请勿重复添加");
                }
            }

            // 1. 根据手机号查询 store_user 表
            LambdaQueryWrapper<StoreUser> userQueryWrapper = new LambdaQueryWrapper<>();
            userQueryWrapper.eq(StoreUser::getPhone, phone);
            StoreUser storeUser = storeUserMapper.selectOne(userQueryWrapper);

            //校验添加子账号的时候如果是当前主账号的手机号，阻断
            if (storeUser != null && storeUser.getStoreId() != null) {
                int storeIdNew = storeUser.getStoreId();
                if (storeIdNew == storeId) {
                    log.error("该手机号为当前当前店铺手机号，请勿重复创建: phone={}, storeId={}", phone, storeId);
                    return R.fail("该手机号为当前当前店铺手机号，请勿重复创建");
                }
            }

            Integer userId;
            if (storeUser == null) {
                // 2. 如果没有数据，则插入一条数据
                StoreUser newUser = new StoreUser();
                newUser.setPhone(phone);
                newUser.setName(accountName != null ? accountName : phone);
//                newUser.setStoreId(storeId);
                newUser.setStatus(0); // 0:启用
                newUser.setDeleteFlag(0); // 0:未删除
                newUser.setMoney(0);
//                newUser.setPassType(0); // 0:初始密码
                newUser.setLogoutFlag(0); // 0:未注销
                newUser.setAccountType(2);
                newUser.setPassType(0);
                newUser.setPassword("");
                newUser.setNickName(accountName != null ? accountName : phone);
                newUser.setCreatedTime(new Date());
                
                int insertResult = storeUserMapper.insert(newUser);
                if (insertResult <= 0) {
                    log.error("插入 store_user 表失败: phone={}", phone);
                    return R.fail("创建子账号失败");
                }
                userId = newUser.getId();
                log.info("成功创建新用户: phone={}, userId={}", phone, userId);
            } else {
                userId = storeUser.getId();
                log.info("用户已存在: phone={}, userId={}", phone, userId);
            }

            // 3. 通过 store_id 和 user_id 查询 store_platform_user_role 表
            LambdaQueryWrapper<StorePlatformUserRole> roleQueryWrapper = new LambdaQueryWrapper<>();
            roleQueryWrapper.eq(StorePlatformUserRole::getUserId, userId)
                    .eq(StorePlatformUserRole::getStoreId, storeId)
                    .eq(StorePlatformUserRole::getRoleId, roleId);
            StorePlatformUserRole existingRole = storePlatformUserRoleMapper.selectOne(roleQueryWrapper);

            if (existingRole == null) {
                // 4. 如果没有数据，则插入数据
                StorePlatformUserRole userRole = new StorePlatformUserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRole.setStoreId(storeId);
                userRole.setDeleteFlag(0);
                userRole.setAccountName(accountName);
                userRole.setCreatedTime(new Date());
                
                boolean insertRoleResult = this.save(userRole);
                if (!insertRoleResult) {
                    log.error("插入 store_platform_user_role 表失败: userId={}, storeId={}, roleId={}", userId, storeId, roleId);
                    return R.fail("创建子账号失败");
                }
                log.info("成功分配角色: userId={}, storeId={}, roleId={}", userId, storeId, roleId);
            } else {
                log.info("用户角色关系已存在: userId={}, storeId={}, roleId={}", userId, storeId, roleId);
            }

            return R.success("创建子账号成功");
        } catch (Exception e) {
            log.error("创建账号并分配角色失败: phone={}, storeId={}, roleId={}", phone, storeId, roleId, e);
            return R.fail("创建账号并分配角色失败");
        }
    }

    @Override
    public List<SubAccountVo> querySubAccounts(Integer storeId, String accountName, String phone, String roleName) {
        if (storeId == null) {
            log.error("店铺ID不能为空");
            return new ArrayList<>();
        }

        try {
            // 查询子账号列表
            List<SubAccountVo> subAccountList = storePlatformUserRoleMapper.querySubAccounts(
                    storeId, accountName, phone, roleName);

            // 计算每个子账号的权限数量
            subAccountList.forEach(subAccount -> {
                if (subAccount.getRoleId() != null) {
                    List<Long> menuIds = storePlatformRoleMenuService.getMenuIdsByRoleId(subAccount.getRoleId());
                    subAccount.setPermissionCount(menuIds != null ? menuIds.size() : 0);
                } else {
                    subAccount.setPermissionCount(0);
                }
            });

            return subAccountList;
        } catch (Exception e) {
            log.error("查询子账号列表失败: storeId={}, accountName={}, phone={}, roleName={}", 
                    storeId, accountName, phone, roleName, e);
            return new ArrayList<>();
        }
    }

    @Override
    public SubAccountDetailVo getSubAccountDetail(Integer userId, Integer storeId , Long roleIdNew) {
        if (userId == null || storeId == null) {
            log.error("用户ID或店铺ID不能为空: userId={}, storeId={}", userId, storeId);
            return null;
        }

        try {
            SubAccountDetailVo detailVo = new SubAccountDetailVo();
            detailVo.setUserId(userId);

            // 1. 查询用户基本信息
            StoreUser storeUser = storeUserMapper.selectById(userId);
            if (storeUser == null) {
                log.error("用户不存在: userId={}", userId);
                return null;
            }
            
            // 设置账号名称（优先使用 name，否则使用 nick_name）
//            String accountName = storeUser.getName();
//            if (accountName == null || accountName.isEmpty()) {
//                accountName = storeUser.getNickName();
//            }
//            detailVo.setAccountName(accountName);
            detailVo.setPhone(storeUser.getPhone());

            // 2. 查询用户角色关联（根据userId和storeId查询）
            LambdaQueryWrapper<StorePlatformUserRole> userRoleQueryWrapper = new LambdaQueryWrapper<>();
            userRoleQueryWrapper.eq(StorePlatformUserRole::getUserId, userId)
                    .eq(StorePlatformUserRole::getRoleId, roleIdNew)
                    .eq(StorePlatformUserRole::getStoreId, storeId);
            StorePlatformUserRole userRole = storePlatformUserRoleMapper.selectOne(userRoleQueryWrapper);

            if (userRole != null && userRole.getRoleId() != null) {
                Long roleId = userRole.getRoleId();
                detailVo.setRoleId(roleId);
                detailVo.setAccountName(userRole.getAccountName());

                // 3. 查询角色信息
                StorePlatformRole role = storePlatformRoleMapper.selectById(roleId);
                if (role != null) {
                    detailVo.setRoleName(role.getRoleName());
                }

                // 4. 查询权限列表（菜单列表）
                List<Long> menuIds = storePlatformRoleMenuService.getMenuIdsByRoleId(roleId);
                if (menuIds != null && !menuIds.isEmpty()) {
                    LambdaQueryWrapper<StorePlatformMenu> menuQueryWrapper = new LambdaQueryWrapper<>();
                    menuQueryWrapper.in(StorePlatformMenu::getMenuId, menuIds);
                    menuQueryWrapper.eq(StorePlatformMenu::getDelFlag, "0");
                    menuQueryWrapper.eq(StorePlatformMenu::getStatus, "0");
                    menuQueryWrapper.orderByAsc(StorePlatformMenu::getMenuSort);
                    List<StorePlatformMenu> menus = storePlatformMenuMapper.selectList(menuQueryWrapper);

                    // 转换为权限项VO列表
                    List<PermissionItemVo> permissionList = menus.stream()
                            .map(menu -> {
                                PermissionItemVo permissionItem = new PermissionItemVo();
                                permissionItem.setPermissionId(menu.getMenuId());
                                permissionItem.setPermissionName(menu.getMenuName());
                                return permissionItem;
                            })
                            .collect(Collectors.toList());
                    detailVo.setPermissions(permissionList);
                } else {
                    detailVo.setPermissions(new ArrayList<>());
                }
            } else {
                // 如果没有角色，设置为空
                detailVo.setRoleId(null);
                detailVo.setRoleName(null);
                detailVo.setPermissions(new ArrayList<>());
            }

            return detailVo;
        } catch (Exception e) {
            log.error("查询子账号详情失败: userId={}, storeId={}", userId, storeId, e);
            return null;
        }
    }

//    @Override
//    public boolean batchDeleteSubAccounts(List<Integer> userIds, Integer storeId) {
//        if (userIds == null || userIds.isEmpty()) {
//            log.error("用户ID列表不能为空");
//            return false;
//        }
//        if (storeId == null) {
//            log.error("店铺ID不能为空");
//            return false;
//        }
//
//        try {
//            // 批量逻辑删除用户角色关联关系
//            LambdaUpdateWrapper<StorePlatformUserRole> updateWrapper = new LambdaUpdateWrapper<>();
//            updateWrapper.eq(StorePlatformUserRole::getStoreId, storeId)
//                    .in(StorePlatformUserRole::getUserId, userIds)
//                    .set(StorePlatformUserRole::getDeleteFlag, 1); // 1代表删除
//
//            int result = storePlatformUserRoleMapper.update(null, updateWrapper);
//            log.info("批量删除子账号成功: storeId={}, userIds={}, 删除数量={}", storeId, userIds, result);
//            return result > 0;
//        } catch (Exception e) {
//            log.error("批量删除子账号失败: storeId={}, userIds={}", storeId, userIds, e);
//            return false;
//        }
//    }


    @Override
    public boolean batchDeleteSubAccounts(List<Integer> userIds, Integer storeId) {
        if (userIds == null || userIds.isEmpty()) {
            log.error("用户ID列表不能为空");
            return false;
        }
        if (storeId == null) {
            log.error("店铺ID不能为空");
            return false;
        }

        try {
            for (Integer userId : userIds) {
                // 1. 先查询该用户在所有店铺下的子账号数量（未删除的）
                LambdaQueryWrapper<StorePlatformUserRole> countWrapper = new LambdaQueryWrapper<>();
                countWrapper.eq(StorePlatformUserRole::getUserId, userId)
                        .eq(StorePlatformUserRole::getDeleteFlag, 0);
                long subAccountCount = storePlatformUserRoleMapper.selectCount(countWrapper);

                log.info("用户在所有店铺下的子账号数量: userId={}, count={}", userId, subAccountCount);

                // 2. 逻辑删除 store_platform_user_role 表的记录（只删除当前店铺的记录）
                LambdaUpdateWrapper<StorePlatformUserRole> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(StorePlatformUserRole::getUserId, userId)
                        .eq(StorePlatformUserRole::getStoreId, storeId)
                        .eq(StorePlatformUserRole::getDeleteFlag, 0)
                        .set(StorePlatformUserRole::getDeleteFlag, 1); // 1代表删除

                int result = storePlatformUserRoleMapper.update(null, updateWrapper);

                if (result <= 0) {
                    log.warn("逻辑删除 store_platform_user_role 记录失败: userId={}, storeId={}", userId, storeId);
                    continue; // 继续处理下一个用户
                }

                StoreUser storeUser = storeUserMapper.selectById(userId);
                if (storeUser != null && storeUser.getPhone() != null) {
                    // 删除Redis中的token，key格式：storePlatform_手机号
                    String tokenKey = "store_" + storeUser.getPhone();
                    String existingToken = baseRedisService.getString(tokenKey);
                    if (existingToken != null) {
                        baseRedisService.delete(tokenKey);
                        log.info("清除角色编辑后的用户token成功 userId={}, phone={}, tokenKey={}",
                                 userId, storeUser.getPhone(), tokenKey);
                    } else {
                        log.warn("用户token不存在或已过期，userId={}, phone={}, tokenKey={}",
                                 userId, storeUser.getPhone(), tokenKey);
                    }
                }

                log.info("逻辑删除 store_platform_user_role 记录成功: userId={}, storeId={}, 删除数量={}", userId, storeId, result);

                // 3. 判断是否只有一个子账号，如果是则同时逻辑删除 store_user 表
                if (subAccountCount == 1) {

                    StoreUser user = storeUserMapper.selectById(userId);

                    if (user != null) {
                        // 如果用户有 storeId 字段值，说明是主账号，不应删除
                        if (user.getStoreId() != null && user.getStoreId() > 0) {
                            log.info("用户是主账号，不删除 store_user 记录: userId={}, storeId={}", userId, user.getStoreId());
                        } else {
                            // 不是主账号，可以安全删除
                            LambdaUpdateWrapper<StoreUser> userUpdateWrapper = new LambdaUpdateWrapper<>();
                            userUpdateWrapper.eq(StoreUser::getId, userId)
                                    .eq(StoreUser::getDeleteFlag, 0)
                                    .set(StoreUser::getDeleteFlag, 1); // 1代表删除
                            int userUpdateResult = storeUserMapper.update(null, userUpdateWrapper);

                            if (userUpdateResult > 0) {
                                log.info("用户只有一个子账号且不是主账号，已同时逻辑删除 store_user 记录: userId={}", userId);
                            } else {
                                log.warn("逻辑删除 store_user 记录失败或记录不存在: userId={}", userId);
                            }
                        }
                    } else {
                        log.warn("未找到用户信息: userId={}", userId);
                    }
                } else {
                    log.info("用户有多个子账号（count={}），仅删除 store_platform_user_role 记录，不删除 store_user 记录: userId={}", subAccountCount, userId);
                }
            }
            log.info("批量删除子账号完成: storeId={}, userIds={}", storeId, userIds);
            return true;
        } catch (Exception e) {
            log.error("批量删除子账号失败: storeId={}, userIds={}", storeId, userIds, e);
            return false;
        }
    }

    @Override
    public boolean updateSubAccount(Integer userId, String phone, String accountName, Integer storeId, Long roleId) {
        if (userId == null || storeId == null) {
            log.error("用户ID或店铺ID不能为空: userId={}, storeId={}", userId, storeId);
            return false;
        }

        try {
            // 1. 验证用户是否存在
            StoreUser storeUser = storeUserMapper.selectById(userId);
            if (storeUser == null || storeUser.getDeleteFlag() != 0) {
                log.error("用户不存在或已删除: userId={}", userId);
                return false;
            }

            // 2. 如果提供了手机号，更新手机号
            if (phone != null && !phone.trim().isEmpty()) {
                // 检查新手机号是否与其他用户重复（排除当前用户）
                LambdaQueryWrapper<StoreUser> phoneCheckWrapper = new LambdaQueryWrapper<>();
                phoneCheckWrapper.eq(StoreUser::getPhone, phone)
                        .ne(StoreUser::getId, userId)
                        .eq(StoreUser::getDeleteFlag, 0);
                StoreUser existingUser = storeUserMapper.selectOne(phoneCheckWrapper);
                
                if (existingUser != null) {
                    // 检查该手机号对应的用户是否在当前店铺已有子账号
                    LambdaQueryWrapper<StorePlatformUserRole> checkRoleWrapper = new LambdaQueryWrapper<>();
                    checkRoleWrapper.eq(StorePlatformUserRole::getUserId, existingUser.getId())
                            .eq(StorePlatformUserRole::getStoreId, storeId)
                            .eq(StorePlatformUserRole::getDeleteFlag, 0);
                    StorePlatformUserRole existingSubAccount = storePlatformUserRoleMapper.selectOne(checkRoleWrapper);
                    
                    if (existingSubAccount != null) {
                        log.error("该手机号在当前店铺已存在子账号，不支持更新: phone={}, storeId={}", phone, storeId);
                        return false;
                    }
                }

                // 更新用户手机号、姓名和昵称
                LambdaUpdateWrapper<StoreUser> userUpdateWrapper = new LambdaUpdateWrapper<>();
                userUpdateWrapper.eq(StoreUser::getId, userId)
                        .set(StoreUser::getPhone, phone);
                
                // 如果提供了账号名称，同时更新姓名和昵称；否则使用手机号作为姓名和昵称
                if (accountName != null && !accountName.trim().isEmpty()) {
                    userUpdateWrapper.set(StoreUser::getName, accountName)
                            .set(StoreUser::getNickName, accountName);
                } else {
                    userUpdateWrapper.set(StoreUser::getName, phone)
                            .set(StoreUser::getNickName, phone);
                }
                
                int userUpdateResult = storeUserMapper.update(null, userUpdateWrapper);
                if (userUpdateResult <= 0) {
                    log.error("更新用户手机号失败: userId={}, phone={}", userId, phone);
                    return false;
                }
                log.info("成功更新用户手机号: userId={}, phone={}", userId, phone);
            }

            // 3. 查询当前用户的角色关联记录
            // 如果提供了角色ID，通过userId + storeId + roleId查询；否则通过userId + storeId查询第一个
            StorePlatformUserRole existingUserRole = null;
            Long targetRoleId = roleId; // 用于确定要查询/更新的角色ID
            
            if (roleId != null) {
                // 如果提供了角色ID，先查询是否存在该角色关联记录
                LambdaQueryWrapper<StorePlatformUserRole> userRoleQueryWrapper = new LambdaQueryWrapper<>();
                userRoleQueryWrapper.eq(StorePlatformUserRole::getUserId, userId)
                        .eq(StorePlatformUserRole::getStoreId, storeId)
                        .eq(StorePlatformUserRole::getRoleId, roleId)
                        .eq(StorePlatformUserRole::getDeleteFlag, 0);
                existingUserRole = storePlatformUserRoleMapper.selectOne(userRoleQueryWrapper);
            }
            
            // 如果通过roleId没找到，或者没有提供roleId，则查询第一个记录
            if (existingUserRole == null) {
                LambdaQueryWrapper<StorePlatformUserRole> userRoleQueryWrapper = new LambdaQueryWrapper<>();
                userRoleQueryWrapper.eq(StorePlatformUserRole::getUserId, userId)
                        .eq(StorePlatformUserRole::getStoreId, storeId)
                        .eq(StorePlatformUserRole::getDeleteFlag, 0)
                        .last("LIMIT 1");
                existingUserRole = storePlatformUserRoleMapper.selectOne(userRoleQueryWrapper);
                
                // 如果没有提供roleId，使用现有记录的roleId
                if (targetRoleId == null && existingUserRole != null) {
                    targetRoleId = existingUserRole.getRoleId();
                }
            }

            // 4. 更新或创建角色关联记录
            if (existingUserRole == null) {
                // 如果不存在角色关联记录，需要创建一条（至少需要角色ID）
                if (roleId == null) {
                    log.error("用户在该店铺没有角色关联记录，且未提供角色ID，无法创建: userId={}, storeId={}", userId, storeId);
                    return false;
                }
                
                // 检查账号名称是否重复
                if (accountName != null && !accountName.trim().isEmpty()) {
                    LambdaQueryWrapper<StorePlatformUserRole> accountNameCheckWrapper = new LambdaQueryWrapper<>();
                    accountNameCheckWrapper.eq(StorePlatformUserRole::getAccountName, accountName)
                            .eq(StorePlatformUserRole::getStoreId, storeId)
                            .eq(StorePlatformUserRole::getDeleteFlag, 0);
                    StorePlatformUserRole existingAccountName = storePlatformUserRoleMapper.selectOne(accountNameCheckWrapper);
                    
                    if (existingAccountName != null) {
                        log.error("该账号名称在当前店铺已存在，不支持创建: accountName={}, storeId={}", accountName, storeId);
                        return false;
                    }
                }
                
                // 创建新的角色关联记录
                StorePlatformUserRole newUserRole = new StorePlatformUserRole();
                newUserRole.setUserId(userId);
                newUserRole.setRoleId(roleId);
                newUserRole.setStoreId(storeId);
                newUserRole.setDeleteFlag(0);
                newUserRole.setAccountName(accountName != null ? accountName : (storeUser.getNickName() != null ? storeUser.getNickName() : storeUser.getPhone()));
                newUserRole.setCreatedTime(new Date());
                
                boolean insertResult = this.save(newUserRole);
                if (!insertResult) {
                    log.error("创建角色关联记录失败: userId={}, storeId={}, roleId={}", userId, storeId, roleId);
                    return false;
                }
                log.info("成功创建角色关联记录: userId={}, storeId={}, roleId={}", userId, storeId, roleId);
            } else {
                // 如果提供了账号名称，更新账号名称（需要检查是否重复）
                if (accountName != null && !accountName.trim().isEmpty()) {
                    // 检查新账号名称是否在当前店铺已存在（排除当前记录）
                    LambdaQueryWrapper<StorePlatformUserRole> accountNameCheckWrapper = new LambdaQueryWrapper<>();
                    accountNameCheckWrapper.eq(StorePlatformUserRole::getAccountName, accountName)
                            .eq(StorePlatformUserRole::getStoreId, storeId)
                            .eq(StorePlatformUserRole::getDeleteFlag, 0)
                            .ne(StorePlatformUserRole::getId, existingUserRole.getId());
                    StorePlatformUserRole existingAccountName = storePlatformUserRoleMapper.selectOne(accountNameCheckWrapper);
                    
                    if (existingAccountName != null) {
                        log.error("该账号名称在当前店铺已存在，不支持更新: accountName={}, storeId={}", accountName, storeId);
                        return false;
                    }

                    // 更新账号名称（只更新当前记录）
                    LambdaUpdateWrapper<StorePlatformUserRole> accountNameUpdateWrapper = new LambdaUpdateWrapper<>();
                    accountNameUpdateWrapper.eq(StorePlatformUserRole::getId, existingUserRole.getId())
                            .set(StorePlatformUserRole::getAccountName, accountName);
                    
                    int accountNameUpdateResult = storePlatformUserRoleMapper.update(null, accountNameUpdateWrapper);
                    if (accountNameUpdateResult <= 0) {
                        log.error("更新账号名称失败: userId={}, accountName={}", userId, accountName);
                        return false;
                    }
                    log.info("成功更新账号名称: userId={}, accountName={}", userId, accountName);
                }

                // 如果提供了角色ID且与现有不同，更新角色信息
                if (roleId != null && !roleId.equals(existingUserRole.getRoleId())) {
                    // 检查新角色是否已存在相同的关联记录
                    LambdaQueryWrapper<StorePlatformUserRole> roleCheckWrapper = new LambdaQueryWrapper<>();
                    roleCheckWrapper.eq(StorePlatformUserRole::getUserId, userId)
                            .eq(StorePlatformUserRole::getStoreId, storeId)
                            .eq(StorePlatformUserRole::getRoleId, roleId)
                            .eq(StorePlatformUserRole::getDeleteFlag, 0);
                    StorePlatformUserRole existingRoleRecord = storePlatformUserRoleMapper.selectOne(roleCheckWrapper);
                    
                    if (existingRoleRecord != null && !existingRoleRecord.getId().equals(existingUserRole.getId())) {
                        log.error("用户在该店铺已存在该角色关联记录: userId={}, storeId={}, roleId={}", userId, storeId, roleId);
                        return false;
                    }

                    // 更新角色ID（只更新当前记录）
                    LambdaUpdateWrapper<StorePlatformUserRole> roleUpdateWrapper = new LambdaUpdateWrapper<>();
                    roleUpdateWrapper.eq(StorePlatformUserRole::getId, existingUserRole.getId())
                            .set(StorePlatformUserRole::getRoleId, roleId);
                    
                    int roleUpdateResult = storePlatformUserRoleMapper.update(null, roleUpdateWrapper);
                    if (roleUpdateResult <= 0) {
                        log.error("更新角色ID失败: userId={}, roleId={}", userId, roleId);
                        return false;
                    }
                    log.info("成功更新角色ID: userId={}, oldRoleId={}, newRoleId={}", userId, existingUserRole.getRoleId(), roleId);
                }
            }

            return true;
        } catch (Exception e) {
            log.error("更新子账号信息失败: userId={}, phone={}, accountName={}, storeId={}, roleId={}", 
                    userId, phone, accountName, storeId, roleId, e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSubAccountNew(Integer userId, String phone, String accountName, Integer storeId, Long roleId,Integer id) {
        try {
            // 先查询要删除的记录，保存信息以便回滚
            StorePlatformUserRole oldUserRole = storePlatformUserRoleMapper.selectById(id);
            if (oldUserRole == null) {
                log.error("要删除的角色关联记录不存在: id={}", id);
                return false;
            }
            
            // 逻辑删除记录
            LambdaUpdateWrapper<StorePlatformUserRole> deleteWrapper = new LambdaUpdateWrapper<>();
            deleteWrapper.eq(StorePlatformUserRole::getUserId, userId)
                    .eq(StorePlatformUserRole::getId, id)
                    .set(StorePlatformUserRole::getDeleteFlag, 1);
            int deleteResult = storePlatformUserRoleMapper.update(null, deleteWrapper);
            
            if (deleteResult > 0) {
                log.info("成功删除角色关联记录: userId={}, storeId={}, roleId={}", userId, storeId, roleId);
                
                // 尝试创建新账号并分配角色
                R<String> createResult = createAccountAndAssignRole(phone, accountName, storeId, roleId);
                
                if (createResult.getCode() == 200) {
                    log.info("成功创建新账号并分配角色: phone={}, storeId={}, roleId={}", phone, storeId, roleId);
                    return true;
                } else {
                    // 创建失败，执行回滚：恢复删除的记录
                    log.warn("创建新账号失败，执行回滚操作: phone={}, storeId={}, roleId={}, error={}", 
                            phone, storeId, roleId, createResult.getMsg());
                    
                    int rollbackResult = storePlatformUserRoleMapper.rollbackDeleteById(Long.valueOf(id));
                    
                    if (rollbackResult > 0) {
                        log.info("成功回滚，恢复角色关联记录: id={}, userId={}, storeId={}, roleId={}", 
                                id, userId, storeId, roleId);
                    } else {
                        log.error("回滚失败，无法恢复角色关联记录: id={}, userId={}, storeId={}, roleId={}", 
                                id, userId, storeId, roleId);
                    }
                    return false;
                }
            } else {
                log.error("删除角色关联记录失败: userId={}, id={}", userId, id);
                return false;
            }
        } catch (Exception e) {
            log.error("更新子账号失败，尝试回滚: userId={}, phone={}, accountName={}, storeId={}, roleId={}, id={}", 
                    userId, phone, accountName, storeId, roleId, id, e);
            
            // 异常情况下也尝试回滚
            try {
                int rollbackResult = storePlatformUserRoleMapper.rollbackDeleteById(Long.valueOf(id));
                if (rollbackResult > 0) {
                    log.info("异常情况下成功回滚，恢复角色关联记录: id={}", id);
                }
            } catch (Exception rollbackException) {
                log.error("回滚操作也失败: id={}", id, rollbackException);
            }
            
            return false;
        }
    }

    @Override
    public IPage<SubAccountListVo> queryAllSubAccounts(Integer pageNum, Integer pageSize, String accountId, String phone, Integer status) {
        try {
            // 创建分页对象
            Page<SubAccountListVo> page = new Page<>(pageNum, pageSize);
            // 执行分页查询
            IPage<SubAccountListVo> result = storePlatformUserRoleMapper.queryAllSubAccounts(page, accountId, phone, status);
            log.info("查询所有子账号信息成功，共{}条记录，当前页{}条，查询条件：accountId={}, phone={}, status={}", 
                    result.getTotal(), result.getRecords() != null ? result.getRecords().size() : 0, accountId, phone, status);
            return result;
        } catch (Exception e) {
            log.error("查询所有子账号信息失败，查询条件：accountId={}, phone={}, status={}", accountId, phone, status, e);
            // 返回空分页对象
            Page<SubAccountListVo> emptyPage = new Page<>(pageNum, pageSize);
            emptyPage.setTotal(0);
            emptyPage.setRecords(new ArrayList<>());
            return emptyPage;
        }
    }

    @Override
    public boolean disableSubAccount(Long id, Integer status) {
        if (id == null) {
            log.error("子账号关联记录ID不能为空");
            return false;
        }

        if (status == null || (status != 0 && status != 1)) {
            log.error("状态参数必须为0（启用）或1（禁用）: status={}", status);
            return false;
        }

        try {
            // 1. 先查询记录是否存在
            StorePlatformUserRole userRole = storePlatformUserRoleMapper.selectById(id);
            if (userRole == null) {
                log.error("子账号关联记录不存在: id={}", id);
                return false;
            }

            // 2. 检查当前状态是否已经是目标状态
            if (userRole.getStatus() != null && userRole.getStatus().equals(status)) {
                String statusText = status == 0 ? "启用" : "禁用";
                log.warn("子账号已经是{}状态: id={}", statusText, id);
                return true; // 已经是目标状态，返回成功
            }

            // 3. 根据传入的 status 值更新状态
            LambdaUpdateWrapper<StorePlatformUserRole> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(StorePlatformUserRole::getId, id)
                    .eq(StorePlatformUserRole::getDeleteFlag, 0) // 只更新未删除的记录
                    .set(StorePlatformUserRole::getStatus, status);
            int updateResult = storePlatformUserRoleMapper.update(null, updateWrapper);
            // 根据传入的 status 值更新
            StoreUser storeUser = storeUserMapper.selectById(userRole.getUserId());
            if (storeUser != null && storeUser.getPhone() != null) {
                // 删除Redis中的token，key格式：storePlatform_手机号
                String tokenKey = "store_" + storeUser.getPhone();
                String existingToken = baseRedisService.getString(tokenKey);
                if (existingToken != null) {
                    baseRedisService.delete(tokenKey);
                    log.info("清除角色编辑后的用户token成功 userId={}, phone={}, tokenKey={}",
                            userRole.getUserId(), storeUser.getPhone(), tokenKey);
                } else {
                    log.warn("用户token不存在或已过期，userId={}, phone={}, tokenKey={}",
                            userRole.getUserId(), storeUser.getPhone(), tokenKey);
                }
            }

            if (updateResult > 0) {
                String statusText = status == 0 ? "启用" : "禁用";
                log.info("成功{}子账号: id={}, userId={}, storeId={}, roleId={}, status={}", 
                        statusText, id, userRole.getUserId(), userRole.getStoreId(), userRole.getRoleId(), status);
                return true;
            } else {
                String statusText = status == 0 ? "启用" : "禁用";
                log.error("{}子账号失败: id={}", statusText, id);
                return false;
            }
        } catch (Exception e) {
            log.error("更新子账号状态异常: id={}, status={}", id, status, e);
            return false;
        }
    }
}

