package com.bonus.canteen.core.device.api;

import com.bonus.canteen.core.device.manage.controller.deprecated.dto.MacApiUSelectDto;
import com.bonus.canteen.core.device.manage.controller.deprecated.vo.MacMachineApiVO;
import com.bonus.canteen.core.device.manage.dto.DeviceSearchDTO;
import com.bonus.canteen.core.device.manage.model.DeviceBind;
import com.bonus.canteen.core.device.manage.model.DeviceInfo;
import com.bonus.canteen.core.device.manage.service.DeviceBindService;
import com.bonus.canteen.core.device.manage.service.DeviceInfoService;
import com.bonus.canteen.core.device.manage.service.DeviceLockerService;
import com.bonus.canteen.core.device.manage.vo.DeviceInfoVO;
import com.bonus.canteen.core.device.utils.DeviceDtoConverter;
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.util.List;

@Service
public class DeviceApi {
   private static final Logger log = LoggerFactory.getLogger(DeviceApi.class);
   @Autowired
   @Lazy
   private DeviceInfoService deviceInfoService;
   @Autowired
   @Lazy
   private DeviceBindService deviceBindService;
//   @Autowired
//   @Lazy
//   private DeviceLockerCabinetService deviceLockerCabinetService;
   @Autowired
   @Lazy
   private DeviceLockerService deviceLockerService;
//   @Autowired
//   @Lazy
//   private DeviceRecipeService deviceRecipeService;
//   @Autowired
//   @Lazy
//   private MenuRecipeApi menuRecipeApi;
//   @Autowired
//   @Lazy
//   private AllocCanteenApi allocCanteenApi;
//   @Autowired
//   @Lazy
//   private MacMenuRecipeService macMenuRecipeService;
//   @Autowired
//   @Lazy
//   private DeviceMenuService deviceMenuService;
//   @Resource(
//      name = "yunshitangTaskExecutor"
//   )
//   AsyncTaskExecutor asyncTaskExecutor;
//
//   public void updateOrdIdAndMealCode(Long ordId, Integer mealCode, Integer lockerStatus, Long deviceId, Integer lockerNum) {
//      this.deviceLockerService.updateOrdIdAndMealCode(ordId, mealCode, lockerStatus, deviceId, lockerNum);
//   }
//
//   public void updateRecipeByCanteenOrStall(MacApiUpdateRepiceDto macApiUpdateRepiceDto) {
//      if (macApiUpdateRepiceDto != null && macApiUpdateRepiceDto.getRecipeId() != null) {
//         this.deviceInfoService.updateRecipeByCanteenOrStall(macApiUpdateRepiceDto.getCanteenId(), macApiUpdateRepiceDto.getShopstallId(), macApiUpdateRepiceDto.getRecipeId());
//      } else {
//         throw new LeException("缺少必传参数");
//      }
//   }
//
//   public void editDeviceRecipe(MenuRecipeMachineChangeDTO menuRecipeMachineChangeDTO) {
//      this.deviceInfoService.editMacRecipe(menuRecipeMachineChangeDTO);
//   }
//
//   public void updateRecipeByNumList(Long recipeId, List<String> numList) {
//      if (!CollUtil.isEmpty(numList)) {
//         List<DeviceInfo> deviceInfoList = this.deviceInfoService.list((new DeviceSearchDTO()).setDeviceNumList(numList));
//         List<DeviceFullInfoVO> deviceFullInfoVOList = this.deviceInfoService.fillFullVo(deviceInfoList);
//         if (!CollUtil.isEmpty(deviceInfoList)) {
//            MenuRecipe menuRecipe = this.menuRecipeApi.getById(recipeId);
//            MenuRecipeMachineChangeDTO dto = new MenuRecipeMachineChangeDTO();
//            if (menuRecipe != null) {
//               dto.setCanteenId(menuRecipe.getCanteenId());
//               dto.setShopstallId(menuRecipe.getStallId());
//            }
//
//            dto.setRecipeId(recipeId);
//            dto.setMachineIdList(deviceFullInfoVOList.stream().map(DeviceFullInfoVO::getDeviceId).toList());
//            this.deviceInfoService.editMacRecipe(dto);
//         }
//      }
//   }
//
//   public void updateRecipeByCanteeStallMeal(Long recipeId, Long canteenId, Long stallId, Long mealLineId, List<Integer> deviceTypeList) {
//      String currentTraceId = LogUtil.getCurrentTraceId();
//      this.asyncTaskExecutor.execute(() -> {
//         LogUtil.putLogTraceId(currentTraceId);
//         if (!ObjectUtil.isEmpty(deviceTypeList)) {
//            DeviceSearchDTO deviceSearchDTO = new DeviceSearchDTO();
//            deviceSearchDTO.setCanteenId(canteenId);
//            deviceSearchDTO.setStallId(stallId);
//            deviceSearchDTO.setMealLineId(mealLineId);
//            deviceSearchDTO.setDeviceTypeList(deviceTypeList);
//            List<DeviceInfo> deviceInfoList = this.deviceInfoService.list(deviceSearchDTO);
//            List<DeviceFullInfoVO> deviceFullInfoVOList = this.deviceInfoService.fillFullVo(deviceInfoList);
//            MenuRecipeMachineChangeDTO dto = new MenuRecipeMachineChangeDTO();
//            dto.setCanteenId(canteenId);
//            dto.setShopstallId(stallId);
//            dto.setRecipeId(recipeId);
//            dto.setMealLineId(mealLineId);
//            dto.setMachineIdList(deviceFullInfoVOList.stream().map(DeviceFullInfoVO::getDeviceId).toList());
//            this.deviceInfoService.editMacRecipeBydevice(dto);
//            deviceInfoList.forEach((s) -> {
//               DeviceMqMessage.deviceUpdateMenuConfigV4(s.getDeviceSn());
//            });
//            if (deviceTypeList.contains(SourceTypeEnum.AUTONOMOUS_WEIGHING.getKey()) || deviceTypeList.contains(SourceTypeEnum.PRODUCTION.getKey())) {
//               IssueRecipeListDTO issueRecipeListDTO = new IssueRecipeListDTO();
//               issueRecipeListDTO.setRecipeId(recipeId);
//               issueRecipeListDTO.setMachineNumList(deviceInfoList.stream().map(MenuSendMacListDto::of).toList());
//               this.macMenuRecipeService.issueRecipeList(issueRecipeListDTO);
//            }
//
//         }
//      });
//   }
//
//   public void deleteRecipeByCanteeStallMeal(Long recipeId, Long canteenId, Long stallId, Long mealLineId, List<Integer> deviceTypeList) {
//      String currentTraceId = LogUtil.getCurrentTraceId();
//      this.asyncTaskExecutor.execute(() -> {
//         LogUtil.putLogTraceId(currentTraceId);
//         if (!ObjectUtil.isEmpty(deviceTypeList)) {
//            DeviceSearchDTO deviceSearchDTO = new DeviceSearchDTO();
//            deviceSearchDTO.setCanteenId(canteenId);
//            deviceSearchDTO.setStallId(stallId);
//            deviceSearchDTO.setMealLineId(mealLineId);
//            deviceSearchDTO.setDeviceTypeList(deviceTypeList);
//            List<DeviceInfo> deviceInfoList = this.deviceInfoService.list(deviceSearchDTO);
//            List<DeviceFullInfoVO> deviceFullInfoVOList = this.deviceInfoService.fillFullVo(deviceInfoList);
//            MenuRecipeMachineChangeDTO dto = new MenuRecipeMachineChangeDTO();
//            dto.setCanteenId(canteenId);
//            dto.setShopstallId(stallId);
//            dto.setRecipeId(recipeId);
//            dto.setMealLineId(mealLineId);
//            dto.setMachineIdList(deviceFullInfoVOList.stream().map(DeviceFullInfoVO::getDeviceId).toList());
//            this.deviceInfoService.deleteMacRecipeBydevice(dto);
//            deviceInfoList.forEach((s) -> {
//               DeviceMqMessage.deviceUpdateMenuConfigV4(s.getDeviceSn());
//            });
//         }
//      });
//   }
//
//   public void sendMenuByCanteen(Long recipeId, List<MenuSendByDTO> menuSendByDTOS) {
//      String currentTraceId = LogUtil.getCurrentTraceId();
//      this.asyncTaskExecutor.execute(() -> {
//         LogUtil.putLogTraceId(currentTraceId);
//         this.deviceMenuService.sendMenuByCanteen(recipeId, menuSendByDTOS);
//      });
//   }
//
//   public void updatePwdBySn(String deviceSn, String devicePwd) {
//      this.deviceInfoService.updatePwdBySn(deviceSn, devicePwd);
//   }
//
//   public void updateDataStatusBySn(String deviceSn, Integer dataStatus) {
//      this.deviceInfoService.updateDataStatusBySn(deviceSn, dataStatus);
//   }
//
//   public void updateTerminalKeyByDeviceSn(String deviceSn, String terminalKey) {
//      this.deviceInfoService.updateTerminalKeyByDeviceSn(deviceSn, terminalKey);
//   }
//
//   public void updateMachineMqttOnlineState(String deviceSn, Integer state, Integer versionCode, String versionName) {
//      this.deviceInfoService.updateMachineMqttOnlineState(deviceSn, state, versionCode, versionName);
//   }
//
//   public DeviceInfoVO getDeviceInfoVoBySn(String deviceSn) {
//      return this.deviceInfoService.getDeviceInfoVoBySn(deviceSn);
//   }
//
//   public DeviceInfo getAndCheckMachineBySn(String machineSn) {
//      DeviceInfo macMachine = this.getBySn(machineSn);
//      if (null == macMachine) {
//         log.error("[设备]没查询到设备信息,machineSn:" + machineSn);
//         throw new LeException("没查询到对应设备信息");
//      } else {
//         return macMachine;
//      }
//   }
//
//   public DeviceInfo getById(Long deviceId) {
//      return this.deviceInfoService.getById(deviceId);
//   }

