package shop.alien.store.service;

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.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import shop.alien.entity.store.LifeActivity;
import shop.alien.entity.store.LifeComment;
import shop.alien.entity.store.LifeLikeRecord;
import shop.alien.entity.store.LifeUser;
import shop.alien.entity.store.vo.LifeActivityVo;
import shop.alien.entity.store.vo.LifePinglunVo;
import shop.alien.mapper.LifeActivityMapper;
import shop.alien.mapper.LifeCommentMapper;
import shop.alien.mapper.LifeLikeRecordMapper;
import shop.alien.mapper.LifeUserMapper;
import shop.alien.store.util.StoreLikeRecordIdentityHelper;
import shop.alien.store.util.StoreLikeRecordIdentityHelper.StoreLikerScope;
import shop.alien.util.common.ListToPage;

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

/**
 * 活动
 */
@Service
@RequiredArgsConstructor
public class LifeActivityService {

    private final LifeActivityMapper lifeActivityMapper;

    private final LifeCommentMapper lifeCommentMapper;

    private final LifeUserMapper lifeUserMapper;

    private final LifeLikeRecordMapper lifeLikeRecordMapper;

    private final StoreLikeRecordIdentityHelper lifeLikeIdentityHelper;

    private final WebAuditService webAuditService;

    public int save(LifeActivity lifeActivity) {
        lifeActivity.setCreatedTime(new Date());
        int insert = lifeActivityMapper.insert(lifeActivity);
        // 获取插入后的主键
        Long id = Long.valueOf(lifeActivity.getId());

        // 添加审核锚点
//        WebAudit webAudit = new WebAudit();
//        webAudit.setId(id.toString());  // 使用正确的主键值
//        webAudit.setType("5");
//
//        Integer auditResult = webAuditService.platformAuditRefundTrack(webAudit);
//
//        if (auditResult <= 0) {
//            return auditResult;
//        }
        return insert;
    }

    public IPage<LifeActivityVo> getActivityList(int page, int size, String phoneId) {
        // 查询活动列表
        IPage<LifeActivity> storePage = new Page<>(page, size);

        QueryWrapper<LifeActivity> queryWrapper = new QueryWrapper<>();
        IPage<LifeActivity> activityList = lifeActivityMapper.selectPage(storePage, queryWrapper);

        // 查询点赞数据
        StoreLikerScope likerScope = lifeLikeIdentityHelper.resolveFromDianzanId(phoneId);
        LambdaQueryWrapper<LifeLikeRecord> likeWrapper = new LambdaQueryWrapper<>();
        likeWrapper.eq(LifeLikeRecord::getType, "3")
                .eq(LifeLikeRecord::getDeleteFlag, "0");
        lifeLikeIdentityHelper.applyLikerFilter(likeWrapper, likerScope);
        List<LifeLikeRecord> likeRecordList = lifeLikeRecordMapper.selectList(likeWrapper);

        List<LifeActivityVo> activityVoList = new ArrayList<>();
        activityList.getRecords().forEach(activity -> {
            LifeActivityVo vo = new LifeActivityVo();
            BeanUtils.copyProperties(activity, vo);
            if (likeRecordList.stream().anyMatch(item -> item.getHuifuId().equals(activity.getId()))) {
                vo.setIsLike("1");
            } else {
                vo.setIsLike("0");
            }
            activityVoList.add(vo);
        });

        IPage<LifeActivityVo> result = new Page<>();
        result.setRecords(activityVoList);
        result.setPages(activityList.getPages());
        result.setTotal(activityList.getTotal());
        result.setSize(activityList.getSize());
        result.setCurrent(activityList.getCurrent());

        return result;
    }

