package com.izouma.dingdong.service.merchant;

import com.izouma.dingdong.domain.Appraisal;
import com.izouma.dingdong.domain.OrderGoodsSpec;
import com.izouma.dingdong.domain.OrderInfo;
import com.izouma.dingdong.domain.merchant.Goods;
import com.izouma.dingdong.domain.merchant.MerchantClassification;
import com.izouma.dingdong.domain.merchant.Sales;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.OrderGoodsSpecRepo;
import com.izouma.dingdong.repo.merchant.GoodsRepo;
import com.izouma.dingdong.repo.merchant.MerchantClassificationRepo;
import com.izouma.dingdong.repo.merchant.SalesRepo;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
@AllArgsConstructor
public class SalesService {

    private SalesRepo salesRepo;

    private MerchantClassificationRepo merchantClassificationRepo;

    private OrderGoodsSpecRepo orderGoodsSpecRepo;

    private GoodsRepo goodsRepo;

    private MerchantClassificationService merchantClassificationService;

    /*
    下订单时插入销量
     */
    public void addSale(OrderInfo orderInfo) {
        //订单规格
        List<OrderGoodsSpec> orderGoodsSpecs = orderGoodsSpecRepo.findAllByOrderInfoId(orderInfo.getId());

        orderGoodsSpecs.forEach(
                spec -> {
                    //查商品销量表的销量数据
                    Sales daySales = this.newSales(spec.getGoodsId(), LocalDate.now());

                    //有订单，销量 + 购买数量
                    daySales.setDaySales(daySales.getDaySales() + spec.getNum());

                    //保存
                    salesRepo.save(daySales);
                }
        );
    }

    /*
    评价时加入销量
     */
    public void addLike(Appraisal appraisal) {
        //Appraisal appraisal = appraisalRepo.findByOrderInfoId(appraisalId).orElseThrow(new BusinessException("评价不存在"));
        List<OrderGoodsSpec> specs = orderGoodsSpecRepo.findAllByOrderInfoId(appraisal.getOrderInfoId());

        specs.forEach(spec -> {
            //Sales daySales = salesRepo.findByGoodsIdAndDay(spec.getGoodsId(), LocalDate.now());
            Sales daySales = this.newSales(spec.getGoodsId(), LocalDate.now());

            if (appraisal.getGoodsLike()) {
                daySales.setDayLikes(daySales.getDayLikes() + 1);
                //查商品数据，加好评数
                goodsRepo.updateLikesById(spec.getGoodsId());
            } else {
                daySales.setDayBad(daySales.getDayBad() + 1);
                //查商品数据，加差评数
                goodsRepo.updateBadById(spec.getGoodsId());
            }
            salesRepo.save(daySales);
        });

    }

    /*
    一天结束设置
     */
    @Scheduled(cron = "59 59 23 * * ?")
    public void dayOver() {
        LocalDate now = LocalDate.now();
        List<Sales> allSales = salesRepo.findAllByDay(now);
        allSales.forEach(
                sales -> {
                    //无差评，销量 >=10，有好评
                    if (sales.getDayBad() == 0 && sales.getDaySales() >= 10 && sales.getDayLikes() > 0) {
                        //查找昨天的好评连续值
                        Integer praise = salesRepo.findByGoodsIdAndDay(sales.getGoodsId(), now.plusDays(-1))
                                .getPraise();
                        //好评连续值+1
                        sales.setPraise(praise + 1);
                    } else {
                        //如果有差评，不为好评商品
                        sales.setPraise(0);
                    }
                    //销量 >50
                    if (sales.getDaySales() >= 50) {
                        //查找昨天的人气连续值
                        Integer popularity = salesRepo.findByGoodsIdAndDay(sales.getGoodsId(), now.plusDays(-1))
                                .getPopularity();
                        //人气连续值+1
                        sales.setPopularity(popularity + 1);
                    } else {
                        sales.setPopularity(0);
                    }
                    salesRepo.save(sales);
                }
        );
        addClass();
    }

    /*
    如果有好评人气商品插入分类
     */
    public void addClass() {
        //查出今天所有人气商品
        List<Sales> popularities = salesRepo.findAllByDayAndPopularityGreaterThanEqual(LocalDate.now(), 5);

        //查处今天所有好评商品
        List<Sales> praises = salesRepo.findAllByDayAndPraiseGreaterThanEqual(LocalDate.now(), 5);

        //插入
        // popularities.forEach(this::into);
        popularities.forEach(p -> {
            this.into(p);
            Goods goods = goodsRepo.findById(p.getGoodsId()).orElseThrow(new BusinessException("无商品"));
            //人气
            goods.setPopularity(true);
            goodsRepo.save(goods);
        });

        // praises.forEach(this::into);
        praises.forEach(p -> {
            this.into(p);
            Goods goods = goodsRepo.findById(p.getGoodsId()).orElseThrow(new BusinessException("无商品"));
            //好评
            goods.setPraise(true);
            goodsRepo.save(goods);
        });
    }


    /*
    插入到商家自定义分类
     */
    private void into(Sales sales) {
        //查找好评热销 -> 1
        MerchantClassification merchantClass = merchantClassificationRepo.findByMerchantIdAndType(sales.getId(), 1);
        if (!merchantClass.getIsOpen()) {
            return;
        }
//        Set<Goods> goodsList = merchantClass.getGoodsList();
//        goodsList.add(sales.getGoods());
//        merchantClass.setGoodsList(goodsList);

        merchantClassificationService.saveOneGoods(merchantClass.getId(), sales.getGoodsId());

//        String goodsId = merchantClass.getGoodsIds();
//        goodsId = goodsId + "," + sales.getGoodsId();
//        merchantClass.setGoodsIds(goodsId);
    }


    /*
    新建销量
     */
    public Sales newSales(Long goodsId, LocalDate localDate) {
        Sales daySales = salesRepo.findByGoodsIdAndDay(goodsId, localDate);
        Goods goods = goodsRepo.findById(goodsId).orElseThrow(new BusinessException("无商品"));

        if (daySales == null) {
            daySales = Sales.builder()
                    .merchantId(goods.getMerchantId())
                    .goodsId(goodsId)
                    .day(localDate)
                    .dayLikes(0)
                    .dayBad(0)
                    .popularity(0)
                    .praise(0)
                    .daySales(0)
                    .build();
        }
        return daySales;
    }

}