   public DeviceInfo getBySn(String deviceSn) {
      return this.deviceInfoService.getBySn(deviceSn);
   }
//
//   public DeviceInfo getByNum(String deviceNum) {
//      return this.deviceInfoService.getByNum(deviceNum);
//   }
//
//   public List<DeviceInfo> getByNumList(List<String> deviceNumList) {
//      return this.deviceInfoService.getByNumList(deviceNumList);
//   }
//
//   public DeviceInfo getDeviceInfoBySnCacheable(String deviceSn) {
//      return this.deviceInfoService.getDeviceInfoBySnCacheable(deviceSn);
//   }
//
//   public DeviceInfoVO getDeviceInfoVoBySnCacheable(String deviceSn) {
//      return this.deviceInfoService.getDeviceInfoVoBySnCacheable(deviceSn);
//   }
//
//   public DeviceInfoVO getDeviceInfoVoByNumCacheable(String deviceNum) {
//      DeviceInfo deviceInfo = this.getByNum(deviceNum);
//      return deviceNum == null ? null : this.deviceInfoService.getDeviceInfoVoBySnCacheable(deviceInfo.getDeviceSn());
//   }
//
//   public Long getFirstCanteenIdBySn(String deviceSn) {
//      DeviceInfoVO deviceInfo = this.deviceInfoService.getDeviceInfoVoBySn(deviceSn);
//      return deviceInfo == null ? null : deviceInfo.getFirstCanteenId();
//   }
//
//   public Long getFirstRecipeIdBySn(String deviceSn) {
//      DeviceInfo deviceInfo = this.deviceInfoService.getBySn(deviceSn);
//      if (deviceInfo == null) {
//         return null;
//      } else {
//         List<DeviceRecipe> deviceRecipes = this.deviceRecipeService.listByDeviceIds(CollUtil.toList(new Long[]{deviceInfo.getDeviceId()}));
//         return CollUtil.isNotEmpty(deviceRecipes) ? ((DeviceRecipe)deviceRecipes.get(0)).getRecipeId() : null;
//      }
//   }
//
//   public List<Long> listRecipeIdsByDeviceType(Integer deviceType) {
//      List<DeviceInfo> deviceList = this.deviceInfoService.list((new DeviceSearchDTO()).setDeviceType(deviceType));
//      if (CollUtil.isEmpty(deviceList)) {
//         return CollUtil.newArrayList(new Long[0]);
//      } else {
//         List<DeviceRecipe> deviceRecipes = this.deviceRecipeService.listByDeviceIds(deviceList.stream().map(DeviceInfo::getDeviceId).toList());
//         return (List)deviceRecipes.stream().map(DeviceRecipe::getRecipeId).filter(Objects::nonNull).collect(Collectors.toList());
//      }
//   }

