package shop.alien.store.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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 org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import shop.alien.entity.second.SecondGoods;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.LifePinglunVo;
import shop.alien.mapper.*;
import shop.alien.mapper.second.SecondGoodsMapper;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 评论
 */
@Service
@RequiredArgsConstructor
public class LifeCommentService {

    private final LifeCommentMapper lifeCommentMapper;

    private final StoreCommentMapper storeCommentMapper;

    private final LifeUserDynamicsMapper lifeUserDynamicsMapper;

    private final LifeUserMapper lifeUserMapper;

    private final LifeActivityMapper lifeActivityMapper;

    private final LifeLikeRecordMapper lifeLikeRecordMapper;

    private final StoreMenuMapper storeRecommendMapper;

    private final StoreClockInMapper storeClockInMapper;

    private final LifeNoticeMapper lifeNoticeMapper;

    private final SecondGoodsMapper secondGoodsMapper;

    public int like(String userId, String huifuId, String type) {
        LambdaUpdateWrapper<LifeLikeRecord> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(LifeLikeRecord::getType, type);
        updateWrapper.eq(LifeLikeRecord::getDianzanId, userId);
        updateWrapper.eq(LifeLikeRecord::getHuifuId, huifuId);
        updateWrapper.eq(LifeLikeRecord::getDeleteFlag, 0);
        List<LifeLikeRecord> record = lifeLikeRecordMapper.selectList(updateWrapper);
        if (CollectionUtils.isEmpty(record)) {
            LifeLikeRecord lifeLikeRecord = new LifeLikeRecord();
            lifeLikeRecord.setCreatedTime(new Date());
            lifeLikeRecord.setHuifuId(huifuId);
            lifeLikeRecord.setDianzanId(userId);
            lifeLikeRecord.setType(type);
            lifeLikeRecordMapper.insert(lifeLikeRecord);

            if ("1".equals(type)) {
                LambdaUpdateWrapper<StoreComment> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.eq(StoreComment::getId, huifuId);
                lambdaUpdateWrapper.setSql("like_count = like_count + 1");
                return storeCommentMapper.update(null, lambdaUpdateWrapper);
            } else if ("2".equals(type)) {
                LambdaUpdateWrapper<LifeUserDynamics> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.eq(LifeUserDynamics::getId, huifuId);
                lambdaUpdateWrapper.setSql("dianzan_count = dianzan_count + 1");
                int num = lifeUserDynamicsMapper.update(null, lambdaUpdateWrapper);
                if (num > 0) insertNotice(userId, huifuId, type);
                return num;
            } else if ("3".equals(type)) {
                LambdaUpdateWrapper<LifeActivity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.eq(LifeActivity::getId, huifuId);
                lambdaUpdateWrapper.setSql("dianzan_count = dianzan_count + 1");
                return lifeActivityMapper.update(null, lambdaUpdateWrapper);
            } else if ("4".equals(type)) {
                LambdaUpdateWrapper<StoreMenu> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.eq(StoreMenu::getId, huifuId);
                lambdaUpdateWrapper.setSql("like_count = like_count + 1");
                return storeRecommendMapper.update(null, lambdaUpdateWrapper);
            } else if ("5".equals(type)) {
                LambdaUpdateWrapper<StoreClockIn> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.eq(StoreClockIn::getId, huifuId);
                lambdaUpdateWrapper.setSql("like_count = like_count + 1");
                return storeClockInMapper.update(null, lambdaUpdateWrapper);
            } else if ("6".equals(type)) {
                LambdaUpdateWrapper<SecondGoods> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.eq(SecondGoods::getId, huifuId);
                lambdaUpdateWrapper.setSql("like_count = like_count + 1");
                return secondGoodsMapper.update(null, lambdaUpdateWrapper);
            }
        }
        return 0;
    }

    /**
     * 发送通知
     */
    private void insertNotice(String userId, String huifuId, String type) {
        if ("2".equals(type)) {
            LifeNotice lifeNotice = new LifeNotice();
            lifeNotice.setSenderId(userId);
            lifeNotice.setBusinessId(Integer.parseInt(huifuId));
            lifeNotice.setNoticeType(0);
            lifeNotice.setTitle("动态通知");
            lifeNotice.setContext("点赞了你的动态");
            LifeUserDynamics lifeUserDynamics = lifeUserDynamicsMapper.selectById(Integer.parseInt(huifuId));
            lifeNotice.setReceiverId(lifeUserDynamics == null ? null : lifeUserDynamics.getPhoneId());
            lifeNoticeMapper.insert(lifeNotice);
        }
    }

