package com.bonus.canteen.core.menu.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.bonus.canteen.core.common.enums.AgreeMentEnum;
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.api.DeviceV2Api;
import com.bonus.canteen.core.device.manage.dto.DeviceSendMenuTimeDTO;
import com.bonus.canteen.core.device.manage.vo.DeviceInfoVO;
import com.bonus.canteen.core.menu.api.MenuDishesApi;
import com.bonus.canteen.core.menu.constant.MenuConstant;
import com.bonus.canteen.core.menu.dto.IssueRecipeListDTO;
import com.bonus.canteen.core.menu.dto.IssueRecipeV2DTO;
import com.bonus.canteen.core.menu.dto.MenuSendMacListDto;
import com.bonus.canteen.core.menu.service.MacMenuRecipeService;
import com.bonus.canteen.core.menu.service.MenuRecipeService;
import com.bonus.canteen.core.menu.vo.IssueRecipeCompressVO;
import com.bonus.canteen.core.menu.vo.IssueRecipeResultVO;
import com.bonus.canteen.core.menu.vo.IssueRecipeVO;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.houqin.i18n.I18n;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class MacMenuRecipeServiceImpl implements MacMenuRecipeService {
   private static final Logger log = LoggerFactory.getLogger(MacMenuRecipeServiceImpl.class);
   @Autowired
   @Lazy
   private RedisTemplate redisTemplate;
   @Autowired
   @Lazy
   private MenuRecipeService menuRecipeService;
   @Autowired
   @Lazy
   private MenuDishesApi menuDishesApi;
   @Autowired
   @Lazy
   private DeviceApi deviceApi;
   @Autowired
   @Lazy
   private DeviceV2Api deviceV2Api;

   @Override
   public IssueRecipeResultVO issueRecipeList(IssueRecipeListDTO issueRecipeListDTO) {
      IssueRecipeVO issueRecipeVO = this.getIssueRecipeDetail(issueRecipeListDTO.getRecipeId());
      if (issueRecipeVO == null) {
         return null;
      } else {
         issueRecipeVO.getDateList().forEach((dateList) -> {
            dateList.getIntervalList().forEach((intervalList) -> {
               if (ObjectUtil.isNotEmpty(intervalList.getProductList()) && intervalList.getProductList().size() > 99) {
                  throw new ServiceException(I18n.getMessage("menu_tcp_send_not_allow", new Object[0]));
               }
            });
         });
         List<MenuSendMacListDto> machineNumList = issueRecipeListDTO.getMachineNumList();
         List<String> numList = machineNumList.stream().map(MenuSendMacListDto::getMchNum).collect(Collectors.toList());
         this.deviceApi.updateRecipeByNumList(issueRecipeListDTO.getRecipeId(), numList);
         List<String> machineNumListWait = new ArrayList();
         List<String> machineNumListerror = new ArrayList();
         Iterator var7 = machineNumList.iterator();

         while(true) {
            DeviceInfoVO macMachine;
            do {
               if (!var7.hasNext()) {
                  return (new IssueRecipeResultVO()).setIssueError(machineNumListerror).setIssueWait(machineNumListWait);
               }

               MenuSendMacListDto menuSendMacListDto = (MenuSendMacListDto)var7.next();
               macMachine = this.deviceApi.getDeviceInfoVoBySnCacheable(menuSendMacListDto.getMachineSn());
            } while(macMachine != null && AgreeMentEnum.MQTT.getKey().equals(macMachine.getDeviceAgreement()));

            Object object = this.redisTemplate.opsForValue().get("yunshitang:merchantId:isonline:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", macMachine.getDeviceNum()));
            if (object == null) {
               machineNumListerror.add(macMachine.getDeviceNum());
               this.redisTemplate.opsForValue().set("yunshitang:merchantId:recipesendtype:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", macMachine.getDeviceNum()), 2);
            } else {
               DeviceSendMenuTimeDTO deviceSendMenuTimeDTO = (new DeviceSendMenuTimeDTO()).setLocalDateTimeMenu(LocalDateTime.now());
               RedisUtil.setObj(String.format("yunshitang:%s:devicesendtime:%s", TenantContextHolder.getTenantId(), macMachine.getDeviceNum()), deviceSendMenuTimeDTO);
               machineNumListerror.add(macMachine.getDeviceNum());
               this.redisTemplate.opsForValue().set("yunshitang:merchantId:recipesendtype:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", macMachine.getDeviceNum()), macMachine.getDeviceType().equals(35) ? 2 : 1);
               this.redisTemplate.opsForValue().set(String.format("yunshitang:%s:recipe:%s", TenantContextHolder.getTenantId(), macMachine.getDeviceNum()), JSON.toJSONString(issueRecipeVO), MenuConstant.ISSUE_RECIPE_EXPIRE_MINUTES, TimeUnit.MINUTES);
               this.redisTemplate.opsForValue().set(String.format("yunshitang:%s:recipeid:%s", TenantContextHolder.getTenantId(), macMachine.getDeviceNum()), issueRecipeListDTO.getRecipeId());
               this.redisTemplate.opsForValue().set("yunshitang:merchantId:recipesendtime:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", macMachine.getDeviceNum()), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
            }
         }
      }
   }