   public List<DeviceInfo> listInfo(DeviceSearchDTO param) {
      return this.deviceInfoService.list(param);
   }

//   public List<DeviceInfo> listInfoBySns(Collection<String> deviceSnList) {
//      return (List)(CollUtil.isEmpty(deviceSnList) ? CollUtil.newArrayList(new DeviceInfo[0]) : this.listInfo((new DeviceSearchDTO()).setDeviceSnList(deviceSnList)));
//   }
//
//   public List<DeviceInfo> listInfoByNames(Collection<String> deviceNameList) {
//      return this.deviceInfoService.listByNames(deviceNameList);
//   }
//
//   public List<DeviceInfo> listInfoByCanteenAndShopstall(Long canteeId, Long shopstallId, Integer deviceType) {
//      List<Long> shopstallIdList = new ArrayList();
//      shopstallIdList.add(LeConstants.DATA_DEFAULT_LONG);
//      if (ObjectUtil.isNotNull(shopstallId) && !LeConstants.DATA_DEFAULT_LONG.equals(shopstallId)) {
//         shopstallIdList.add(shopstallId);
//      }
//
//      DeviceSearchDTO param = (new DeviceSearchDTO()).setDeviceType(deviceType).setCanteenId(canteeId).setStallIdList(shopstallIdList);
//      return this.deviceInfoService.list(param);
//   }
//
//   public DeviceLocker getLockerByDeviceIdAndNum(Long deviceId, Integer lockerNum) {
//      return this.deviceLockerService.getByDeviceIdAndNum(deviceId, lockerNum);
//   }
//
//   public Integer getLockerMealCodeByOrdId(Long ordId) {
//      return this.deviceLockerService.selectMealCodeByOrdId(ordId);
//   }

