package com.ruoyi.brewery.service.impl;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import com.ruoyi.bar.domain.WyBarIcon;
import com.ruoyi.bar.domain.WyBarIconLog;
import com.ruoyi.bar.service.IWyBarIconLogService;
import com.ruoyi.bar.service.IWyBarIconService;
import com.ruoyi.brewery.domain.WyBeer;
import com.ruoyi.brewery.domain.WyBeerReviewLike;
import com.ruoyi.brewery.domain.WyBrewery;
import com.ruoyi.brewery.service.*;
import com.ruoyi.common.constant.CoinObtainType;
import com.ruoyi.common.core.domain.entity.WyBeerReviewScore;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.brewery.mapper.WyBeerReviewMapper;
import com.ruoyi.brewery.domain.WyBeerReview;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 酒评Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-21
 */
@Service
public class WyBeerReviewServiceImpl implements IWyBeerReviewService {
    @Resource
    private WyBeerReviewMapper wyBeerReviewMapper;
    @Resource
    private IWyBeerService wyBeerService;
    @Resource
    private IWyBreweryService wyBreweryService;
    @Resource
    private IWyBarIconService wyBarIconService;
    @Resource
    private IWyBarIconLogService wyBarIconLogService;
    @Autowired
    private IWyBeerReviewLikeService wyBeerReviewLikeService;
    @Autowired
    private IWyBeerReviewReplyService wyBeerReviewReplyService;
    /**
     * 查询酒评
     *
     * @param id 酒评主键
     * @return 酒评
     */
    @Override
    public WyBeerReview selectWyBeerReviewById(Long id) {
        return wyBeerReviewMapper.selectWyBeerReviewById(id);
    }

    @Override
    public int setWyBeerReviewTop(Long id) {
        final WyBeerReview wyBeerReview = selectWyBeerReviewById(id);
        if (wyBeerReview == null) {
            throw new RuntimeException("酒评不存在");
        }
        final WyBeerReview query = new WyBeerReview();
        query.setBeerId(wyBeerReview.getBeerId());
        query.setIsTop(1);
        final List<WyBeerReview> wyBeerReviews = wyBeerReviewMapper.selectWyBeerReviewList(query);
        wyBeerReviews.forEach(beerReview -> {
            beerReview.setIsTop(0);
            wyBeerReviewMapper.updateWyBeerReview(beerReview);
        });
        wyBeerReview.setIsTop(1);
        return wyBeerReviewMapper.updateWyBeerReview(wyBeerReview);
    }

    @Override
    public int cancelWyBeerReviewTop(Long id) {
        final WyBeerReview wyBeerReview = selectWyBeerReviewById(id);
        if (wyBeerReview == null) {
            throw new RuntimeException("酒评不存在");
        }
        wyBeerReview.setIsTop(0);
        return wyBeerReviewMapper.updateWyBeerReview(wyBeerReview);
    }

    @Override
    public WyBeerReview selectWyBeerReviewByBeerIdTop1(Long beerId){
        return wyBeerReviewMapper.selectWyBeerReviewByBeerIdTop1(beerId);
    }

    @Override
    public WyBeerReview selectWyBeerReviewByBeerIdAndCustomerId(Long beerId, Long customerId) {
        return wyBeerReviewMapper.selectWyBeerReviewByBeerIdAndCustomerId(beerId, customerId);
    }

    /**
     * 查询酒评列表
     *
     * @param wyBeerReview 酒评
     * @return 酒评
     */
    @Override
    public List<WyBeerReview> selectWyBeerReviewList(WyBeerReview wyBeerReview) {
        final List<WyBeerReview> wyBeerReviews = wyBeerReviewMapper.selectWyBeerReviewList(wyBeerReview);
//        final List<WyBeerReview> wyBeerReviews = wyBeerReviewMapper.selectWyBeerReviewLists(wyBeerReview);
        wyBeerReviews.forEach(beerReview -> {
            if (beerReview.getAnonymous()) {
                beerReview.setUserName("匿名用户");
            }
            if (beerReview.getUserName() == null || beerReview.getUserName().isEmpty()) {
                beerReview.setUserName("匿名用户");
            }
        });
        return wyBeerReviews;
    }