    public int cancelLike(String userId, String huifuId, String type) {
        LambdaQueryWrapper<LifeLikeRecord> lifeLikeRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        lifeLikeRecordLambdaQueryWrapper.eq(LifeLikeRecord::getDianzanId, userId);
        lifeLikeRecordLambdaQueryWrapper.eq(LifeLikeRecord::getHuifuId, huifuId);
        lifeLikeRecordLambdaQueryWrapper.eq(LifeLikeRecord::getType, type);
        lifeLikeRecordLambdaQueryWrapper.eq(LifeLikeRecord::getDeleteFlag, 0);
        List<LifeLikeRecord> record = lifeLikeRecordMapper.selectList(lifeLikeRecordLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(record)) {
            LambdaUpdateWrapper<LifeLikeRecord> lifeLikeRecordLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lifeLikeRecordLambdaUpdateWrapper.eq(LifeLikeRecord::getHuifuId, huifuId);
            lifeLikeRecordLambdaUpdateWrapper.eq(LifeLikeRecord::getDianzanId, userId);
            lifeLikeRecordLambdaUpdateWrapper.eq(LifeLikeRecord::getType, type);
            lifeLikeRecordMapper.delete(lifeLikeRecordLambdaUpdateWrapper);

        if ("1".equals(type)) {
            LambdaUpdateWrapper<StoreComment> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(StoreComment::getId, huifuId).gt(StoreComment::getLikeCount, 0);
            lambdaUpdateWrapper.setSql("like_count = like_count - 1");
            return storeCommentMapper.update(null, lambdaUpdateWrapper);
        } else if ("2".equals(type)) {
            LambdaUpdateWrapper<LifeUserDynamics> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(LifeUserDynamics::getId, huifuId).gt(LifeUserDynamics::getDianzanCount, 0);
            lambdaUpdateWrapper.setSql("dianzan_count = dianzan_count - 1");
            return lifeUserDynamicsMapper.update(null, lambdaUpdateWrapper);
        } else if ("3".equals(type)) {
            LambdaUpdateWrapper<LifeActivity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(LifeActivity::getId, huifuId).gt(LifeActivity::getDianzanCount, 0);
            lambdaUpdateWrapper.setSql("dianzan_count = dianzan_count - 1");
            return lifeActivityMapper.update(null, lambdaUpdateWrapper);
        } else if ("4".equals(type)) {
            LambdaUpdateWrapper<StoreMenu> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(StoreMenu::getId, huifuId).gt(StoreMenu::getLikeCount, 0);
            lambdaUpdateWrapper.setSql("like_count = like_count - 1");
            return storeRecommendMapper.update(null, lambdaUpdateWrapper);
        } else if ("5".equals(type)) {
            LambdaUpdateWrapper<StoreClockIn> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(StoreClockIn::getId, huifuId).gt(StoreClockIn::getLikeCount, 0);
            lambdaUpdateWrapper.setSql("like_count = like_count - 1");
            return storeClockInMapper.update(null, lambdaUpdateWrapper);
        }else if ("6".equals(type)) {
            LambdaUpdateWrapper<SecondGoods> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(SecondGoods::getId, huifuId).gt(SecondGoods::getLikeCount, 0);
            lambdaUpdateWrapper.setSql("like_count = like_count - 1");
            return secondGoodsMapper.update(null, lambdaUpdateWrapper);
        }
    }
        return 0;
}

    public int addOrUpdateStore(LifeComment store) {
        if (StringUtils.isEmpty(store.getId())) {
            Date nowDate = new Date(System.currentTimeMillis());
            store.setPinglunTime(new java.sql.Timestamp(nowDate.getTime()));
            if (StringUtils.isEmpty(store.getHuifuId())) {
                store.setHuifuId(store.getId());
            }
            return lifeCommentMapper.insert(store);
        } else {
            return lifeCommentMapper.updateById(store);
        }
    }

