package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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 org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.StoreClockInVo;
import shop.alien.mapper.*;
import shop.alien.store.service.StoreClockInService;
import shop.alien.store.service.StoreCommentService;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 店铺打卡 服务实现类
 * </p>
 *
 * @author ssk
 * @since 2025-05-15
 */
@Service
@RequiredArgsConstructor
public class StoreClockInServiceImpl extends ServiceImpl<StoreClockInMapper, StoreClockIn> implements StoreClockInService {

    private final StoreClockInMapper storeClockInMapper;

    private final LifeUserMapper lifeUserMapper;

    private final LifeFansMapper lifeFansMapper;

    private final LifeLikeRecordMapper lifeLikeRecordMapper;

    private final StoreCommentService storeCommentService;

    private final LifeCollectMapper lifeCollectMapper;

    @Override
    public StoreClockIn addStoreClockIn(StoreClockIn storeClockIn) {
        LifeUser user = lifeUserMapper.selectById(storeClockIn.getUserId());
        storeClockIn.setPhoneId("user_" + user.getUserPhone());
        storeClockInMapper.insert(storeClockIn);
        return storeClockIn;
    }

    @Override
    public IPage<StoreClockInVo> getStoreClockInList(Integer userId, int page, int size, String phoneId, int mySelf,Integer storeId) {
        IPage<StoreClockIn> iPage = new Page<>(page, size);
        // 查询我的点赞
        LambdaQueryWrapper<LifeLikeRecord> likeWrapper = new LambdaQueryWrapper<>();
        likeWrapper.eq(LifeLikeRecord::getDianzanId, phoneId);
        likeWrapper.eq(LifeLikeRecord::getType, "5");
        List<LifeLikeRecord> lifeLikeList = lifeLikeRecordMapper.selectList(likeWrapper);
        List<String> likeList = lifeLikeList.stream().map(LifeLikeRecord::getHuifuId).collect(Collectors.toList());


        if(StringUtils.isNotBlank(String.valueOf(storeId)) && !String.valueOf(storeId).equals("null")){
            IPage<StoreClockInVo> storeClockInIPage1 = storeClockInMapper.getStoreClockInList(iPage, new QueryWrapper<StoreClockIn>()
                    .eq("clock.store_id", storeId)
                    .eq("clock.delete_flag", 0)
                    .eq("user.delete_flag", 0)
                    .eq("store.delete_flag", 0)
                    .isNotNull(0 == mySelf, "clock.img_url")
                    .and(wrapper1 ->
                            wrapper1.eq("clock.permission", 1)
                                    .or(wSub ->
                                            wSub.eq("clock.permission", 2)
                                                    .eq("clock.user_id", userId)
                                    ))
                    .orderByDesc("created_time"));
            storeClockInIPage1.getRecords().forEach(vo -> {
                if (likeList.contains(String.valueOf(vo.getId()))) {
                    vo.setIsLike("1");
                } else {
                    vo.setIsLike("0");
                }
            });
            return storeClockInIPage1;
        }
        QueryWrapper<StoreClockIn> wrapper = new QueryWrapper<>();
        wrapper.eq(1 == mySelf, "clock.user_id", userId);
        wrapper.isNotNull(0 == mySelf, "clock.img_url");
        wrapper.eq("clock.delete_flag", 0);
        wrapper.eq("user.delete_flag", 0);
        wrapper.eq("store.delete_flag", 0);
        wrapper.and(wrapper1 ->
                wrapper1.eq("clock.permission", 1)
                        .or(wSub ->
                                wSub.eq("clock.permission", 2)
                                        .eq("clock.user_id", userId)
                        )
        );
        wrapper.orderByDesc("clock.created_time");

        IPage<StoreClockInVo> storeClockInIPage = storeClockInMapper.getStoreClockInList(iPage, wrapper);

        // 查询我的关注
        LambdaQueryWrapper<LifeFans> lifeFansWrapper = new LambdaQueryWrapper<>();
        lifeFansWrapper.eq(LifeFans::getFansId, phoneId);
        List<LifeFans> lifeFansList = lifeFansMapper.selectList(lifeFansWrapper);
        List<String> followList = lifeFansList.stream().map(LifeFans::getFollowedId).collect(Collectors.toList());

        // 查询我的粉丝
        lifeFansWrapper = new LambdaQueryWrapper<>();
        lifeFansWrapper.eq(LifeFans::getFollowedId, phoneId);
        lifeFansList = lifeFansMapper.selectList(lifeFansWrapper);
        List<String> fansList = lifeFansList.stream().map(LifeFans::getFansId).collect(Collectors.toList());



        // 查询我的收藏
        LambdaQueryWrapper<LifeCollect> collectWrapper = new LambdaQueryWrapper<>();
        collectWrapper.eq(LifeCollect::getUserId, String.valueOf(userId));
        List<LifeCollect> lifeCollectList = lifeCollectMapper.selectList(collectWrapper);
        List<String> collectList = lifeCollectList.stream().map(LifeCollect::getStoreId).collect(Collectors.toList());


        storeClockInIPage.getRecords().forEach(vo -> {
            if (followList.contains(vo.getPhoneId())) {
                vo.setIsFollowThis("1");
            } else {
                vo.setIsFollowThis("0");
            }
            if (fansList.contains(vo.getPhoneId())) {
                vo.setIsFollowMe("1");
            } else {
                vo.setIsFollowMe("0");
            }
            if (likeList.contains(String.valueOf(vo.getId()))) {
                vo.setIsLike("1");
            } else {
                vo.setIsLike("0");
            }
            if (collectList.contains(String.valueOf(vo.getStoreId()))) {
                vo.setIsCollect("1");
            } else {
                vo.setIsCollect("0");
            }

//            // 该用户的打卡记录
//            LambdaQueryWrapper<StoreClockIn> clockInWrapper = new LambdaQueryWrapper<>();
//            clockInWrapper.eq(StoreClockIn::getUserId, vo.getUserId());
//            List<StoreClockIn> clockInList = storeClockInMapper.selectList(clockInWrapper);
//
//            Set<Integer> clockInSet = clockInList.stream().map(StoreClockIn::getStoreId).collect(Collectors.toSet());
//            // 该用户今天打卡记录
//            Set<Integer> clockInTodaySet = clockInList.stream().filter(item -> item.getCreatedTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().equals(LocalDate.now())).map(StoreClockIn::getStoreId).collect(Collectors.toSet());
//
//            // 在该店铺的打卡次数
//            Map<Integer, Long> clockInStoreNumMap = clockInList.stream().collect(Collectors.groupingBy(StoreClockIn::getStoreId, Collectors.counting()));
//
//            // 该用户打卡的所有店铺次数（一个店铺只算一次）
//            int clockInNum = (int) clockInList.stream().map(StoreClockIn::getStoreId).distinct().count();
//
//            // 是否在该店铺打过卡
//            if (clockInSet.contains(vo.getStoreId())){
//                vo.setClockInStore("1");
//            } else {
//                vo.setClockInStore("0");
//            }
//            // 今天是否在该店铺打过卡
//            if (clockInTodaySet.contains(vo.getStoreId())){
//                vo.setClockInStoreToday("1");
//            } else {
//                vo.setClockInStoreToday("0");
//            }
//            // 在该店铺打卡次数clockInStoreNum
//            vo.setClockInStoreNum(clockInStoreNumMap.get(vo.getStoreId()));
//            // 打卡次数
//            vo.setClockInNum(clockInNum);
            vo.setCommentCount(Integer.parseInt(storeCommentService.getCommitCountAndScore(vo.getId(), 4, vo.getStoreId(),null,null).get("commitCount").toString()));
        });


        return storeClockInIPage;
    }

    @Override
    public int deleteClockIn(Integer id) {
        return storeClockInMapper.deleteById(id);
    }

    @Override
    public int setPermission(int userId, Integer id, int permission) {
        LambdaUpdateWrapper<StoreClockIn> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(StoreClockIn::getPermission, permission);
        wrapper.eq(StoreClockIn::getUserId, userId);
        wrapper.eq(null != id, StoreClockIn::getId, id);
        return storeClockInMapper.update(null, wrapper);
    }

    @Override
    public int setImg(int id, String img) {
        LambdaUpdateWrapper<StoreClockIn> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(StoreClockIn::getImgUrl, img);
        wrapper.eq(StoreClockIn::getId, id);
        return storeClockInMapper.update(null, wrapper);
    }

    /**
     * 获取门店打卡次数
     *
     * @return list
     */
    @Override
    public List<Map<Integer, Integer>> getStoreClockInCount() {
        return storeClockInMapper.getStoreClockInCount();
    }

    /**
     * 获取所有店铺打卡次数（有图片并且设置为可见的）
     *
     * @return map
     */
    @Override
    public List<Map<Integer, Integer>> getStoreClockInWithCanLookCount() {
        return storeClockInMapper.getStoreClockInWithCanLookCount();
    }
}