    public Map<String, Object> getActivityById(String id, String currentId, int page, int size) {
        Map<String, Object> map = new HashMap<>();
        LifeActivity lifeActivity = lifeActivityMapper.selectById(id);
        LifeActivityVo hdVo = new LifeActivityVo();
        BeanUtils.copyProperties(lifeActivity, hdVo);
        StoreLikerScope currentLikerScope = lifeLikeIdentityHelper.resolveFromDianzanId(currentId);
        LambdaQueryWrapper<LifeLikeRecord> recordQueryWrapper = new LambdaQueryWrapper<>();
        recordQueryWrapper.eq(LifeLikeRecord::getHuifuId, lifeActivity.getId());
        lifeLikeIdentityHelper.applyLikerFilter(recordQueryWrapper, currentLikerScope);
        List<LifeLikeRecord> dianzanRecords = lifeLikeRecordMapper.selectList(recordQueryWrapper);
        if (!CollectionUtils.isEmpty(dianzanRecords)) {
            hdVo.setIsLike("1");
        } else {
            hdVo.setIsLike("0");
        }
        LambdaUpdateWrapper<LifeComment> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(LifeComment::getDongtaiShequId, lifeActivity.getId());
        wrapper.eq(LifeComment::getPinglunLeibie, "2");
        List<LifeComment> lifeComments = lifeCommentMapper.selectList(wrapper);
        List<LifePinglunVo> plVoList = new ArrayList<>();
        for (LifeComment pl : lifeComments) {
            LifePinglunVo vo = new LifePinglunVo();
            BeanUtils.copyProperties(pl, vo);
            LifeUser user = lifeUserMapper.selectById(pl.getUserId());
            if (user != null) {
                vo.setHeadImage(user.getUserImage());
                vo.setUserAdress(user.getAddress());
            }
            recordQueryWrapper = new LambdaQueryWrapper<>();
            recordQueryWrapper.eq(LifeLikeRecord::getHuifuId, pl.getId());
            lifeLikeIdentityHelper.applyLikerFilter(recordQueryWrapper, currentLikerScope);
            dianzanRecords = lifeLikeRecordMapper.selectList(recordQueryWrapper);
            if (!CollectionUtils.isEmpty(dianzanRecords)) {
                vo.setDianzanStatus("1");
            } else {
                vo.setDianzanStatus("0");
            }
            plVoList.add(vo);
        }
        List<Map<String, Object>> mapResult = new ArrayList<>();
        if (!CollectionUtils.isEmpty(plVoList)) {
            Map<String, List<LifePinglunVo>> mapPingluns = plVoList.stream().filter(item -> StringUtils.isNotEmpty(item.getHuifuId())).collect(Collectors.groupingBy(LifePinglunVo::getHuifuId));
            map.put("pinglunCount", lifeComments.size());
            for (Map.Entry<String, List<LifePinglunVo>> entry : mapPingluns.entrySet()) {
                String year = entry.getKey();
                List<LifePinglunVo> records = entry.getValue();
                Map<String, Object> newMap = new HashMap<>();
                newMap.put("huifuId", year);
                newMap.put("records", records);
                mapResult.add(newMap);
            }
        }
        map.put("pingluns", ListToPage.setPage(mapResult, page, size));
        map.put("huodong", hdVo);
        return map;
    }

    public Map<String, Object> getActivityByActivityId(String id, String currentId) {
        Map<String, Object> map = new HashMap<>();
        LifeActivity lifeActivity = lifeActivityMapper.selectById(id);
        LifeActivityVo hdVo = new LifeActivityVo();
        BeanUtils.copyProperties(lifeActivity, hdVo);
        StoreLikerScope currentLikerScope = lifeLikeIdentityHelper.resolveFromDianzanId(currentId);
        LambdaQueryWrapper<LifeLikeRecord> recordQueryWrapper = new LambdaQueryWrapper<>();
        recordQueryWrapper.eq(LifeLikeRecord::getHuifuId, lifeActivity.getId());
        lifeLikeIdentityHelper.applyLikerFilter(recordQueryWrapper, currentLikerScope);
        List<LifeLikeRecord> dianzanRecords = lifeLikeRecordMapper.selectList(recordQueryWrapper);
        if (!CollectionUtils.isEmpty(dianzanRecords)) {
            hdVo.setIsLike("1");
        } else {
            hdVo.setIsLike("0");
        }
        LambdaUpdateWrapper<LifeComment> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(LifeComment::getDongtaiShequId, lifeActivity.getId());
        wrapper.eq(LifeComment::getPinglunLeibie, "2");
        List<LifeComment> lifeComments = lifeCommentMapper.selectList(wrapper);
        List<LifePinglunVo> plVoList = new ArrayList<>();
        for (LifeComment pl : lifeComments) {
            LifePinglunVo vo = new LifePinglunVo();
            BeanUtils.copyProperties(pl, vo);
            LifeUser user = lifeUserMapper.selectById(pl.getUserId());
            if (user != null) {
                vo.setHeadImage(user.getUserImage());
                vo.setUserAdress(user.getAddress());
            }
            recordQueryWrapper = new LambdaQueryWrapper<>();
            recordQueryWrapper.eq(LifeLikeRecord::getHuifuId, pl.getId());
            lifeLikeIdentityHelper.applyLikerFilter(recordQueryWrapper, currentLikerScope);
            dianzanRecords = lifeLikeRecordMapper.selectList(recordQueryWrapper);
            if (!CollectionUtils.isEmpty(dianzanRecords)) {
                vo.setDianzanStatus("1");
            } else {
                vo.setDianzanStatus("0");
            }
            plVoList.add(vo);
        }
        List<Map<String, Object>> mapResult = new ArrayList<>();
        if (!CollectionUtils.isEmpty(plVoList)) {
            Map<String, List<LifePinglunVo>> mapPingluns = plVoList.stream().filter(item -> StringUtils.isNotEmpty(item.getHuifuId())).collect(Collectors.groupingBy(LifePinglunVo::getHuifuId));
            map.put("pinglunCount", lifeComments.size());
            for (Map.Entry<String, List<LifePinglunVo>> entry : mapPingluns.entrySet()) {
                String year = entry.getKey();
                List<LifePinglunVo> records = entry.getValue();
                Map<String, Object> newMap = new HashMap<>();
                newMap.put("huifuId", year);
                newMap.put("records", records);
                mapResult.add(newMap);
            }
        }
        map.put("huodong", hdVo);
        return map;
    }
}
