package cn.iocoder.yudao.module.member.job;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.member.controller.admin.storeorder.vo.StoreOrderCountVO;
import cn.iocoder.yudao.module.member.dal.dataobject.storebusiness.StoreBusinessDO;
import cn.iocoder.yudao.module.member.dal.mysql.business.BusinessMapper;
import cn.iocoder.yudao.module.member.dal.mysql.storebusiness.StoreBusinessMapper;
import cn.iocoder.yudao.module.member.service.storeorder.StoreOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:qjq 计算门店流水
 * @Date:2024/4/24 下午3:22
 */
@Component
@Slf4j
public class StoreOrderCountJob implements JobHandler {
    @Resource
    private StoreOrderService storeOrderService;

    @Resource
    private BusinessMapper businessMapper;

    @Resource
    private StoreBusinessMapper storeBusinessMapper;
    /**
     * 执行任务
     *
     * @param param 参数
     * @return 结果
     * @throws Exception 异常
     */
    @Override
    @TenantIgnore
    public String execute(String param) throws Exception {
        try {
            List<Long> allStoreId = businessMapper.getAllStoreId();



            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 定义日期格式化器
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            if(StrUtil.isNotBlank(param)){
                currentDate = LocalDate.parse(param, formatter);
            }

            // 获取前一天的日期
            LocalDate previousDate = currentDate.minusDays(1);

            // 将前一天的日期格式化为字符串
            String formattedDate = previousDate.format(formatter);

            List<StoreOrderCountVO> storeOrderCountVOS = storeOrderService.countOrder(formattedDate, formattedDate);
            LocalDateTime startOfDay = previousDate.atStartOfDay();
            LocalDateTime endOfDay = previousDate.atTime(LocalTime.MAX).withNano(0);
            BigDecimal zero = BigDecimal.ZERO;
            for (Long storeId:allStoreId){
                StoreBusinessDO todayBusiness = storeBusinessMapper.getTodayBusiness(storeId, startOfDay, endOfDay);
                List<StoreOrderCountVO> collect = storeOrderCountVOS.stream().filter(vo -> vo.getCarteenId().equals(storeId)).collect(Collectors.toList());
                if (collect.isEmpty()){
                    todayBusiness.setTurnover(zero).setOrderSum(0).setCustomerSum(0).setPriceAvg(zero).setReduce(zero)
                            .setBreakfast(zero).setBreakfastNum(0)
                            .setLunch(zero).setLunchNum(0)
                            .setDinner(zero).setDinnerNum(0)
                            .setWeigh(zero);
                }else {
                    double total = collect.stream().mapToDouble(StoreOrderCountVO::getTotalPrice).sum();
                    int size = collect.size();
                    BigDecimal divide = new BigDecimal(total).divide(new BigDecimal(size), 2, BigDecimal.ROUND_HALF_UP);

                    List<StoreOrderCountVO> breakfast = collect.stream().filter(vo -> vo.getTimeSlot().equals("早上")).collect(Collectors.toList());
                    double breakfastSum = breakfast.stream().mapToDouble(StoreOrderCountVO::getTotalPrice).sum();

                    List<StoreOrderCountVO> lunch = collect.stream().filter(vo -> vo.getTimeSlot().equals("中午")).collect(Collectors.toList());
                    double lunchSum = lunch.stream().mapToDouble(StoreOrderCountVO::getTotalPrice).sum();

                    List<StoreOrderCountVO> dinner = collect.stream().filter(vo -> vo.getTimeSlot().equals("晚上")).collect(Collectors.toList());
                    double dinnerSum = dinner.stream().mapToDouble(StoreOrderCountVO::getTotalPrice).sum();

                    double reduce = collect.stream().mapToDouble(StoreOrderCountVO::getReductionPrice).sum();
                    todayBusiness.setTurnover(new BigDecimal(total)).setOrderSum(size)
                            .setCustomerSum(size).setPriceAvg(divide).setReduce(new BigDecimal(reduce))
                            .setBreakfast(new BigDecimal(breakfastSum)).setBreakfastNum(breakfast.size())
                            .setLunch(new BigDecimal(lunchSum)).setLunchNum(lunch.size())
                            .setDinner(new BigDecimal(dinnerSum)).setDinnerNum(dinner.size())
                            .setWeigh(zero);
                }
                storeBusinessMapper.updateById(todayBusiness);
            }
        } catch (Exception e) {
            return "超市订单统计失败";
        }
        return "超市订单统计成功";
    }
}