    public Map<String, List<LifePinglunVo>> getAppealByStoreId(String userId, String storeId, String idHuifu, String pinglunLevel, String pinglunDays, String pinglunLeibie) {
        LambdaUpdateWrapper<LifeComment> wrapper = new LambdaUpdateWrapper<>();
        if (userId != null && !userId.isEmpty()) {
            wrapper.eq(LifeComment::getUserId, userId);
        }
        if (storeId != null && !storeId.isEmpty()) {
            wrapper.eq(LifeComment::getStoreId, storeId);
        }
        if (pinglunLevel != null && !pinglunLevel.isEmpty()) {
            List<String> list = Arrays.stream(pinglunLevel.split(","))
                    .map(String::trim)
                    .collect(Collectors.toList());
            wrapper.in(LifeComment::getPinglunLevel, list);
        }
        if (pinglunLeibie != null && !pinglunLeibie.isEmpty()) {
            wrapper.eq(LifeComment::getPinglunLeibie, pinglunLeibie);
        }
        wrapper.orderByDesc(LifeComment::getPinglunTime);
        List<LifeComment> lifePingluns = lifeCommentMapper.selectList(wrapper);
        List<LifePinglunVo> lifePinglunVos = new ArrayList<>();
        if (!ObjectUtils.isEmpty(lifePingluns)) {
            for (LifeComment pl : lifePingluns) {
                LifePinglunVo vo = new LifePinglunVo();
                BeanUtils.copyProperties(pl, vo);
                if (!StringUtils.isEmpty(vo.getUserId())) {
                    LifeUser user = lifeUserMapper.selectById(vo.getUserId());
                    if (!ObjectUtils.isEmpty(user)) {
                        vo.setHeadImage(user.getUserImage());
                    }
                    LambdaUpdateWrapper<LifeLikeRecord> recordLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    recordLambdaUpdateWrapper.eq(LifeLikeRecord::getHuifuId, vo.getId());
                    recordLambdaUpdateWrapper.eq(LifeLikeRecord::getDianzanId, vo.getUserId());
                    List<LifeLikeRecord> records = lifeLikeRecordMapper.selectList(recordLambdaUpdateWrapper);
                    if (ObjectUtils.isEmpty(records)) {
                        vo.setDianzanStatus("0");
                    } else {
                        vo.setDianzanStatus("1");
                    }
                }
                lifePinglunVos.add(vo);
            }
        }
        Map<String, List<LifePinglunVo>> listMap;
        listMap = lifePinglunVos.stream().filter(item -> !StringUtils.isEmpty(item.getHuifuId())).collect(Collectors.groupingBy(LifePinglunVo::getHuifuId));
        if (!StringUtils.isEmpty(idHuifu) && !CollectionUtils.isEmpty(listMap)) {
            listMap.forEach((key, value) -> {
                value.sort(Comparator.comparing(LifePinglunVo::getPinglunTime));
            });
            if (idHuifu.equals("1")) {
                listMap = listMap.entrySet().stream()
                        .filter(entry -> entry.getValue().size() > 1)
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
            } else if (idHuifu.equals("0")) {
                listMap = listMap.entrySet().stream()
                        .filter(entry -> entry.getValue().size() == 1)
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
            }
        }
        if (!StringUtils.isEmpty(pinglunDays) && !CollectionUtils.isEmpty(lifePingluns)) {
            Integer days = Integer.valueOf(pinglunDays);
            Iterator<Map.Entry<String, List<LifePinglunVo>>> iterator = listMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, List<LifePinglunVo>> entry = iterator.next();
                List<LifePinglunVo> lifePinglunList = entry.getValue();
                if (!lifePinglunList.isEmpty()) {
                    Date firstPinglunTime = lifePinglunList.get(0).getPinglunTime();
                    LocalDate firstLocalDate = firstPinglunTime.toInstant()
                            .atZone(ZoneId.systemDefault())
                            .toLocalDate();
                    LocalDate currentDate = LocalDate.now();
                    long daysBetween = ChronoUnit.DAYS.between(firstLocalDate, currentDate);
                    if (daysBetween > days) {
                        iterator.remove();
                    }
                }
            }
        }
        return listMap;
    }

    /**
     * 分页查询商家端顾客评论
     *
     * @param pageNum     页数
     * @param pageSize    页容
     * @param storeId     店铺id
     * @param isReply     是否回复,0:全部;1:已回复;2:未回复;
     * @param commentType 评论类别,0:全部;1:好评;2:中评;3:差评;
     * @param date        查询日期
     * @return IPage<LifeComment>
     */
    public IPage<LifeComment> getStoreComment(Integer pageNum, Integer pageSize, Integer storeId, Integer isReply, Integer commentType, String date) {
        IPage<LifeComment> iPage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<LifeComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null != storeId, LifeComment::getStoreId, storeId);
        wrapper.gt(LifeComment::getPinglunTime, date);
        return lifeCommentMapper.selectPage(iPage, wrapper);
    }
}
