package com.izouma.dingdong.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.izouma.dingdong.domain.Appraisal;
import com.izouma.dingdong.domain.OrderGoodsSpec;
import com.izouma.dingdong.domain.OrderInfo;
import com.izouma.dingdong.domain.User;
import com.izouma.dingdong.domain.merchant.Goods;
import com.izouma.dingdong.dto.AppraisalMerDTO;
import com.izouma.dingdong.enums.AppraisalSort;
import com.izouma.dingdong.enums.OrderStatus;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.AppraisalRepo;
import com.izouma.dingdong.repo.OrderGoodsSpecRepo;
import com.izouma.dingdong.repo.OrderInfoRepo;

import com.izouma.dingdong.service.merchant.SalesService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class AppraisalService {

    private AppraisalRepo      appraisalRepo;
    private OrderInfoRepo      orderInfoRepo;
    private OrderGoodsSpecRepo orderGoodsSpecRepo;
    private SalesService       salesService;

    /*
    客户评价
     */
    @Transactional
    public Appraisal userAppraisal(Appraisal appraisal) {

        OrderInfo order = orderInfoRepo.findById(appraisal.getOrderInfoId()).orElseThrow(new BusinessException("无订单"));
        //OrderInfo order = appraisal.getOrder();
        if (OrderStatus.RATED.equals(order.getStatus())) {

            order.setRated(true);
            order.setStatus(OrderStatus.COMPLETED);
            orderInfoRepo.save(order);

            appraisal.setMerchantId(order.getMerchantId());
            appraisal.setRiderId(order.getRiderId());
            appraisal.setLikes(0);
            appraisal.setAppraiseTime(LocalDateTime.now());
            appraisal.setEnabled(true);

            appraisal = appraisalRepo.save(appraisal);
            //更新销量数据
            salesService.addLike(appraisal);
            return appraisal;
        } else if (OrderStatus.COMPLETED.equals(order.getStatus())) {
            throw new BusinessException("订单已评价");
        } else {
            throw new BusinessException("订单未完成");
        }
    }

    /*
    按商品查找评价
     */
    public List<AppraisalMerDTO> goodsAppraisals(Long goodsId) {
        List<OrderGoodsSpec> specs = orderGoodsSpecRepo.findAllByGoodsId(goodsId);
        if (ObjectUtil.isNull(specs)) {
            return null;
        }
//        List<Appraisal> appraisals = CollUtil.newArrayList();
        List<AppraisalMerDTO> appraisals = CollUtil.newArrayList();
        specs.forEach(s -> {
            Appraisal appraisal = appraisalRepo.findByOrderInfoId(s.getOrderInfoId())
                    .orElseThrow(new BusinessException("无订单"));
            if (ObjectUtil.isNotNull(appraisal)) {
                appraisals.add(this.toDTO(appraisal));
//                appraisals.add(appraisal);
            }
        });
        return appraisals;
    }

    /**
     * 转商家显示dto
     *
     * @param appraisal 评价
     * @return 商家需要信息的评价dto
     */
    public AppraisalMerDTO toDTO(Appraisal appraisal) {
        OrderInfo order = orderInfoRepo.findById(appraisal.getOrderInfoId()).orElseThrow(new BusinessException("无订单"));
        List<Goods> collect = order.getOrderGoodsSpecs()
                .stream()
                .map(OrderGoodsSpec::getGoods)
                .collect(Collectors.toList());
        String goodsName = collect.stream().map(Goods::getName).collect(Collectors.joining(","));
        User user = order.getUser();
        return AppraisalMerDTO.builder()
                .appraiseTime(appraisal.getAppraiseTime())
                .avatar(user.getAvatar())
                .goodsAppraise(appraisal.getGoodsAppraise())
                //.goodsBad(appraisal.getGoodsBad())
                .goodsLike(appraisal.getGoodsLike())
                .goodsName(goodsName)
                .merchantReply(appraisal.getMerchantReply())
                .nickname(user.getNickname())
                .img(appraisal.getImg())
                .build();
    }

    /**
     * 商户评价排序
     *
     * @param merchantId    商户id
     * @param appraisalSort 评价规则
     * @return 商户所有评价
     */
    public List<Appraisal> appraisalsSort(Long merchantId, AppraisalSort appraisalSort) {
        List<Appraisal> appraisals = appraisalRepo.findAllByMerchantId(merchantId);
        //默认时间排序
        appraisals.sort((a, b) -> b.getAppraiseTime().compareTo(a.getAppraiseTime()));

        List<Appraisal> good = appraisals.stream().filter(Appraisal::getGoodsLike).collect(Collectors.toList());
        List<Appraisal> bad = appraisals.stream().filter(a -> !a.getGoodsLike()).collect(Collectors.toList());

        List<Appraisal> appraisals1 = new ArrayList<>();
        switch (appraisalSort) {
            //最新
            case LATEST:
                appraisals1.addAll(appraisals.stream().filter(
                        a -> !a.getAppraiseTime().isBefore(LocalDateTime.now().plusMonths(1)))
                        .collect(Collectors.toList()));
                break;
            //好评
            case PRAISE:
                appraisals1.addAll(good);
                appraisals1.addAll(bad);
                break;
            //差评
            case BAD_REVIEW:
                appraisals1.addAll(bad);
                appraisals1.addAll(good);
                break;
            //有图
            case HAVE_PIC:
                List<Appraisal> pic = appraisals.stream().filter(a -> StrUtil.isNotBlank(a.getImg()))
                        .collect(Collectors.toList());
                List<Appraisal> noPic = appraisals.stream().filter(a -> StrUtil.isBlank(a.getImg()))
                        .collect(Collectors.toList());
                appraisals1.addAll(pic);
                appraisals1.addAll(noPic);
                break;
            default:
                appraisals1.addAll(appraisals);
        }
        return appraisals1;
    }


}