//   public IssueRecipeResultVO issueNoRecipeList(IssueRecipeListDTO issueRecipeListDTO) {
//      List<String> machineNumListWait = new ArrayList();
//      List<String> machineNumListerror = new ArrayList();
//      List<String> numList = (List)issueRecipeListDTO.getMachineNumList().stream().map(MenuSendMacListDto::getMchNum).collect(Collectors.toList());
//      List<DeviceInfoVO> deviceInfoVOList = this.deviceV2Api.getDeviceInfoVoByNumList(numList);
//      Map<Long, List<DeviceInfoVO>> recipeMap = (Map)deviceInfoVOList.stream().filter((s) -> {
//         return ObjectUtil.isNotEmpty(s.getFirstRecipeId());
//      }).collect(Collectors.groupingBy(DeviceInfoVO::getFirstRecipeId));
//      recipeMap.forEach((k, v) -> {
//         IssueRecipeVO issueRecipeVO = this.getIssueRecipeDetail(k);
//         IssueRecipeCompressVO issueRecipeCompressVO = this.getIssueRecipeDetailCompress(k);
//         v.stream().forEach((macMachine) -> {
//            if (macMachine != null && AgreeMentEnum.MQTT.getKey().equals(macMachine.getDeviceAgreement())) {
//               this.redisTemplate.opsForValue().set("yunshitang:merchantId:recipesendtype:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", macMachine.getDeviceNum()), 3);
//               MacMessage.distributeRecipe(issueRecipeCompressVO, macMachine.getDeviceSn());
//            } else {
//               Object object = this.redisTemplate.opsForValue().get("yunshitang:merchantId:isonline:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", macMachine.getDeviceNum()));
//               if (object == null) {
//                  machineNumListerror.add(macMachine.getDeviceNum());
//                  this.redisTemplate.opsForValue().set("yunshitang:merchantId:recipesendtype:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", macMachine.getDeviceNum()), 2);
//               } else {
//                  DeviceSendMenuTimeDTO deviceSendMenuTimeDTO = (new DeviceSendMenuTimeDTO()).setLocalDateTimeMenu(LocalDateTime.now());
//                  RedisUtil.setObj(String.format("yunshitang:%s:devicesendtime:%s", TenantContextHolder.getTenantId(), macMachine.getDeviceNum()), deviceSendMenuTimeDTO);
//                  machineNumListerror.add(macMachine.getDeviceNum());
//                  this.redisTemplate.opsForValue().set("yunshitang:merchantId:recipesendtype:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", macMachine.getDeviceNum()), macMachine.getDeviceType().equals(35) ? 2 : 1);
//                  this.redisTemplate.opsForValue().set(String.format("yunshitang:%s:recipe:%s", TenantContextHolder.getTenantId(), macMachine.getDeviceNum()), JSON.toJSONString(issueRecipeVO), MenuConstant.ISSUE_RECIPE_EXPIRE_MINUTES, TimeUnit.MINUTES);
//                  this.redisTemplate.opsForValue().set(String.format("yunshitang:%s:recipeid:%s", TenantContextHolder.getTenantId(), macMachine.getDeviceNum()), macMachine.getFirstRecipeId());
//                  this.redisTemplate.opsForValue().set("yunshitang:merchantId:recipesendtime:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", macMachine.getDeviceNum()), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
//               }
//            }
//
//         });
//      });
//      return (new IssueRecipeResultVO()).setIssueError(machineNumListerror).setIssueWait(machineNumListWait);
//   }

   private IssueRecipeVO getIssueRecipeDetail(Long recipeId) {
      IssueRecipeV2DTO issueRecipeV2DTO = new IssueRecipeV2DTO();
      LocalDate startDate = LocalDate.now();
      LocalDate endDate = startDate.plusDays(6L);
      issueRecipeV2DTO.setRecipeId(recipeId);
      issueRecipeV2DTO.setBeginDate(startDate);
      issueRecipeV2DTO.setEndDate(endDate);

      try {
         return this.menuDishesApi.issueRecipeV2(issueRecipeV2DTO);
      } catch (Exception var6) {
         log.info(var6.getMessage());
         return null;
      }
   }

   private IssueRecipeCompressVO getIssueRecipeDetailCompress(Long recipeId) {
      IssueRecipeV2DTO issueRecipeV2DTO = new IssueRecipeV2DTO();
      LocalDate startDate = LocalDate.now();
      LocalDate endDate = startDate.plusDays(6L);
      issueRecipeV2DTO.setRecipeId(recipeId);
      issueRecipeV2DTO.setBeginDate(startDate);
      issueRecipeV2DTO.setEndDate(endDate);

      try {
         return this.menuRecipeService.issueRecipeV2Compress(issueRecipeV2DTO);
      } catch (Exception var6) {
         log.info(var6.getMessage());
         return null;
      }
   }
}
