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 shop.alien.util.type.LifeFansIdentityQuery;
import shop.alien.util.type.TypeUtil;

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;

    private final TypeUtil typeUtil;

    @Override
    public List<Map<String, Object>> getFriends(String phone) {
        LambdaQueryWrapper<LifeFans> myFollowWrapper = new LambdaQueryWrapper<>();
        LifeFansIdentityQuery.applyFansSide(myFollowWrapper, LifeFansIdentityQuery.resolve(phone, typeUtil));
        myFollowWrapper.eq(LifeFans::getDeleteFlag, 0);
        List<LifeFans> myFollows = this.list(myFollowWrapper);

        List<String> phones = new ArrayList<>();
        for (LifeFans myFollow : myFollows) {
            LambdaQueryWrapper<LifeFans> fansQueryWrapper = new LambdaQueryWrapper<>();
            LifeFansIdentityQuery.applyFansSide(fansQueryWrapper,
                    LifeFansIdentityQuery.resolve(myFollow.getFollowedId(), typeUtil));
            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;
    }

    @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<>();
        LifeFansIdentityQuery.applyFansSide(wrapper,
                LifeFansIdentityQuery.resolve("user_" + lifeUser1.getUserPhone(), typeUtil));
        LifeFansIdentityQuery.applyFollowedSide(wrapper,
                LifeFansIdentityQuery.resolve("user_" + lifeUser2.getUserPhone(), typeUtil));
        return !lifeFansMapper.selectList(wrapper).isEmpty();
    }
}
