package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.StorePlatformRole;
import shop.alien.entity.store.StorePlatformUserRole;
import shop.alien.entity.store.StoreUser;
import shop.alien.entity.store.vo.SubAccountStoreListVo;
import shop.alien.mapper.StorePlatformUserRoleMapper;
import shop.alien.mapper.StoreUserMapper;
import shop.alien.mapper.SubAccountStoreMapper;
import shop.alien.store.service.SubAccountStoreService;

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

/**
 * 子账号关联门店服务实现类
 *
 * @author system
 * @since 2025-01-01
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SubAccountStoreServiceImpl implements SubAccountStoreService {

    private final SubAccountStoreMapper subAccountStoreMapper;

    private final StorePlatformUserRoleMapper storePlatformUserRoleMapper;

    private final StoreUserMapper storeUserMapper;

    @Override
    public List<SubAccountStoreListVo> getSubAccountStoreList(Integer userId) {
        log.info("SubAccountStoreServiceImpl.getSubAccountStoreList?userId={}", userId);
        List<SubAccountStoreListVo> storeList = new ArrayList<>();
        if (userId == null) {
            log.warn("用户ID为空");
            return new ArrayList<>();
        }
        List<StorePlatformUserRole> list = new ArrayList<>();
        StoreUser storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>()
                .eq(StoreUser :: getId, userId));
        if(storeUser!=null){
            if(storeUser.getAccountType() != 1){
                list = storePlatformUserRoleMapper.selectList(new LambdaQueryWrapper<StorePlatformUserRole>()
                        .eq(StorePlatformUserRole :: getUserId, userId));
            }
        }
        if(list.size()>0 || storeUser.getStoreId() != null){
            //查出主子账号所有门店信息回显
            storeList = subAccountStoreMapper.selectSubAccountStoreListByUserIdTwo(userId);
        }else{
            //主账号没有门店 子账号有门店 查出主账号 账号信息和子账号门店信息组合回显
            storeList = subAccountStoreMapper.selectSubAccountStoreListByUserId(userId);
        }
        log.info("查询子账号关联门店列表完成 - 用户ID: {}, 门店数量: {}", userId, storeList != null ? storeList.size() : 0);
        return storeList;
    }
}
