package com.bonus.canteen.core.order.deprecated.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bonus.canteen.core.account.v3.api.vo.AccInfoDetailVO;
import com.bonus.canteen.core.account.v3.api.vo.AccInfoServiceV3Api;
import com.bonus.canteen.core.account.v4.api.CardInfoServiceV4Api;
import com.bonus.canteen.core.common.page.PageDTO;
import com.bonus.canteen.core.common.page.PageVO;
import com.bonus.canteen.core.common.utils.LogUtil;
import com.bonus.canteen.core.customer.vo.CustPayVO;
import com.bonus.canteen.core.device.api.DeviceApi;
import com.bonus.canteen.core.device.manage.vo.DeviceInfoVO;
import com.bonus.canteen.core.menu.model.AllocMealtimeModel;
import com.bonus.canteen.core.order.android.dto.MacOrderImageSaveDTO;
import com.bonus.canteen.core.order.client.OrderModuleClient;
import com.bonus.canteen.core.order.client.po.CustPayInfoQueryParam;
import com.bonus.canteen.core.order.client.po.MealtimeCheckNowParam;
import com.bonus.canteen.core.order.client.po.MealtimeQueryParam;
import com.bonus.canteen.core.order.common.constants.OrderStateEnum;
import com.bonus.canteen.core.order.common.model.OrderInfo;
import com.bonus.canteen.core.order.common.service.OrderDetailService;
import com.bonus.canteen.core.order.common.service.OrderInfoService;
import com.bonus.canteen.core.order.common.vo.OrderDetailVO;
import com.bonus.canteen.core.order.deprecated.constants.OrderStateOldEnum;
import com.bonus.canteen.core.order.deprecated.dto.MacOrdRefundQueryDTO;
import com.bonus.canteen.core.order.deprecated.dto.MacQueryOrdByMacOrdIdDTO;
import com.bonus.canteen.core.order.deprecated.dto.OrdInfoMachineDto;
import com.bonus.canteen.core.order.deprecated.dto.OrdLeCodeDTO;
import com.bonus.canteen.core.order.deprecated.param.MacOrdParam;
import com.bonus.canteen.core.order.deprecated.service.MacOrdBusiness;
import com.bonus.canteen.core.order.deprecated.service.OrdAppInfoService;
import com.bonus.canteen.core.order.deprecated.vo.*;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.houqin.constant.RetCodeEnum;
import com.bonus.common.houqin.utils.LeBeanUtil;
import com.bonus.canteen.core.order.mq.OrderMessageSend;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MacOrdBusinessImpl implements MacOrdBusiness {
   private static final Logger log = LoggerFactory.getLogger(MacOrdBusinessImpl.class);
   @Autowired
   @Lazy
   private AccInfoServiceV3Api accInfoServiceV3Api;
   @Autowired
   @Lazy
   private CardInfoServiceV4Api accCardServiceApi;
   @Autowired
   @Lazy
   private DeviceApi deviceApi;
   @Autowired
   @Lazy
   private OrderModuleClient orderModuleClient;
   @Lazy
   @Autowired
   private OrderInfoService orderInfoService;
   @Lazy
   @Autowired
   private OrderDetailService orderDetailService;
   @Lazy
   @Autowired
   private OrdAppInfoService ordAppInfoService;

   public List<OrdAssignSrcMacVO> queryAssignSourceOrd(MacOrdParam macOrdParam, String machineSn) {
      log.info("[设备查询订单]:入参{}", JSON.toJSONString(macOrdParam));
      macOrdParam.setSourceTypeList((List)null);
      macOrdParam.setLocaldate(LocalDate.now());
      if (ObjectUtil.isNotEmpty(macOrdParam.getSerialNum())) {
         macOrdParam.setCustId(this.accCardServiceApi.queryCustIdBySerialNum(macOrdParam.getSerialNum()));
      }

      return this.listAssignSourceOrd(macOrdParam);
   }

   private List<OrdAssignSrcMacVO> listAssignSourceOrd(MacOrdParam macOrdParam) {
      LogUtil.info("设备查询指定来源的订单", macOrdParam);

      try {
         if (StrUtil.isNotBlank(macOrdParam.getAuthCode())) {
            String leniucode = macOrdParam.getAuthCode().substring(4);
            OrdLeCodeDTO ordLeCodeDto = (OrdLeCodeDTO)JSON.parseObject(leniucode, OrdLeCodeDTO.class);
            Long ordId = ordLeCodeDto.getP();
            OrderInfo orderInfo = this.orderInfoService.checkAndGetOrderInfo(ordId);
            macOrdParam.setCustId(orderInfo.getCustId());
         }
      } catch (Exception var10) {
         throw new ServiceException("请扫码订单码", RetCodeEnum.CORE_PARAM_ERROR.getKey());
      }

      DeviceInfoVO macMachine = this.deviceApi.getDeviceInfoVoBySnCacheable(macOrdParam.getMachineSn());
      if (ObjectUtil.isNotNull(macOrdParam.getQueryTime())) {
         AllocMealtimeModel mealtimeModel = this.orderModuleClient.mealtimeQuery(MealtimeQueryParam.ofAssignTime(macOrdParam.getQueryTime(), macMachine.getFirstCanteenId(), macMachine.getFirstShopstallId()));
         if (ObjectUtil.isNull(mealtimeModel)) {
            throw new ServiceException("不在就餐时间段内", RetCodeEnum.MENU_NOT_IN_TIME_INTERVAL.getKey());
         }

         macOrdParam.setMealtimeType(mealtimeModel.getMealtimeType());
      }

      if (ObjectUtil.isNull(macOrdParam.getOrdState())) {
         macOrdParam.setNotOrdState(OrderStateOldEnum.REFUND.getKey());
      }

      Long custId = macOrdParam.getCustId();
      if (!ObjectUtil.isNull(custId) && custId > 0L) {
         if (OrderStateOldEnum.COMPLETE.getKey().equals(macOrdParam.getOrdState())) {
            macOrdParam.setOrdState(OrderStateEnum.FINISH.getKey());
         } else {
            macOrdParam.setOrdState(OrderStateEnum.PLACE.getKey());
         }

         List<OrdAssignSrcMacVO> ordMacVOList = this.ordAppInfoService.getOrderListForAndroid(macOrdParam);
         if (CollectionUtil.isEmpty(ordMacVOList)) {
            ordMacVOList = new ArrayList();
         }

         List<OrdAssignSrcMacVO> ordShopList = this.ordAppInfoService.getOrderShopListForAndroid(macOrdParam);
         if (CollectionUtil.isNotEmpty(ordShopList)) {
            ordMacVOList.addAll(ordShopList);
         }

         if (CollectionUtil.isNotEmpty(ordMacVOList)) {
            List<OrdMacDtlVO> ordDetailList =this.orderDetailService.getOrderDetailList(ordMacVOList
                    .stream().map(OrdAssignSrcMacVO::getOrdId).collect(Collectors.toList()),
                    ordMacVOList.stream().map(OrdAssignSrcMacVO::getOrdGoodsDate)
                            .collect(Collectors.toList())).stream().map(OrdMacDtlVO::of).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(ordDetailList)) {
               Map<Long, List<OrdMacDtlVO>> detailMap = ordDetailList.stream().collect(Collectors
                       .groupingBy(OrdMacDtlVO::getOrderId));
               Iterator var8 = ((List)ordMacVOList).iterator();

               while(var8.hasNext()) {
                  OrdAssignSrcMacVO temp = (OrdAssignSrcMacVO)var8.next();
                  temp.setOrdDetailList((List)detailMap.get(temp.getOrdId()));
               }
            }
         }

         return (List)ordMacVOList;
      } else {
         log.info("***[订单核销]_为查询到人员信息*****************************");
         return Lists.newArrayList();
      }
   }

   public OrdCurrentReserveMacVO getCurrentReserve(MacOrdParam macOrdParam) {
      DeviceInfoVO macMachine = this.deviceApi.getDeviceInfoVoBySnCacheable(macOrdParam.getMachineSn());
      AllocMealtimeModel mealtime = this.orderModuleClient.mealtimeCheckNow(MealtimeCheckNowParam.of(macMachine.getFirstCanteenId(), macMachine.getFirstShopstallId()));
      macOrdParam.setIntervalId(mealtime.getMealtimeId());
      if (ObjectUtil.isEmpty(macOrdParam.getCustId())) {
         Long custId = this.accCardServiceApi.queryCustIdBySerialNum(macOrdParam.getSerialNum());
         if (ObjectUtil.isNull(custId)) {
            throw new ServiceException("查询不到对应人员信息", RetCodeEnum.CORE_PARAM_ERROR.getKey());
         }

         macOrdParam.setCustId(custId);
      }

      macOrdParam.setLocaldate(LocalDate.now());
      macOrdParam.setOrdState(OrderStateEnum.PLACE.getKey());
      if (OrderStateOldEnum.COMPLETE.getKey().equals(macOrdParam.getOrdState())) {
         macOrdParam.setOrdState(OrderStateEnum.FINISH.getKey());
      } else {
         macOrdParam.setOrdState(OrderStateEnum.PLACE.getKey());
      }

      OrdCurrentReserveMacVO reserveMacVO = this.ordAppInfoService.getReserveOrderListForAndroid(macOrdParam);
      if (ObjectUtil.isNotNull(reserveMacVO)) {
         List<OrdMacDtlVO> ordDetailList = this.orderDetailService.getOrderDetailList(CollUtil
                 .toList(reserveMacVO.getOrdId()), CollUtil.toList(reserveMacVO.getOrderDate()))
                 .stream().map(OrdMacDtlVO::of).collect(Collectors.toList());
         reserveMacVO.setOrdDetailList(ordDetailList);
      } else {
         reserveMacVO = new OrdCurrentReserveMacVO();
      }

      CustPayVO custInfo = this.orderModuleClient.custPayInfoQuery(CustPayInfoQueryParam.ofCustId(macOrdParam.getCustId()));
      if (ObjectUtil.isNotNull(custInfo)) {
         reserveMacVO.setCustName(custInfo.getCustName());
         reserveMacVO.setOrgFullName(custInfo.getOrgFullName());
      }

      return reserveMacVO;
   }

   public AjaxResult queryOrdInfoByMacOrdId(MacQueryOrdByMacOrdIdDTO queryDto) {
      this.deviceApi.getAndCheckMachineBySn(queryDto.getMachineSn());
      OrderInfo orderInfo = this.orderInfoService.checkAndGetOrderInfoByMacOrderId(queryDto.getMacOrdId());
      CustPayVO custInfo = this.orderModuleClient.custPayInfoQuery(CustPayInfoQueryParam.ofCustId(orderInfo.getCustId()));
      if (custInfo == null) {
         log.error("[设备]根据设备订单号查询订单信息,没有查询到人员信息,ordId:" + orderInfo.getOrderId());
         return AjaxResult.error(RetCodeEnum.CUST_PERSONAL_NO_EXIT.getKey(), RetCodeEnum.CUST_PERSONAL_NO_EXIT.getDesc());
      } else {
         AccInfoDetailVO accInfoDetail = this.accInfoServiceV3Api.getAccInfoDetail(custInfo.getCustId());
         if (ObjectUtil.isNull(accInfoDetail)) {
            log.error("[设备]根据设备订单号查询订单信息,没有查询到账户信息,ordId:" + orderInfo.getOrderId());
            return AjaxResult.error(RetCodeEnum.CUST_PERSONAL_NO_EXIT.getKey(), RetCodeEnum.CUST_PERSONAL_NO_EXIT.getDesc());
         } else {
            MacQueryOrdByMacOrdIdVO macOrdVO = new MacQueryOrdByMacOrdIdVO();
            macOrdVO.setCustName(custInfo.getCustName());
            macOrdVO.setCustNum(custInfo.getCustNum());
            macOrdVO.setOrgFullName(custInfo.getOrgFullName());
            macOrdVO.setCustPhotoUrl(custInfo.getCustPhotoUrl());
            macOrdVO.setWalletBal(accInfoDetail.getWalletBal().intValue());
            macOrdVO.setSubsidyBal(accInfoDetail.getSubsidyBal().intValue());
            macOrdVO.setAccBal(accInfoDetail.getAccBalTotal().intValue());
            macOrdVO.setRedEnvelope(accInfoDetail.getRedEnvelope().intValue());
            macOrdVO.setRealAmount(orderInfo.getRealAmount().intValue());
            return AjaxResult.success(macOrdVO);
         }
      }
   }

   public PageVO<QueryOrdTradeForAppVO> queryCustTradePageList(OrdInfoMachineDto ordInfoMachineDto, PageDTO page) {
      Page<QueryOrdTradeForAppVO> pageResult = new Page();
      PageDTO.startPage(page);
      List<OrderInfo> ordAppInfoList = this.orderInfoService.listCustOrder(ordInfoMachineDto.getCustId(), null, null, (List)null, (List)null);
      if (CollectionUtils.isNotEmpty(ordAppInfoList)) {
         List<Long> orderIds = ordAppInfoList.stream().map(OrderInfo::getOrderId).collect(Collectors.toList());
         List<LocalDate> dateList = ordAppInfoList.stream().map(OrderInfo::getOrderDate).collect(Collectors.toList());
         Map<Long, List<OrderDetailVO>> detailVOGroupByOrderIdList = this.orderDetailService.getDetailVOGroupByOrderIdList(orderIds, dateList);
         List<QueryOrdTradeForAppVO> ordTradelist = ordAppInfoList.stream().map((map) -> {
            QueryOrdTradeForAppVO tradeForAppVO = LeBeanUtil.copyCreateProperties(map, QueryOrdTradeForAppVO.class);
            tradeForAppVO.setOrdId(map.getOrderId());
            tradeForAppVO.setIntervalName(map.getMealtimeName());
            tradeForAppVO.setShopstallName(map.getStallName());
            tradeForAppVO.setOrderDetailList(detailVOGroupByOrderIdList.getOrDefault(map.getOrderId(), Lists.newArrayList()));
            return tradeForAppVO;
         }).collect(Collectors.toList());
         pageResult.setRecords(ordTradelist);
         return PageVO.of(ordAppInfoList, ordTradelist);
      } else {
         return PageVO.empty();
      }
   }

   public List<OrdAssignSrcMacOldVO> queryOrdListBySn(MacOrdRefundQueryDTO ordRefundQueryDTO) {
      List<OrdAssignSrcMacOldVO> orderList = this.ordAppInfoService.queryOrdListBySn(ordRefundQueryDTO);
      if (CollectionUtil.isNotEmpty(orderList)) {
         Map<Long, List<OrdMacDtlVO>> detailGroup = this.orderDetailService.getOrderDetailList(orderList.stream()
                 .map(OrdAssignSrcMacOldVO::getOrdId).collect(Collectors.toList()),
                 orderList.stream().map(OrdAssignSrcMacOldVO::getOrdGoodsDate)
                         .collect(Collectors.toList())).stream().map(OrdMacDtlVO::of)
                 .collect(Collectors.groupingBy(OrdMacDtlVO::getOrderId));
         Iterator var4 = ((List)orderList).iterator();

         while(var4.hasNext()) {
            OrdAssignSrcMacOldVO temp = (OrdAssignSrcMacOldVO)var4.next();
            temp.setOrdDetailList(detailGroup.getOrDefault(temp.getOrdId(), CollUtil.newArrayList(new OrdMacDtlVO[0])));
         }
      } else {
         orderList = new ArrayList();
      }

      return orderList;
   }

   public void orderImageSave(List<MacOrderImageSaveDTO> dtoList) {
      OrderMessageSend.orderV3AsyncImageSave(dtoList);
   }
}