   public List<DeviceBind> listBindByDeviceSn(String deviceSn) {
      return this.deviceBindService.listBySn(deviceSn);
   }

//   public List<DeviceBind> listBindByDeviceType(Integer deviceType) {
//      return this.deviceBindService.listByType(deviceType);
//   }
//
//   public List<CustomShopstallVO> listCustomShopstallVoByDeviceId(Long deviceId) {
//      List<DeviceBindVO> deviceBindVoList = this.deviceBindService.listVoByDeviceId(deviceId);
//      List<DeviceRecipeVO> deviceRecipeVOList = this.deviceRecipeService.listVoByDeviceIds(CollUtil.toList(new Long[]{deviceId}));
//      return DeviceDtoConverter.toCustomShopstallVO(deviceBindVoList, deviceRecipeVOList);
//   }
//
//   public boolean existsByCanteenId(Long canteenId) {
//      return this.deviceBindService.existsByCanteenId(canteenId);
//   }
//
//   public boolean existsByShopstallId(Long shopstall) {
//      return this.deviceBindService.existsByStallId(shopstall);
//   }

   public Integer getMaxOrdNum(Long deviceId, Integer deviceType) {
      return this.deviceInfoService.getMaxOrdNum(deviceId, deviceType);
   }
//
//   public Integer getLockerNum(Long deviceId) {
//      return this.deviceLockerCabinetService.getLockerNum(deviceId);
//   }
//
//   public void increaseOpenTime(Long ordId, Integer counterNum) {
//      this.deviceLockerService.increaseOpenTime(ordId, counterNum);
//   }
//
//   public List<Integer> listWaitLockerNum(String machineSn, Long custId) {
//      return this.deviceLockerService.listWaitLockerNum(custId, machineSn);
//   }
//
//   public List<DeviceLocker> listLocker(DeviceLockerSearchDTO param) {
//      return this.deviceLockerService.list(param);
//   }
//
//   public Integer getMinOpenableLocker(Long deviceId) {
//      return this.deviceLockerService.getMinOpenableLocker(deviceId);
//   }
//
//   public List<Integer> listUsingLockerNumByOrdId(Long ordId) {
//      return this.deviceLockerService.listLockerNumByOrdId(ordId);
//   }

