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

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.canteen.core.common.enums.SourceTypeEnum;
import com.bonus.canteen.core.common.redis.RedisUtil;
import com.bonus.canteen.core.common.utils.TenantContextHolder;
import com.bonus.canteen.core.device.api.DeviceApi;
import com.bonus.canteen.core.device.manage.controller.deprecated.vo.MacHeartBeatVo;
import com.bonus.canteen.core.device.manage.dto.DeviceSearchDTO;
import com.bonus.canteen.core.device.manage.model.DeviceInfo;
import com.bonus.canteen.core.device.manage.vo.ListDeviceByDishIdVO;
import com.bonus.canteen.core.device.metadata.api.DeviceMetadataApi;
import com.bonus.canteen.core.device.mettadata.model.DeviceMetadataModel;
import com.bonus.canteen.core.menu.api.MenuDishesApi;
import com.bonus.canteen.core.order.deprecated.service.OrdAppInfoService;
import com.bonus.canteen.core.order.deprecated.vo.AppDtlOrdDetailVO;
import com.bonus.canteen.core.order.deprecated.vo.AppPageOrdListVO;
import com.bonus.canteen.core.order.weight.dto.QueryWeighBindDetailDTO;
import com.bonus.canteen.core.order.weight.mapper.MacWeighBindMapper;
import com.bonus.canteen.core.order.weight.model.MacWeighBind;
import com.bonus.canteen.core.order.weight.service.MacWeighBindService;
import com.bonus.canteen.core.order.weight.vo.BuffetBindVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.lang.invoke.SerializedLambda;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

@Service
public class MacWeighBindServiceImpl extends ServiceImpl<MacWeighBindMapper, MacWeighBind> implements MacWeighBindService {
   private static final Logger log = LoggerFactory.getLogger(MacWeighBindServiceImpl.class);
   @Autowired
   @Lazy
   private RedisTemplate redisTemplate;
   @Autowired
   @Lazy
   private DeviceApi deviceApi;
   @Autowired
   @Lazy
   private OrdAppInfoService ordAppInfoService;
   @Autowired
   @Lazy
   private MenuDishesApi menuDishesApi;
   @Autowired
   @Lazy
   private DeviceMetadataApi deviceMetadataApi;

   public List<ListDeviceByDishIdVO> queryDeviceByDishId(Long dishId) {
      Integer customId = this.menuDishesApi.getOneMenuDishes(dishId).getCustomId();
      List<ListDeviceByDishIdVO> deviceInfo = new ArrayList();
      List<DeviceInfo> macMachines = this.deviceApi.listInfo((new DeviceSearchDTO())
              .setDeviceType(SourceTypeEnum.AUTONOMOUS_WEIGHING.getKey()));
      macMachines.forEach((macMachine) -> {
         Object o = this.redisTemplate.opsForValue().get(String.format("yunshitang:%s:heartbase:%s",
                 TenantContextHolder.getTenantId().toString(), macMachine.getDeviceNum()));
         if (!Objects.isNull(o)) {
            MacHeartBeatVo macHeartBeatVo = (MacHeartBeatVo)JSON.parseObject(String.valueOf(o), MacHeartBeatVo.class);
            if (macHeartBeatVo.getMenuNo().equals(customId)) {
               ListDeviceByDishIdVO device = new ListDeviceByDishIdVO();
               device.setDeviceName(macMachine.getDeviceName());
               device.setDeviceNum(macMachine.getDeviceNum());
               deviceInfo.add(device);
            }
         }

      });
      return deviceInfo;
   }

