package com.bonus.canteen.core.report.statistics.order.basic.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.canteen.core.allocation.api.AllocHolidayApi;
import com.bonus.canteen.core.customer.constants.CustAgeEnum;
import com.bonus.canteen.core.customer.constants.CustConstant;
import com.bonus.canteen.core.customer.model.CustInfo;
import com.bonus.canteen.core.order.common.model.OrderAmountDetail;
import com.bonus.canteen.core.order.mq.constants.OrderChangeTypeEnum;
import com.bonus.canteen.core.order.mq.po.OrderChangePO;
import com.bonus.canteen.core.report.api.dto.ReportCustConsumeSumDTO;
import com.bonus.canteen.core.report.statistics.config.mq.ReportOrderConsumeService;
import com.bonus.canteen.core.report.statistics.config.mq.enums.ReportMsgStatusEnum;
import com.bonus.canteen.core.report.statistics.order.basic.dto.ReportOrderInfoDTO;
import com.bonus.canteen.core.report.statistics.order.basic.mapper.ReportOrderInfoMapper;
import com.bonus.canteen.core.report.statistics.order.basic.model.ReportOrderInfo;
import com.bonus.canteen.core.order.common.model.*;
import com.bonus.canteen.core.report.statistics.param.ReportBaseParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ReportOrderInfoService extends ServiceImpl<ReportOrderInfoMapper, ReportOrderInfo> implements ReportOrderConsumeService {
   private static final Logger log = LoggerFactory.getLogger(ReportOrderInfoService.class);
   private static final int ORDER = 1;
   @Resource
   private AllocHolidayApi allocHolidayApi;
//   @Autowired
//   private MgrAuthApi mgrAuthApi;
//   @Autowired
//   ReportOrderInfoOrderTimeService reportOrderInfoOrderTimeService;
//   @Autowired
//   ReportOrderInfoOrderDateService reportOrderInfoOrderDateService;
//   @Autowired
//   ReportRefundService reportRefundService;
//   @Resource(
//      name = "yunshitangTaskExecutor"
//   )
//   private AsyncTaskExecutor asyncTaskExecutor;

   public int getOrder() {
      return 1;
   }

//   public ReportBaseTotalVO<ReportBasicOrderVO> pageSummary(ReportBasicOrderParam param) {
//      MgrUserAuthPO authPO = this.mgrAuthApi.getUserAuthPO();
//      ParamUtil.formatOrders(param.getPage(), ReportBasicOrderVO.class);
//      List<Long> orderIdPage = ((ReportOrderInfoMapper)this.baseMapper).listSummaryId(param, authPO);
//      if (CollUtil.isEmpty(orderIdPage)) {
//         return (new ReportBaseTotalVO()).setResultPage(PageVO.of((List)CollUtil.newArrayList(new ReportBasicOrderVO[0])));
//      } else {
//         PageVO<ReportBasicOrderVO> list = PageVO.of(orderIdPage, ((ReportOrderInfoMapper)this.baseMapper).listSummary(param, orderIdPage));
//         List<ReportBasicOrderVO> reportBasicOrderVOList = list.getRecords();
//         ReportBasicOrderVO total = new ReportBasicOrderVO();
//         if (param.getIfQueryTotal()) {
//            total = ((ReportOrderInfoMapper)this.baseMapper).getSummaryTotal(param, authPO);
//         }
//
//         if (CollUtil.isEmpty(reportBasicOrderVOList)) {
//            return (new ReportBaseTotalVO()).setResultPage(list);
//         } else {
//            if (CollUtil.isNotEmpty(param.getTradeTypeList())) {
//               reportBasicOrderVOList = reportBasicOrderVOList.stream().filter((s) -> {
//                  return param.getTradeTypeList().contains(s.getTradeType());
//               }).toList();
//            }
//
//            reportBasicOrderVOList.forEach((e) -> {
//               e.setConsumeSource(this.formatSource(e));
//               e.setReportOrderPays(this.parsePayTypeStr(e.getPayTypeStr()));
//               e.setPayTypeStr(this.getPayTypesDescStr(e.getReportOrderPays()));
//               e.setPayChannelStr(this.getPayTypesDescStrByChannel(e.getReportOrderPays()));
//               e.setReportOrderDiscounts(this.parseDiscountStr(e.getDiscountStr()));
//            });
//            list.setRecords(reportBasicOrderVOList);
//            return (new ReportBaseTotalVO()).setResultPage(list).setTotalLine(total);
//         }
//      }
//   }
//
//   public ReportBaseTotalVO<ReportBasicOrderVO> pageSummaryExport(ReportBasicOrderParam param) {
//      MgrUserAuthPO authPO = this.mgrAuthApi.getUserAuthPO();
//      PageMethod.startPage(param.getPage());
//      List<Long> orderIdPage = ((ReportOrderInfoMapper)this.baseMapper).listSummaryId(param, authPO);
//      if (CollUtil.isEmpty(orderIdPage)) {
//         return (new ReportBaseTotalVO()).setResultPage(PageVO.of((List)orderIdPage, CollUtil.newArrayList(new ReportBasicOrderVO[0])));
//      } else {
//         PageVO<ReportBasicOrderVO> pageVO = PageVO.of(orderIdPage, ((ReportOrderInfoMapper)this.baseMapper).listSummary(param, orderIdPage));
//         List<ReportBasicOrderVO> list = pageVO.getRecords();
//         boolean ifExportPayTypeFlag = this.ifExportPayType(param.getExportCols());
//         list.forEach((e) -> {
//            e.setConsumeSource(this.formatSource(e));
//            if (ifExportPayTypeFlag) {
//               List<ReportOrderPay> payList = this.parsePayTypeStr(e.getPayTypeStr());
//               e.setPayTypeStr(this.getPayTypesDescStr(payList));
//               e.setPayChannelStr(this.getPayTypesDescStrByChannel(payList));
//            }
//
//         });
//         ReportBasicOrderVO total = this.getReportBasicOrderVO(param, authPO);
//         return (new ReportBaseTotalVO()).setResultPage(PageVO.of(list)).setTotalLine(total);
//      }
//   }
//
//   public ReportBasicOrderVO getReportBasicOrderVO(ReportBasicOrderParam param, MgrUserAuthPO authPO) {
//      if (Objects.isNull(authPO)) {
//         authPO = this.mgrAuthApi.getUserAuthPO();
//      }
//
//      return ((ReportOrderInfoMapper)this.baseMapper).getSummaryTotal(param, authPO);
//   }
//
//   private boolean ifExportPayType(List<String> exportCols) {
//      return exportCols.contains("payChannelStr") || exportCols.contains("payTypeStr");
//   }

   public void consume(OrderChangePO payload, ReportOrderInfoDTO baseInfo) {
      log.info("报表MQ消费-订单基本信息：开始");
      ReportOrderInfo reportOrderInfo = this.formatReportOrderInfo(payload, baseInfo);
      reportOrderInfo.setStatus(ReportMsgStatusEnum.NOT_CONSUME.getKey());
      this.saveOrUpdate(reportOrderInfo);
      baseInfo.setReportOrderInfo(reportOrderInfo);
      List<Integer> payChannels = new ArrayList();
      List<Integer> payTypes = new ArrayList();
      List orderAmountDetailList;
      if (Objects.equals(OrderChangeTypeEnum.REFUND.getKey(), payload.getChangeType())) {
         orderAmountDetailList = payload.getRefundAmountDetailList();
      } else {
         orderAmountDetailList = payload.getAmountDetailList();
      }

      if (!CollUtil.isEmpty(orderAmountDetailList)) {
         Iterator var7 = orderAmountDetailList.iterator();

         while(var7.hasNext()) {
            OrderAmountDetail orderAmountDetail = (OrderAmountDetail)var7.next();
            payChannels.add(orderAmountDetail.getPayChannel());
            payTypes.add(orderAmountDetail.getPayType());
         }
      }

      baseInfo.setPayChannels(payChannels);
      baseInfo.setPayTypes(payTypes);
      List<Long> dishesIds = payload.getOrderDetailList().stream().map(OrderDetail::getGoodsDishesId).filter(Objects::nonNull).collect(Collectors.toList());
      baseInfo.setDishesIds(dishesIds);
      log.info("报表MQ消费-订单基本信息：结束");
   }

   public void fix(ReportBaseParam param) {
      log.info("报表修复数据-订单基本信息：开始");
      LocalDateTime startTime = param.getStartDate().atStartOfDay();
      LocalDateTime endTime = param.getEndDate().atTime(23, 59, 59);
      ((ReportOrderInfoMapper)this.baseMapper).deleteByPayTime(startTime, endTime);
      ((ReportOrderInfoMapper)this.baseMapper).initByPayTime(startTime, endTime);
      log.info("报表修复数据-订单基本信息：结束");
   }

   public <T> T initParam(OrderChangePO payload, ReportOrderInfoDTO baseInfo, Class<T> tClass) {
      LocalDate statisticDate = Objects.equals(OrderChangeTypeEnum.REFUND.getKey(), payload.getChangeType()) ? payload.getOrderRefund().getCheckTime().toLocalDate() : payload.getOrderInfo().getPayTime().toLocalDate();
      return ReflectUtil.newInstance(tClass, new Object[]{baseInfo, statisticDate});
   }

   private ReportOrderInfo formatReportOrderInfo(OrderChangePO payload, ReportOrderInfoDTO baseInfo) {
      OrderInfo orderInfo = payload.getOrderInfo();
      ReportOrderInfo reportOrderInfo = (ReportOrderInfo) BeanUtil.copyProperties(orderInfo, ReportOrderInfo.class, new String[0]);
      reportOrderInfo.setCanteenId(Objects.isNull(orderInfo.getCanteenId()) ? -1L : orderInfo.getCanteenId());
      reportOrderInfo.setStallId(Objects.isNull(orderInfo.getStallId()) ? -1L : orderInfo.getStallId());
      CustInfo custInfo = baseInfo.getCustInfo();
      reportOrderInfo.setOrgId(Objects.isNull(custInfo) ? CustConstant.TEMPORARY_ORG_ID : custInfo.getOrgId());
      Integer psnType = Objects.isNull(custInfo) ? -1 : custInfo.getPsnType();
      reportOrderInfo.setPsnType(Objects.isNull(psnType) ? -1 : psnType);
      reportOrderInfo.setOutTradeNo(Objects.isNull(payload.getOutTradeNo()) ? null : payload.getOutTradeNo());
      CustAgeEnum enumByAge = Objects.isNull(custInfo) ? CustAgeEnum.OTHER : CustAgeEnum.getEnumByAge(custInfo.getBirthday());
      reportOrderInfo.setAgeType(enumByAge.getKey());
      Integer holidayType = this.allocHolidayApi.getHolidayType(reportOrderInfo.getPayTime().toLocalDate());
      reportOrderInfo.setHolidayType(Objects.isNull(holidayType) ? -1 : holidayType);
      reportOrderInfo.setDiscountsAmount((Objects.isNull(orderInfo.getDiscountsAmount()) ? BigDecimal.ZERO : orderInfo.getDiscountsAmount()).multiply(BigDecimal.valueOf(-1L)));
      reportOrderInfo.setMealtimeType(Objects.isNull(orderInfo.getMealtimeType()) ? -1 : orderInfo.getMealtimeType());
      return reportOrderInfo;
   }
//
//   private String formatSource(ReportBasicOrderVO payload) {
//      List<String> source = new ArrayList();
//      source.add(Objects.nonNull(payload.getConsumeSource()) ? payload.getConsumeSource() : null);
//      source.add(Objects.nonNull(payload.getSourceType()) && !Objects.equals(payload.getSourceType(), -1) ? SourceTypeEnum.getDesc(payload.getSourceType()) : null);
//      return (String)source.stream().filter(CharSequenceUtil::isNotBlank).collect(Collectors.joining("-"));
//   }
//
//   public ReportBaseTotalVO<ReportCustSummaryVO> pageCustSummary(ReportCustSummaryParam param) {
//      MgrUserAuthPO authPO = this.mgrAuthApi.getUserAuthPO();
//      ReportCustSummaryParam copyParam = (ReportCustSummaryParam)BeanUtil.copyProperties(param, ReportCustSummaryParam.class, new String[0]);
//      CompletableFuture<List<ReportCustSummaryVO>> listFuture = CompletableFuture.supplyAsync(() -> {
//         PageMethod.startPage(copyParam.getPage());
//         List<ReportCustSummaryVO> list = ((ReportOrderInfoMapper)this.baseMapper).listCustSummary(param, authPO);
//         List<Long> custIdList = list.stream().map(ReportCustSummaryVO::getCustId).toList();
//         List<String> orgFullNameList = list.stream().map(ReportCustSummaryVO::getOrgFullName).toList();
//         copyParam.setCustIdList(custIdList);
//         copyParam.setOrgFullNameList(orgFullNameList);
//         if (copyParam.getSumType().equals(CommonConstants.ONE)) {
//            List<ReportMealtimeTypeCustNumDTO> listConsumeDayNum = ((ReportOrderInfoMapper)this.baseMapper).getTotalConsumeDayNum(copyParam, authPO);
//            Map<String, Integer> consumeDayNumMap = (Map)listConsumeDayNum.stream().collect(Collectors.toMap((e) -> {
//               Long var10000 = e.getCustId();
//               return "" + var10000 + "_" + e.getOrgFullName();
//            }, ReportMealtimeTypeCustNumDTO::getCustNum));
//            list.forEach((e) -> {
//               Long var10001 = e.getCustId();
//               Integer consumeDayNum = (Integer)consumeDayNumMap.get("" + var10001 + "_" + e.getOrgFullName());
//               e.setTotalConsumeDayNum(Objects.isNull(consumeDayNum) ? 0 : consumeDayNum);
//            });
//         }
//
//         return list;
//      }, this.asyncTaskExecutor);
//      CompletableFuture<ReportCustSummaryVO> totalFuture = CompletableFuture.supplyAsync(() -> {
//         ReportCustSummaryVO total = this.getReportCustSummaryVO(param, authPO);
//         if (param.getSumType().equals(CommonConstants.ONE)) {
//            param.setIfTotal(CommonConstants.ONE);
//            List<ReportMealtimeTypeCustNumDTO> totalConsumeDayNum = ((ReportOrderInfoMapper)this.baseMapper).getTotalConsumeDayNum(param, authPO);
//            total.setTotalConsumeDayNum(Objects.isNull(totalConsumeDayNum) ? 0 : ((ReportMealtimeTypeCustNumDTO)totalConsumeDayNum.get(0)).getCustNum());
//         }
//
//         return total;
//      }, this.asyncTaskExecutor);
//      CompletableFuture<Void> future = CompletableFuture.allOf(listFuture, totalFuture);
//      future.join();
//      List<ReportCustSummaryVO> list = (List)listFuture.join();
//      ReportCustSummaryVO total = (ReportCustSummaryVO)totalFuture.join();
//      return (new ReportBaseTotalVO()).setResultPage(PageVO.of(list)).setTotalLine(total);
//   }
//
//   public ReportCustSummaryVO getReportCustSummaryVO(ReportCustSummaryParam param, MgrUserAuthPO authPO) {
//      if (Objects.isNull(authPO)) {
//         authPO = this.mgrAuthApi.getUserAuthPO();
//      }
//
//      return (ReportCustSummaryVO)Optional.ofNullable(((ReportOrderInfoMapper)this.baseMapper).getCustSummaryTotal(param, authPO)).orElse(new ReportCustSummaryVO());
//   }
//
//   public List<ReportNotConsumeDTO> queryNotConsumeData() {
//      return ((ReportOrderInfoMapper)this.baseMapper).queryNotConsumeData();
//   }
//
//   public void updateOrderMsg(List<ReportNotConsumeDTO> list) {
//      ((ReportOrderInfoMapper)this.baseMapper).updateOrderMsg(list);
//   }
//
//   public List<DeviceOrderDishesSumVO> getOrderDishesSumForDevice(DeviceOrderDishesSumQueryDTO param) {
//      return ((ReportOrderInfoMapper)this.baseMapper).getOrderDishesSumForDevice(param);
//   }
//
//   public String getPayTypesDescStr(List<ReportOrderPay> reportOrderPays) {
//      return CollUtil.isEmpty(reportOrderPays) ? PayTypeEnum.getDesc((Integer)null) : (String)reportOrderPays.stream().filter((s) -> {
//         return s.getPayAmount().compareTo(BigDecimal.ZERO) > 0 || reportOrderPays.size() == 1;
//      }).map((s) -> {
//         return PayTypeEnum.getDesc(s.getPayType());
//      }).collect(Collectors.joining("+"));
//   }
//
//   public String getPayTypesDescStrByChannel(List<ReportOrderPay> reportOrderPays) {
//      return CollUtil.isEmpty(reportOrderPays) ? PayChannelEnum.getDesc((Integer)null) : (String)reportOrderPays.stream().filter((s) -> {
//         return s.getPayAmount().compareTo(BigDecimal.ZERO) > 0 || reportOrderPays.size() == 1;
//      }).map((s) -> {
//         return PayChannelEnum.getDesc(s.getPayChannel());
//      }).collect(Collectors.joining("+"));
//   }
//
//   private List<ReportOrderPay> parsePayTypeStr(String payTypeStr) {
//      List<ReportOrderPay> payList = new ArrayList();
//      if (CharSequenceUtil.isNotBlank(payTypeStr)) {
//         String[] payTypeArr = payTypeStr.split(";");
//         String[] var4 = payTypeArr;
//         int var5 = payTypeArr.length;
//
//         for(int var6 = 0; var6 < var5; ++var6) {
//            String payType = var4[var6];
//            String[] payTypeDetail = payType.split("-");
//            ReportOrderPay reportOrderPay = new ReportOrderPay();
//            reportOrderPay.setPayType(Integer.valueOf(payTypeDetail[0]));
//            reportOrderPay.setPayChannel(Integer.valueOf(payTypeDetail[1]));
//            reportOrderPay.setPayAmount(new BigDecimal(payTypeDetail[2]));
//            reportOrderPay.setRefundAmount(new BigDecimal(payTypeDetail[3]));
//            payList.add(reportOrderPay);
//         }
//      }
//
//      return payList;
//   }
//
//   private List<ReportOrderDiscount> parseDiscountStr(String discountStr) {
//      List<ReportOrderDiscount> discountList = new ArrayList();
//      if (CharSequenceUtil.isNotBlank(discountStr)) {
//         String[] discountArr = discountStr.split(";");
//         String[] var4 = discountArr;
//         int var5 = discountArr.length;
//
//         for(int var6 = 0; var6 < var5; ++var6) {
//            String discount = var4[var6];
//            String[] discountDetail = discount.split(",");
//            ReportOrderDiscount reportOrderDiscount = new ReportOrderDiscount();
//            reportOrderDiscount.setChangeType(Integer.valueOf(discountDetail[0]));
//            reportOrderDiscount.setChangeDetailType(Integer.valueOf(discountDetail[1]));
//            reportOrderDiscount.setChangeAmount(new BigDecimal(discountDetail[2]));
//            discountList.add(reportOrderDiscount);
//         }
//      }
//
//      return discountList;
//   }

   public List<ReportOrderInfo> getCustConsumeSum(ReportCustConsumeSumDTO content) {
      return ((ReportOrderInfoMapper)this.baseMapper).getCustConsumeSum(content);
   }

//   public List<ReportOrderDetaiVO> drpDishesSum(OrderDrpDishesSumDTO content) {
//      return ((ReportOrderInfoMapper)this.baseMapper).drpDishesSum(content);
//   }
//
//   public List<OrderBusStatVO> listOrderStatForBus(OrderStatBusDTO param) {
//      MgrUserAuthPO authPO = this.mgrAuthApi.getUserAuthPO();
//      return ((ReportOrderInfoMapper)this.baseMapper).listOrderStatForBus(param, authPO);
//   }
//
//   public OrderBookStatMobileVO getBookStat(Long custId) {
//      LocalDateTime startTime = LocalDate.now().minusMonths(3L).atStartOfDay();
//      LocalDateTime endTime = LocalDate.now().atTime(23, 59, 59);
//      return ((ReportOrderInfoMapper)this.baseMapper).getBookStat(custId, startTime, endTime);
//   }
//
//   public OrderBookRefundStatMobileVO getBookRefundStat(Long custId) {
//      LocalDateTime startTime = LocalDate.now().minusMonths(3L).atStartOfDay();
//      LocalDateTime endTime = LocalDate.now().atTime(23, 59, 59);
//      return ((ReportOrderInfoMapper)this.baseMapper).getBookRefundStat(custId, startTime, endTime);
//   }
//
//   public ReportBaseTotalVO<ReportRemoteDetailVO> pageRemoteDetailSummary(ReportRemoteParam param) {
//      MgrUserAuthPO authPO = this.mgrAuthApi.getUserAuthPO();
//      PageMethod.startPage(param.getPage());
//      List<ReportRemoteDetailVO> list = ((ReportOrderInfoMapper)this.baseMapper).listRemoteDetailSummary(param, authPO);
//      ReportRemoteDetailVO total = ((ReportOrderInfoMapper)this.baseMapper).getRemoteDetailTotal(param, authPO);
//      return (new ReportBaseTotalVO()).setResultPage(PageVO.of(list)).setTotalLine(total);
//   }
//
//   public ReportBaseTotalVO<ReportRemoteSumVO> pageRemoteSummary(ReportRemoteParam param) {
//      MgrUserAuthPO authPO = this.mgrAuthApi.getUserAuthPO();
//      PageMethod.startPage(param.getPage());
//      List<ReportRemoteSumVO> list = ((ReportOrderInfoMapper)this.baseMapper).listRemoteSummary(param, authPO);
//      ReportRemoteSumVO totalLine = (ReportRemoteSumVO)Optional.ofNullable(((ReportOrderInfoMapper)this.baseMapper).listRemoteSummaryTotal(param, authPO)).orElse(new ReportRemoteSumVO());
//      return (new ReportBaseTotalVO()).setResultPage(PageVO.of(list)).setTotalLine(totalLine);
//   }
}
