package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.LifeBlacklistVo;
import shop.alien.mapper.*;
import shop.alien.store.config.BaseRedisService;
import shop.alien.store.service.LifeBlacklistService;
import shop.alien.util.common.JwtUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 黑名单
 * 服务实现类
 * </p>
 *
 * @author ssk
 * @since 2025-04-30
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LifeBlacklistServiceImpl extends ServiceImpl<LifeBlacklistMapper, LifeBlacklist> implements LifeBlacklistService {

    private final LifeBlacklistMapper lifeBlacklistMapper;
    private final StoreUserMapper storeUserMapper;
    private final LifeUserMapper lifeUserMapper;
    private final StoreImgMapper storeImgMapper;
    private final BaseRedisService baseRedisService;
    private final StoreInfoMapper storeInfoMapper;

    @Override
    public int blackList(LifeBlacklist lifeBlacklist) {
        LambdaUpdateWrapper<LifeBlacklist> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(LifeBlacklist::getBlockerId, lifeBlacklist.getBlockerId());
        wrapper.eq(LifeBlacklist::getBlockedId, lifeBlacklist.getBlockedId());
        wrapper.eq(LifeBlacklist::getBlockedType, lifeBlacklist.getBlockedType());
        wrapper.eq(LifeBlacklist::getBlockerType, lifeBlacklist.getBlockerType());
        LifeBlacklist lifeBlacklist1 = lifeBlacklistMapper.selectOne(wrapper);
        if (lifeBlacklist1 != null) {
            return 2;
        }

        // 获取拉黑方phoneId
        String blockerPhoneId = "";
        if ("1".equals(lifeBlacklist.getBlockerType())) {
            StoreUser storeUser = storeUserMapper.selectById(lifeBlacklist.getBlockerId());
            if (storeUser != null) blockerPhoneId = "store_" + storeUser.getPhone();
        } else {
            LifeUser lifeUser = lifeUserMapper.selectById(lifeBlacklist.getBlockerId());
            if (lifeUser != null) blockerPhoneId = "user_" + lifeUser.getUserPhone();
        }

        // 获取被拉黑方phoneId
        String blockedPhoneId = "";
        if ("1".equals(lifeBlacklist.getBlockedType())) {
            StoreUser storeUser = storeUserMapper.selectById(lifeBlacklist.getBlockedId());
            if (storeUser != null) blockedPhoneId = "store_" + storeUser.getPhone();
        } else {
            LifeUser lifeUser = lifeUserMapper.selectById(lifeBlacklist.getBlockedId());
            if (lifeUser != null) blockedPhoneId = "user_" + lifeUser.getUserPhone();
        }
        lifeBlacklist.setBlockerPhoneId(blockerPhoneId);
        lifeBlacklist.setBlockedPhoneId(blockedPhoneId);
        int num = lifeBlacklistMapper.insert(lifeBlacklist);
        if (baseRedisService.hasKey("blackList_" + blockedPhoneId)) {
            baseRedisService.setListRight("blackList_" + blockedPhoneId, blockerPhoneId);
        } else {
            baseRedisService.setSaveOrOverwriteScriptList("blackList_" + blockedPhoneId, Arrays.asList(blockerPhoneId));
        }
        return num;
    }

    @Override
    public List<LifeBlacklistVo> blackListByUserId(String userType, String userId, Integer type) {
        List<LifeBlacklistVo> lifeBlacklistVos = new ArrayList<>();
        LambdaUpdateWrapper<LifeBlacklist> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(LifeBlacklist::getBlockerId, userId);
        wrapper.eq(LifeBlacklist::getBlockerType, userType);
        if (1 == type) {
            wrapper.eq(LifeBlacklist::getBlockedType, "1");
        } else if (2 == type) {
            wrapper.eq(LifeBlacklist::getBlockedType, "2");
        }
        List<LifeBlacklist> lifeBlacklists = lifeBlacklistMapper.selectList(wrapper);

        for (LifeBlacklist lifeBlacklist : lifeBlacklists) {
            LifeBlacklistVo vo = new LifeBlacklistVo();
            BeanUtils.copyProperties(lifeBlacklist, vo);
            lifeBlacklistVos.add(vo);
        }

        lifeBlacklistVos.forEach(lifeBlacklist -> {
            if (lifeBlacklist.getBlockedId() != null && lifeBlacklist.getBlockedType() != null) {
                if ("1".equals(lifeBlacklist.getBlockedType())) {
                    StoreUser storeUser = storeUserMapper.selectById(lifeBlacklist.getBlockedId());
                    StoreInfo storeInfo = storeInfoMapper.selectById(storeUser.getStoreId());
                    lifeBlacklist.setStoreInfo(storeInfo);
                    StoreImg storeImg = null;
                    if (storeUser != null) {
                        lifeBlacklist.setName(storeUser.getName());
                        lifeBlacklist.setPhoneId(storeUser.getPhone());
                        lifeBlacklist.setUserImage(storeUser.getHeadImg());
                        storeImg = storeImgMapper.selectOne(new LambdaUpdateWrapper<StoreImg>().eq(StoreImg::getStoreId, storeUser.getStoreId()).eq(StoreImg::getImgType, 10));
                        if (storeImg != null) {
                            lifeBlacklist.setUserImage(storeImg.getImgUrl());
                        }
                    }
                } else {
                    LifeUser lifeUser = lifeUserMapper.selectById(lifeBlacklist.getBlockedId());
                    if (lifeUser != null) {
                        lifeBlacklist.setName(lifeUser.getUserName());
                        lifeBlacklist.setUserImage(lifeUser.getUserImage());
                        lifeBlacklist.setPhoneId(lifeUser.getUserPhone());
                    }

                }
            }
        });
        return lifeBlacklistVos;
    }

    @Override
    public Boolean isBlackListUser(LifeBlacklist lifeBlacklist) {
        LambdaUpdateWrapper<LifeBlacklist> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(LifeBlacklist::getBlockerId, lifeBlacklist.getBlockerId());
        wrapper.eq(LifeBlacklist::getBlockedId, lifeBlacklist.getBlockedId());
        wrapper.eq(LifeBlacklist::getBlockedType, lifeBlacklist.getBlockedType());
        wrapper.eq(LifeBlacklist::getBlockerType, lifeBlacklist.getBlockerType());
        lifeBlacklist = lifeBlacklistMapper.selectOne(wrapper);
        return lifeBlacklist != null;
    }

    @Override
    public int cancelBlacklist(LifeBlacklist lifeBlacklist) {
        LifeBlacklist black = lifeBlacklistMapper.selectById(lifeBlacklist.getId());
        if (black == null) return 0;
//        LambdaUpdateWrapper<LifeBlacklist> wrapper = new LambdaUpdateWrapper<>();
//        wrapper.eq(LifeBlacklist::getBlockedId, lifeBlacklist.getBlockedId());
//        wrapper.eq(LifeBlacklist::getBlockerId, lifeBlacklist.getBlockerId());
//        wrapper.eq(LifeBlacklist::getBlockedType, lifeBlacklist.getBlockedType());
//        wrapper.eq(LifeBlacklist::getBlockerType, lifeBlacklist.getBlockerType());
        if (baseRedisService.hasKey("blackList_" + black.getBlockedPhoneId())) {
            baseRedisService.removeAllOccurrences("blackList_" + black.getBlockedPhoneId(), black.getBlockerPhoneId());
        }
        return lifeBlacklistMapper.deleteById(black.getId());
    }

    @Override
    public boolean hasBlackList(String otherSidePhoneId) throws Exception {
        try {
            String phoneId = Objects.requireNonNull(JwtUtil.getCurrentUserInfo()).getString("userType") + "_" + JwtUtil.getCurrentUserInfo().getString("phone");
            LambdaQueryWrapper<LifeBlacklist> wrapper = new LambdaQueryWrapper<>();
            wrapper.apply("((blocker_phone_id='" + otherSidePhoneId + "' and blocked_phone_id='" + phoneId + "')" +
                    " or (blocker_phone_id='" + phoneId + "' and blocked_phone_id='" + otherSidePhoneId + "'))");
            return lifeBlacklistMapper.selectCount(wrapper) > 0;
        } catch (Exception e) {
            log.error("LifeBlacklistServiceImpl.hasBlackList() error={}", e.getMessage());
            throw new Exception(e);
        }
    }


}
