package com.bonus.canteen.core.device.manage.service;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.bonus.canteen.core.common.redis.RedisUtil;
import com.bonus.canteen.core.common.utils.TenantContextHolder;
import com.bonus.canteen.core.device.constants.DeviceOnlineStatusEnum;
import com.bonus.canteen.core.device.manage.controller.deprecated.dto.DeviceHeartBeatDto;
import com.bonus.canteen.core.device.manage.controller.deprecated.vo.MacHeartBeatVo;
import com.bonus.canteen.core.device.manage.controller.deprecated.vo.v2.MacTcpStateVo;
import com.bonus.canteen.core.device.manage.dto.DeviceSendMenuTimeDTO;
import com.bonus.canteen.core.device.manage.dto.DeviceTcpDto;
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.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class DeviceTcpService {
   private static final Logger log = LoggerFactory.getLogger(DeviceTcpService.class);
   @Autowired
   @Lazy
   private RedisTemplate<Object, Object> redisTemplate;

   public List<MacTcpStateVo> status(List<DeviceTcpDto> macNumList) {
      List<MacTcpStateVo> macTcpStateVoList = new ArrayList();
      macNumList.stream().forEach((s) -> {
         MacTcpStateVo macTcpStateVo = new MacTcpStateVo();
         macTcpStateVo.setDeviceNum(s.getDeviceNum());
         Object object = this.redisTemplate.opsForValue().get("yunshitang:merchantId:isonline:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", s.getDeviceNum()));
         if (object != null) {
            macTcpStateVo.setOnlineState(DeviceOnlineStatusEnum.ONLINE_STATUS_ENUM.key());
         }

         Object lastsendtime;
         if ("2".equals(s.getDeviceModel())) {
            lastsendtime = this.redisTemplate.opsForValue().get("yunshitang:merchantId:recipesendtime:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", s.getDeviceNum()));
            if (lastsendtime != null) {
               macTcpStateVo.setLastSendTime(((String)lastsendtime).replaceAll("\"", ""));
            }
         } else {
            lastsendtime = this.redisTemplate.opsForValue().get("yunshitang:merchantId:recipesendtime:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", s.getDeviceNum()));
            if (lastsendtime != null) {
               macTcpStateVo.setLastSendTime(((String)lastsendtime).replaceAll("\"", "").replaceAll("T", " "));
            }
         }

         Object menustate = this.redisTemplate.opsForValue().get("yunshitang:merchantId:menustate:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", s.getDeviceNum()));
         if (menustate != null) {
            macTcpStateVo.setMenuState((Integer)menustate);
         }

         Object recipesendtype = this.redisTemplate.opsForValue().get("yunshitang:merchantId:recipesendtype:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", s.getDeviceNum()));
         if (recipesendtype != null) {
            macTcpStateVo.setRecipeSendType((Integer)recipesendtype);
         }

         Object macip = this.redisTemplate.opsForValue().get("yunshitang:merchantId:macip:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", s.getDeviceNum()));
         if (macip != null) {
            macTcpStateVo.setDeviceIp((String)macip);
         }

         Object o = this.redisTemplate.opsForValue().get(String.format("yunshitang:%s:heartbase:%s", TenantContextHolder.getTenantId().toString(), s.getDeviceNum()));
         if (!Objects.isNull(o)) {
            MacHeartBeatVo macHeartBeatVo = (MacHeartBeatVo)JSON.parseObject(String.valueOf(o), MacHeartBeatVo.class);
            macTcpStateVo.setMenuName(macHeartBeatVo.getMenuName());
            if (macHeartBeatVo.getMenuUpTime() != null) {
               macTcpStateVo.setMenuUpdateTime(macHeartBeatVo.getMenuUpTime());
            }

            macTcpStateVo.setMenuNo(macHeartBeatVo.getMenuNo());
            macTcpStateVo.setAntennaState(macHeartBeatVo.getAntennaState());
            macTcpStateVo.setDeviceVersion(macHeartBeatVo.getDeviceVersion());
         } else if (ObjectUtil.isNotEmpty(s.getDeviceModel()) && s.getDeviceModel().equals("3")) {
            macTcpStateVo.setMenuName("无/无");
         } else {
            macTcpStateVo.setMenuName("无");
         }

         macTcpStateVoList.add(macTcpStateVo);
      });
      return macTcpStateVoList;
   }

   public void updatestate(String deviceIp, List<DeviceHeartBeatDto> deviceTcpDtoList, boolean ismqtt) {
      deviceTcpDtoList.stream().forEach((s) -> {
         this.redisTemplate.opsForValue().set("yunshitang:merchantId:macip:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", s.getMacNo()), deviceIp);
         if (ObjectUtil.isNotEmpty(s.getOnlineState()) && s.getOnlineState().equals(1) && ismqtt) {
            this.redisTemplate.opsForValue().set("yunshitang:merchantId:isonline:macNumber".replace("merchantId", String.valueOf(TenantContextHolder.getTenantId())).replace("macNumber", s.getMacNo()), s.getMacNo(), 60L, TimeUnit.SECONDS);
         } else if (ObjectUtil.isNotEmpty(s.getOnlineState()) && s.getOnlineState().equals(2)) {
            this.redisTemplate.delete("yunshitang:merchantId:isonline:macNumber".replace("merchantId", String.valueOf(TenantContextHolder.getTenantId())).replace("macNumber", s.getMacNo()));
         } else {
            this.redisTemplate.opsForValue().set("yunshitang:merchantId:isonline:macNumber".replace("merchantId", String.valueOf(TenantContextHolder.getTenantId())).replace("macNumber", s.getMacNo()), s.getMacNo());
         }

         Object o = this.redisTemplate.opsForValue().get(String.format("yunshitang:%s:heartbase:%s", TenantContextHolder.getTenantId().toString(), s.getMacNo()));
         MacHeartBeatVo macHeartBeatVo = new MacHeartBeatVo();
         if (ObjectUtil.isNotEmpty(o)) {
            macHeartBeatVo = (MacHeartBeatVo)JSON.parseObject(String.valueOf(o), MacHeartBeatVo.class);
         }

         macHeartBeatVo.setLocalMilliSecond(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
         macHeartBeatVo.setAntennaState(s.getAntennaState());
         macHeartBeatVo.setDeviceVersion(s.getDeviceVersion());
         macHeartBeatVo.setMenuNo(s.getMenuNo());
         macHeartBeatVo.setMenuName(s.getMenuName());
         macHeartBeatVo.setMenuPrice(s.getMenuPrice());
         this.redisTemplate.opsForValue().set(String.format("yunshitang:%s:heartbase:%s", TenantContextHolder.getTenantId().toString(), s.getMacNo()), JSON.toJSONString(macHeartBeatVo));
         DeviceSendMenuTimeDTO deviceSendMenuTimeDTO = (DeviceSendMenuTimeDTO) RedisUtil.getObj(String.format("yunshitang:%s:devicesendtime:%s", TenantContextHolder.getTenantId(), s.getMacNo()));
         if (!ismqtt || ObjectUtil.isEmpty(s.getLocalDateTimeMenuSend()) || ObjectUtil.isNotEmpty(s.getLocalDateTimeMenuSend()) && (ObjectUtil.isEmpty(deviceSendMenuTimeDTO) || LocalDateTimeUtil.between(deviceSendMenuTimeDTO.getLocalDateTimeMenu(), s.getLocalDateTimeMenuSend()).getSeconds() > -2L)) {
            this.redisTemplate.opsForValue().set("yunshitang:merchantId:recipesendtype:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", s.getMacNo()), s.getDeviceSendSuccess());
            if (ObjectUtil.isNotEmpty(s.getLocalDateTimeMenuSend())) {
               this.redisTemplate.opsForValue().set("yunshitang:merchantId:recipesendtime:macNumber".replace("merchantId", TenantContextHolder.getTenantId().toString()).replace("macNumber", s.getMacNo()), s.getLocalDateTimeMenuSend().toString());
            }
         }

      });
   }
}