   public List<AppPageOrdListVO> queryWeighBindDetail(String openid, QueryWeighBindDetailDTO param) {
      LocalDateTime minTime = null;
      LocalDateTime maxTime = null;
      if (param.getNowDate() != null) {
         minTime = param.getNowDate().atStartOfDay().with(LocalTime.MIN);
         maxTime = param.getNowDate().atStartOfDay().with(LocalTime.MAX);
      }

      List<AppPageOrdListVO> noDeal = ((MacWeighBindMapper)this.baseMapper).queryWeighBindDetail(openid, param, minTime, maxTime);
      List<AppPageOrdListVO> alreadyDeal = new ArrayList();
      Iterator var7 = noDeal.iterator();

      while(true) {
         AppPageOrdListVO index;
         Integer amount;
         List ordDetailList;
         do {
            do {
               if (!var7.hasNext()) {
                  return alreadyDeal;
               }

               index = (AppPageOrdListVO)var7.next();
               amount = 0;
               ordDetailList = this.ordAppInfoService.getAppDtlOrdDetail(openid, index.getMacOrdId(), param);
            } while(ordDetailList == null);
         } while(ordDetailList.size() == 0);

         index.setTakeOutFlag(5);
         if (index.getCheckState().equals(3)) {
            index.setCheckState(2);
         } else if (index.getCheckState().equals(4)) {
            index.setCheckState(3);
         }

         index.setOrdDetailList(ordDetailList);
         index.setOrdDetailSum(ordDetailList.size());
         AppPageOrdListVO appPageOrdListVO = new AppPageOrdListVO();
         BeanUtils.copyProperties(index, appPageOrdListVO);
         Iterator var12 = ordDetailList.iterator();

         while(var12.hasNext()) {
            AppDtlOrdDetailVO vo = (AppDtlOrdDetailVO)var12.next();
            Integer totalAmount = 0;
            if (vo.getSalesMode().equals(2)) {
               totalAmount = (new BigDecimal(vo.getPrice() * vo.getMenuWeigh() / vo.getWeight())).multiply(index.getDiscount()).intValue();
            } else {
               totalAmount = (new BigDecimal(vo.getPrice() * vo.getQuantity())).multiply(index.getDiscount()).intValue();
            }

            vo.setTotalAmount(totalAmount);
            amount = amount + totalAmount;
            vo.setGoodsRefundNum(vo.getMenuWeigh());
         }

         appPageOrdListVO.setAmount(amount);
         appPageOrdListVO.setNeedPayAmount(amount);
         alreadyDeal.add(appPageOrdListVO);
      }
   }

   public Integer countBindBetweenTimes(LocalDateTime startTime, LocalDateTime endTime) {
      return ((MacWeighBindMapper)this.baseMapper).countBindBetweenTimes(startTime, endTime);
   }

   public Boolean cleanAfterOrderPaid(String macOrdId, String plateSerialNum) {
      log.info("计量主机MQ消费-更新绑盘状态：{}", macOrdId);
      if (ObjectUtil.isEmpty(plateSerialNum)) {
         MacWeighBind macWeighBind = this.getBaseMapper().selectOne(Wrappers.lambdaQuery(MacWeighBind.class)
                 .select(MacWeighBind::getSerialNum).eq(MacWeighBind::getMacOrdId, macOrdId));
         plateSerialNum = ObjectUtil.isNotEmpty(macWeighBind) ? macWeighBind.getSerialNum() : null;
      }

      if (ObjectUtil.isNotEmpty(plateSerialNum)) {
         BuffetBindVo buffetBindVo = (BuffetBindVo) RedisUtil.getObj(String.format("yunshitang:%s:PERSONALBINDORD:%s", TenantContextHolder.getTenantId(), plateSerialNum));
         log.info("计量主机MQ消费-删除绑盘：{} 订单:{}", plateSerialNum, macOrdId);
         DeviceMetadataModel deviceMetadataModel = this.deviceMetadataApi.queryBuffetMetadata();
         if (ObjectUtil.isNotEmpty(buffetBindVo) && macOrdId.equals(buffetBindVo.getMacOrdId()) || ObjectUtil.isNotEmpty(deviceMetadataModel) && "2".equals(deviceMetadataModel.getIfBindplatebeforetakefood())) {
            RedisUtil.delete(String.format("yunshitang:%s:PERSONALBINDORD:%s", TenantContextHolder.getTenantId(), plateSerialNum));
         }
      }

      return ((MacWeighBindMapper)this.baseMapper).updateBindState(macOrdId);
   }
}