    @Override
    public List<WyBeerReview> selectWyBeerReviewListWithLike(WyBeerReview wyBeerReview, Long userId) {
        final List<WyBeerReview> wyBeerReviews = wyBeerReviewMapper.selectWyBeerReviewList(wyBeerReview);
        wyBeerReviews.forEach(beerReview -> {
            if (beerReview.getAnonymous()) {
                beerReview.setUserName("匿名用户");
            }
            if (beerReview.getUserName() == null || beerReview.getUserName().isEmpty()) {
                beerReview.setUserName("匿名用户");
            }
            final WyBeerReviewLike wyBeerReviewLike = wyBeerReviewLikeService.selectWyBeerReviewLikeByReviewIdAndCustomerId(beerReview.getId(),
                    userId);
            if (wyBeerReviewLike != null) {
                beerReview.setReviewLike(wyBeerReviewLike);
            }
        });
        return wyBeerReviews;
    }

    @Override
    public WyBeerReviewScore selectWyBeerReviewScoreList(Long beerId) {
        return wyBeerReviewMapper.selectWyBeerReviewScoreList(beerId);
    }

    @Override
    public List<WyBeerReviewScore> selectWyBeerReviewScoreAll() {
        return wyBeerReviewMapper.selectWyBeerReviewScoreAll();
    }

    /**
     * 新增酒评
     *
     * @param wyBeerReview 酒评
     * @return 结果
     */
    @Transactional
    @Override
    public int insertWyBeerReview(WyBeerReview wyBeerReview) {
        final WyBeerReview wyBeerReviews = wyBeerReviewMapper.selectWyBeerReviewByBeerIdAndCustomerId(wyBeerReview.getBeerId(), wyBeerReview.getUserId());
        if (wyBeerReviews != null) {
            throw new RuntimeException("该用户已对该酒进行过评价");
        }
        wyBeerReview.setCreateTime(DateUtils.getNowDate());
        final int i = wyBeerReviewMapper.insertWyBeerReview(wyBeerReview);
        // 更新酒评分数
        if (i > 0) {
            final WyBrewery wyBrewery = wyBreweryService.selectWyBreweryById(wyBeerReview.getBreweryId());
            if (wyBrewery != null && wyBrewery.getFirstReviewCoin() != null && wyBrewery.getFirstReviewCoin() != 0) {
                //存在首评奖励
                final WyBeer beer = wyBeerService.selectWyBeerById(wyBeerReview.getBeerId());
                rewardBeerIcon(wyBeerReview.getBreweryId(), "首次评价奖励：" + beer.getBeerName(), wyBeerReview.getBarId(), wyBrewery.getFirstReviewCoin(), CoinObtainType.Review, wyBeerReview.getId());
            }
            checkReviewData(wyBeerReview.getBeerId());
        }
        return i;
    }

    /**
     * 奖励啤酒币
     */
    private void rewardBeerIcon(Long breweryId, String remark, Long barId, Long rewardCount, Integer obtainType, Long codeId) {
        WyBarIcon wyBarIcon = wyBarIconService.selectWyBarIconByBreweryIdAndBarId(breweryId, barId);
        if (wyBarIcon == null) {
            //钱包不存在,创建钱包
            wyBarIcon = new WyBarIcon();
            wyBarIcon.setBreweryId(breweryId);
            wyBarIcon.setBarId(barId);
            wyBarIcon.setBalance(rewardCount);
            wyBarIconService.insertWyBarIcon(wyBarIcon);
        } else {
            if (wyBarIcon.getBalance() == null) {
                wyBarIcon.setBalance(0L);
            }
            //钱包存在,增加余额
            wyBarIcon.setBalance(wyBarIcon.getBalance() + rewardCount);
            wyBarIconService.updateWyBarIcon(wyBarIcon);
        }
        final WyBarIconLog wyBarIconLog = new WyBarIconLog();    //记录钱包变动日志
        wyBarIconLog.setBarId(barId);
        wyBarIconLog.setBreweryId(breweryId);
        wyBarIconLog.setBalance(wyBarIcon.getBalance());
        wyBarIconLog.setAmount(rewardCount);//变动数量
        wyBarIconLog.setRemark(remark);
        wyBarIconLog.setObtainType(obtainType);
        wyBarIconLog.setCodeId(codeId);
        wyBarIconLogService.insertWyBarIconLog(wyBarIconLog);
    }

