package shop.alien.store.service.impl;

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.stereotype.Service;
import shop.alien.entity.store.LifeFans;
import shop.alien.entity.store.LifeUser;
import shop.alien.mapper.LifeFansMapper;
import shop.alien.mapper.LifeUserMapper;
import shop.alien.mapper.StoreUserMapper;
import shop.alien.store.service.LifeFansService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 粉丝/会员表 服务实现类
 * </p>
 *
 * @author lhb
 * @since 2025-05-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LifeFansServiceImpl extends ServiceImpl<LifeFansMapper, LifeFans> implements LifeFansService {

    private final LifeUserMapper lifeUserMapper;

    private final StoreUserMapper storeUserMapper;
    private final LifeFansMapper lifeFansMapper;

    @Override
    public List<Map<String, Object>> getFriends(String phone) {
        // 查询我关注的人
        LambdaQueryWrapper<LifeFans> myFollowWrapper = new LambdaQueryWrapper<>();
        myFollowWrapper.eq(LifeFans::getFansId, phone)
                .eq(LifeFans::getDeleteFlag, 0);
        List<LifeFans> myFollows = this.list(myFollowWrapper);


        List<String> phones = new ArrayList<>();
        for (LifeFans myFollow : myFollows) {
            // 查询是否关注我
            LambdaQueryWrapper<LifeFans> fansQueryWrapper = new LambdaQueryWrapper<>();
            myFollowWrapper.eq(LifeFans::getFansId, myFollow.getFollowedId());
            List<LifeFans> fansList = this.list(fansQueryWrapper);
            List<String> myFollowIds = fansList.stream()
                    .map(LifeFans::getFollowedId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            if (myFollowIds.contains(phone)) {
                phones.add(myFollow.getFollowedId());
            }
        }

        // 查询好友用户信息
        if (phones.isEmpty()) {
            return Collections.emptyList();
        }
        List<String> userPhone = phones.stream()
                .filter(id -> id.startsWith("user"))
                .map(id -> {
                    int underscoreIndex = id.indexOf('_');
                    return underscoreIndex != -1 ?
                            id.substring(underscoreIndex + 1) :
                            id;
                })
                .collect(Collectors.toList());
        List<String> storePhone = phones.stream()
                .filter(id -> id.startsWith("store"))
                .map(id -> {
                    int underscoreIndex = id.indexOf('_');
                    return underscoreIndex != -1 ?
                            id.substring(underscoreIndex + 1) :
                            id;
                })
                .collect(Collectors.toList());
        List<Map<String, Object>> userList = new ArrayList<>();

        // 获取互相关注的用户
        if (!userPhone.isEmpty()) {
            LambdaQueryWrapper<LifeUser> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.in(LifeUser::getUserPhone, userPhone)
                    .eq(LifeUser::getDeleteFlag, 0);
            List<LifeUser> lifeUsers = lifeUserMapper.selectList(userWrapper);
            for (LifeUser lifeUser : lifeUsers) {
                Map<String, Object> user = new HashMap<>();
                user.put("userName", lifeUser.getUserName());
                user.put("userPhone", lifeUser.getUserPhone());
                user.put("id", lifeUser.getId());
                user.put("userImage", lifeUser.getUserImage());
                userList.add(user);
            }
        }

        // 获取互相关注的商家
        if (!storePhone.isEmpty()) {
            String userPhones = "'" + String.join("','", storePhone) + "'";
            List<Map<String, Object>> storeUsers = storeUserMapper.selectStore(userPhones);
            for (Map<String, Object> storeUser : storeUsers) {
                Map<String, Object> user = new HashMap<>();
                user.put("userName", storeUser.get("storeName"));
                user.put("userPhone", storeUser.get("phone"));
                user.put("id", storeUser.get("id"));
                user.put("userImage", storeUser.get("imgUrl"));
                userList.add(user);
            }
        }
        return userList;
    }

    /**
     * 查询是否关注
     *
     * @param userId         用户id
     * @param followedUserId 关注人id
     * @return boolean
     */
    @Override
    public boolean getFollowStatus(Integer userId, Integer followedUserId) {
        LifeUser lifeUser1 = lifeUserMapper.selectOne(new LambdaQueryWrapper<LifeUser>().eq(LifeUser::getId, userId));
        if (null == lifeUser1) {
            log.error("用户1不存在: {}", userId);
            return false;
        }
        LifeUser lifeUser2 = lifeUserMapper.selectOne(new LambdaQueryWrapper<LifeUser>().eq(LifeUser::getId, followedUserId));
        if (null == lifeUser2) {
            log.error("用户2不存在: {}", followedUserId);
            return false;
        }
        LambdaQueryWrapper<LifeFans> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LifeFans::getFansId, "user_" + lifeUser1.getUserPhone())
                .eq(LifeFans::getFollowedId, "user_" + lifeUser2.getUserPhone());
        return !lifeFansMapper.selectList(wrapper).isEmpty();
    }
}
