package com.izouma.dingdong.service.merchant;

import cn.hutool.core.collection.CollUtil;
import com.izouma.dingdong.domain.MoneyRecord;
import com.izouma.dingdong.domain.OrderInfo;
import com.izouma.dingdong.domain.User;
import com.izouma.dingdong.domain.backstage.Banner;
import com.izouma.dingdong.domain.backstage.Category;
import com.izouma.dingdong.domain.backstage.Promote;
import com.izouma.dingdong.domain.backstage.TimeTag;
import com.izouma.dingdong.domain.merchant.Goods;
import com.izouma.dingdong.domain.merchant.Merchant;
import com.izouma.dingdong.domain.merchant.MerchantSettings;
import com.izouma.dingdong.dto.MerchantDTO;
import com.izouma.dingdong.enums.FinancialType;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.AppraisalRepo;
import com.izouma.dingdong.repo.MoneyRecordRepo;
import com.izouma.dingdong.repo.OrderInfoRepo;
import com.izouma.dingdong.repo.UserRepo;
import com.izouma.dingdong.repo.backstage.BannerRepo;
import com.izouma.dingdong.repo.backstage.CategoryRepo;
import com.izouma.dingdong.repo.backstage.PromoteRepo;
import com.izouma.dingdong.repo.backstage.TimeTagRepo;
import com.izouma.dingdong.repo.merchant.*;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class MerchantSettingsService {

    private MerchantSettingsRepo merchantSettingsRepo;
    private OrderInfoRepo orderInfoRepo;
    private TimeTagRepo timeTagRepo;
    private MerchantRepo merchantRepo;
    private UserRepo userRepo;
    private MoneyRecordRepo moneyRecordRepo;
    private BannerRepo bannerRepo;
    private CategoryRepo categoryRepo;
    private PromoteRepo promoteRepo;
    private GoodsRepo goodsRepo;
    private AppraisalRepo appraisalRepo;
    private GoodsSpecificationRepo goodsSpecificationRepo;
    private MerchantClassificationRepo merchantClassificationRepo;
    // private FullReductionRepo fullReductionRepo;

    /*
    显示所有订单
     */
    public List<OrderInfo> allOrder(Long id) {
        return orderInfoRepo.findAllByMerchantId(id);
    }

    /*
    时间标签类商家列表
     */
    public List<MerchantDTO> timeMerchant(Long timeTagId) {
        TimeTag timeTag = timeTagRepo.findById(timeTagId).orElseThrow(new BusinessException("无时间标签"));
        List<MerchantSettings> all = merchantSettingsRepo.findAll();
        List<MerchantSettings> collect = all.stream().filter(a ->
                //商家开始时间早于结束前的一小时 或者 商家结束时间早于开始后的一小时
                !a.getStartTime().isAfter(timeTag.getEndTime().minusHours(1)) || !a.getEndTime().isAfter(timeTag.getStartTime().plusHours(1))
        ).collect(Collectors.toList());

        List<MerchantDTO> list = CollUtil.newArrayList();

        collect.forEach(a -> {
            Merchant merchant = merchantRepo.findById(a.getMerchantId()).orElseThrow(new BusinessException("无商家"));
            list.add(new MerchantDTO(merchant, a));
        });

        return list;
    }


    /*
    商户叮咚币记录
     */
    public void income(Long merchantId, Long fromUserId, BigDecimal amount, FinancialType type) {
        //按商户Id找出用户
        User userMer = userRepo.findById(merchantRepo.findUserIdById(merchantId)).orElseThrow(new BusinessException("无用户"));
        //商家应得 = 减去骑手应得，减去平台抽成
        userMer.setMoney(userMer.getMoney().add(amount));
        userRepo.save(userMer);

        //购买的user
        User user = userRepo.findById(fromUserId).orElseThrow(new BusinessException("无用户"));

        //商家记录到对账单
        moneyRecordRepo.save(
                MoneyRecord.builder()
                        .avatar(user.getAvatar())
                        .name(user.getNickname())
                        .type(type)
                        .time(LocalDateTime.now())
                        .amount(amount)
                        .userId(userMer.getId())
                        .fromUserId(fromUserId)
                        .enabled(true)
                        .build()
        );
    }

    /*
     * 首页上的东西
     * banner
     * 分类
     * 优惠专区
     * 每日力荐
     * 新店推荐
     * 推荐商家
     * 发现美食
     */
    public Map<String, Object> index(Double longitude, Double latitude) {
        //banner
        List<Banner> banners = bannerRepo.findAll();

        //一级分类
        List<Category> categories = categoryRepo.findAllByParent((long) 1);

        //时间标签
        List<TimeTag> timeTags = timeTagRepo.findAll();
        LocalTime now = LocalTime.now();
        List<TimeTag> timeTag = timeTags.stream().filter(t -> now.isAfter(t.getStartTime()) && now.isBefore(t.getEndTime())).collect(Collectors.toList());

        //优惠专区
        //主推荐位 2个
        List<Promote> promote1 = promoteRepo.findAllByAction(1);
        promote1.subList(0, 2);
        //副推荐位 4个
        List<Promote> promote2 = promoteRepo.findAllByAction(2);
        promote2.subList(0, 4);

        //新店推荐 最多8个
        LocalDate date = LocalDate.now().minusMonths(1);
        LocalTime time = LocalTime.parse("00:00:00");
        LocalDateTime dateTime = LocalDateTime.of(date, time);
        List<Merchant> newMerchants = merchantRepo.findAllByEstablishTimeAfter(dateTime);
        newMerchants.subList(0, 8);


        Map<String, Object> map = new HashMap<>();
        map.put("banner", banners);
        map.put("categories", categories);
        map.put("timeTag", timeTag.get(0));
        map.put("promote1", promote1);
        map.put("promote2", promote2);
        map.put("newMerchants", newMerchants);
        return map;
    }

    /*
    明星商家
     */
    public boolean starMerchant(Merchant merchant) {
        //非新商家
        boolean b = merchant.getEstablishTime().isAfter(LocalDateTime.now().minusMonths(1));
        if (b) {
            return merchant.getMonthSales() >= 10000 && merchant.getBadNum() > 0 && merchant.getGoodNum() > 3000;
        }
        return false;

    }

    /*
    人均消费 月订单
     */
    public BigDecimal consumption(Merchant merchant) {
        List<OrderInfo> orders = orderInfoRepo.findAllByMerchantId(merchant.getId());
        List<BigDecimal> collect = orders.stream().map(o ->
                o.getRealAmount().subtract(o.getDeliveryAmount())
        ).collect(Collectors.toList());

        BigDecimal total = BigDecimal.ZERO;
        for (BigDecimal c : collect) {
            total = total.add(c);
        }

        return total.divide(BigDecimal.valueOf(collect.size()), 2);
    }


    /*
    删除商家
     */
    public void del(Long merchantId) {
        //删除商户
        merchantRepo.deleteById(merchantId);
        merchantSettingsRepo.deleteByMerchantId(merchantId);

        //删除商品规格
        List<Long> collect = goodsRepo.findAllByMerchantId(merchantId).stream().map(Goods::getId).collect(Collectors.toList());
        collect.forEach(c -> goodsSpecificationRepo.deleteByGoodsId(c));

        //删除商品
        goodsRepo.deleteAllByMerchantId(merchantId);

        //删除订单
        orderInfoRepo.deleteAllByMerchantId(merchantId);

        //删除评价
        appraisalRepo.deleteAllByMerchantId(merchantId);

        //删除商家分类
        merchantClassificationRepo.findAllByMerchantId(merchantId);

    }

}