    /**
     * 更新酒信息
     */
    private void checkReviewData(Long beerId) {
        WyBeerReview review = new WyBeerReview();
        review.setBeerId(beerId);
        final List<WyBeerReview> wyBeerReviews = wyBeerReviewMapper.selectWyBeerReviewList(review);
        //计算综合分平均值
        final double overallRating = wyBeerReviews.stream().mapToDouble(WyBeerReview::getOverallRating).average().orElse(0.0);
        final WyBeer beer = wyBeerService.selectWyBeerById(beerId);
        if (beer != null) {
            beer.setBeerReviewsCount(wyBeerReviews.size());
            beer.setBeerOverallRating(overallRating);
            wyBeerService.updateWyBeer(beer);
        }
    }

    /**
     * 修改酒评
     *
     * @param wyBeerReview 酒评
     * @return 结果
     */
    @Override
    public int updateWyBeerReview(WyBeerReview wyBeerReview) {
        wyBeerReview.setUpdateTime(DateUtils.getNowDate());
        return wyBeerReviewMapper.updateWyBeerReview(wyBeerReview);
    }

    /**
     * 批量删除酒评
     *
     * @param ids 需要删除的酒评主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteWyBeerReviewByIds(Long[] ids) {
        final int i = wyBeerReviewMapper.deleteWyBeerReviewByIds(ids);
//        for (Long id : ids) {
//            checkReviewData(id);
//        }
        return i;
    }

    /**
     * 删除酒评信息
     *
     * @param id 酒评主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteWyBeerReviewById(Long id) {
        final WyBeerReview wyBeerReview = this.selectWyBeerReviewById(id);
        final WyBrewery wyBrewery = wyBreweryService.selectWyBreweryById(wyBeerReview.getBreweryId());
        final int i = wyBeerReviewMapper.deleteWyBeerReviewById(id);
        if (i > 0) {
            checkReviewData(wyBeerReview.getBeerId());
            final int i1 = wyBeerReviewLikeService.deleteWyBeerReviewLikeByReviewId(id);
            final int i2 = wyBeerReviewReplyService.deleteWyBeerReviewReplyByReviewId(id);
            final WyBarIconLog wyBarIconLog = new WyBarIconLog();
            wyBarIconLog.setCodeId(id);
            wyBarIconLog.setObtainType(CoinObtainType.Review);
            wyBarIconLog.setBreweryId(wyBeerReview.getBreweryId());
            wyBarIconLog.setBarId(wyBeerReview.getBarId());
            final List<WyBarIconLog> wyBarIconLogs = wyBarIconLogService.selectWyBarIconLogList(wyBarIconLog);
            if (wyBarIconLogs != null && wyBarIconLogs.size() > 0) {
                wyBarIconLogs.forEach(log -> {
                    rewardBeerIcon(log.getBreweryId(), "删除评价退回", log.getBarId(), log.getAmount() * -1, CoinObtainType.ReviewReturn, id);
                });
            }
        }
        return i;
    }

    @Override
    public Integer selectBeerReviewCountByDays(Long breweryId, int lastDays) {
        final WyBeerReview wyBeerReview = new WyBeerReview();
        wyBeerReview.setBreweryId(breweryId);
        final HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        final String LastDay = DateUtils.getTime();
        final String firstDay = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.addDays(DateUtils.getNowDate(), -lastDays));
        objectObjectHashMap.put("beginTime", firstDay);
        objectObjectHashMap.put("endTime", LastDay);
        wyBeerReview.setParams(objectObjectHashMap);
        final List<WyBeerReview> wyBeerReviews = this.selectWyBeerReviewList(wyBeerReview);
        return wyBeerReviews.size();
    }

    @Override
    public List<WyBeerReview> selectWyBeerReviewListWithBrewery(WyBeerReview wyBeerReview) {
        List<WyBeerReview> wyBeerReviewlists = wyBeerReviewMapper.selectWyBeerReviewLists(wyBeerReview);
        wyBeerReviewlists.forEach(beerReview -> {
            if (beerReview.getAnonymous()) {
                beerReview.setUserName("匿名用户");
            }
            if (beerReview.getUserName() == null || beerReview.getUserName().isEmpty()) {
                beerReview.setUserName("匿名用户");
            }
        });

        return wyBeerReviewlists;
    }
}