   public Long getActiveLockerCount(Long machineId) {
      return this.deviceLockerService.getActiveLockerCount(machineId);
   }
//
//   public Long getMerchantIdInSn(String sn) {
//      if (StringUtil.isEmpty(sn)) {
//         throw new LeException("唯一码sn为空");
//      } else {
//         DeviceInfoInSystem bySnInSys = this.deviceInfoService.getBySnInSys(sn);
//         return bySnInSys != null ? bySnInSys.getTenantId() : null;
//      }
//   }
//
//   public List<String> getDiscountDeviceNameByDeviceIds(List<Long> machineIdList) {
//      return this.deviceInfoService.getDiscountDeviceNameByDeviceIds(machineIdList);
//   }
//
//   public Integer getRecipeBindCount(Long recipeId) {
//      return this.deviceRecipeService.deviceCountByRecipeId(recipeId);
//   }
//
//   public Integer getRecipeBindCount(List<Long> recipeIds) {
//      return this.deviceRecipeService.deviceCountByRecipeId(recipeIds);
//   }

   public List<MacMachineApiVO> getMachineList(MacApiUSelectDto macApiUpdateRepiceDto) {
      DeviceSearchDTO deviceSearchDTO = DeviceDtoConverter.toDeviceSearchDTO(macApiUpdateRepiceDto);
      List<DeviceInfo> list = this.deviceInfoService.list(deviceSearchDTO);
      List<DeviceInfoVO> voList = this.deviceInfoService.fillVo(list);
      return DeviceDtoConverter.toMacMachineApiVO(voList);
   }

//   public boolean checkCanteenStallRelation(Long canteenId, Long stallId, Long mealLineId) {
//      return this.deviceInfoService.checkCanteenStallRelation(canteenId, stallId, mealLineId);
//   }
//
//   public List<MacTcpStateVo> queryDeviceLayoutRecipe(DeviceLayoutRecipeQueryDTO param) {
//      DeviceSearchDTO searchParam = (new DeviceSearchDTO()).setCanteenId(param.getDiningId()).setStallId(param.getShopstallId()).setDeviceNum(param.getDeviceNum()).setDeviceType(SourceTypeEnum.AUTONOMOUS_WEIGHING.getKey());
//      return this.deviceInfoService.queryDeviceLayoutRecipe(searchParam);
//   }
//
//   public List<DeviceInfoOpenVo> getOpenLockerCabinetList() {
//      List<DeviceInfo> allCabinets = this.deviceInfoService.getAllCabinets();
//      if (allCabinets.size() == 0) {
//         return null;
//      } else {
//         List<DeviceInfoOpenVo> deviceInfoOpenVos = BeanUtil.copyToList(allCabinets, DeviceInfoOpenVo.class);
//         Map<Long, DeviceInfoOpenVo> deviceInfoMap = (Map)deviceInfoOpenVos.stream().collect(Collectors.toMap(DeviceInfoOpenVo::getDeviceId, Function.identity()));
//         List<DeviceBind> deviceBinds = this.deviceBindService.listByDeviceIds(ListUtil.toList(deviceInfoMap.keySet()));
//         Map<Long, String> canteenNameMaps = new HashMap();
//         if (deviceBinds.size() > 0) {
//            Set<Long> canteenIds = (Set)deviceBinds.stream().map(DeviceBind::getCanteenId).collect(Collectors.toSet());
//            canteenNameMaps = (Map)this.allocCanteenApi.queryCanteenByCanteenIdList(canteenIds).stream().collect(Collectors.toMap(AllocCanteen::getCanteenId, AllocCanteen::getCanteenName));
//         }
//
//         Map<Long, DeviceBind> bindMap = (Map)deviceBinds.stream().collect(Collectors.toMap(DeviceBind::getDeviceId, Function.identity()));
//         List<DeviceLockerCabinet> lockerCabinets = this.deviceLockerCabinetService.listByDeviceIds(ListUtil.toList(deviceInfoMap.keySet()));
//         List<LockerCabinetOpenVo> lockerCabinetOpenVos = BeanUtil.copyToList(lockerCabinets, LockerCabinetOpenVo.class);
//         Map<Long, List<LockerCabinetOpenVo>> lockerCabinetMap = (Map)lockerCabinetOpenVos.stream().collect(Collectors.groupingBy(LockerCabinetOpenVo::getDeviceId));
//         List<DeviceLocker> deviceLockers = this.deviceLockerService.listByDeviceIds(deviceInfoMap.keySet());
//         List<LockerOpenVO> lockers = BeanUtil.copyToList(deviceLockers, LockerOpenVO.class);
//         Map<Long, List<LockerOpenVO>> lockersMap = (Map)lockers.stream().collect(Collectors.groupingBy(LockerOpenVO::getDeviceId));
//         Iterator var13 = deviceInfoOpenVos.iterator();
//
//         while(var13.hasNext()) {
//            DeviceInfoOpenVo deviceInfoOpenVo = (DeviceInfoOpenVo)var13.next();
//            Long deviceId = deviceInfoOpenVo.getDeviceId();
//            DeviceBind deviceBind = (DeviceBind)bindMap.get(deviceId);
//            if (deviceBind != null) {
//               String canteenName = (String)((Map)canteenNameMaps).get(deviceBind.getCanteenId());
//               deviceInfoOpenVo.setCanteenId(deviceBind.getCanteenId()).setCanteenName(canteenName);
//            }
//
//            deviceInfoOpenVo.setLockerCabinets((List)lockerCabinetMap.get(deviceId));
//            deviceInfoOpenVo.setLockers((List)lockersMap.get(deviceId));
//         }
//
//         return deviceInfoOpenVos;
//      }
//   }
//
//   public String getCompatibleSnByHeaders(Map<String, String> headers) {
//      String machineSn = (String)headers.get("machine-sn");
//      if (StrUtil.isBlank(machineSn)) {
//         String machineNum = (String)headers.get("machine-num");
//         DeviceInfo deviceInfo = this.getByNum(machineNum);
//         machineSn = deviceInfo != null ? deviceInfo.getDeviceSn() : null;
//      }
//
//      return machineSn;
//   }
//
//   /** @deprecated */
//   public MacMachineVo getMachineConfigBySn(String machineSn) {
//      DeviceInfoVO deviceInfoVo = this.deviceInfoService.getDeviceInfoVoBySn(machineSn);
//      return deviceInfoVo == null ? null : DeviceDtoConverter.toMacMachineVo(deviceInfoVo);
//   }
//
//   public List<MacTcpStateVo> getMealDetailByNums(List<String> mchNums) {
//      return CollUtil.isEmpty(mchNums) ? ListUtil.empty() : this.deviceInfoService.queryDeviceLayoutRecipe((new DeviceSearchDTO()).setDeviceNumList(mchNums));
//   }
//
//   /** @deprecated */
//   public List<MacMachineVo> getMachineByShopstallIdAndMchType(Long shopstallId, Integer mchType) {
//      List<DeviceInfo> list = this.deviceInfoService.list((new DeviceSearchDTO()).setStallId(shopstallId).setDeviceType(mchType));
//      List<DeviceInfoVO> voList = this.deviceInfoService.fillVo(list);
//      return DeviceDtoConverter.toMacMachineVo(voList);
//   }
//
//   /** @deprecated */
//   public List<DeviceInfoVO> getDeviceByDeviceType(Integer mchType) {
//      List<DeviceInfo> list = this.deviceInfoService.list((new DeviceSearchDTO()).setDeviceType(mchType));
//      List<DeviceInfoVO> voList = this.deviceInfoService.fillVo(list);
//      return voList;
//   }
//
//   public List<MarketDeviceTreeVO> listTenantDevice(List<Integer> deviceTypes, List<Long> canteenIds, List<Long> stallIds) {
//      return (List)Optional.ofNullable(this.deviceInfoService.listTenantDevice(deviceTypes, canteenIds, stallIds)).orElse(new ArrayList());
//   }
}
