package com.bonus.canteen.core.allocation.canteen.business.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bonus.canteen.core.allocation.alloc.model.AllocMetadata;
import com.bonus.canteen.core.allocation.api.*;
import com.bonus.canteen.core.allocation.canteen.business.AllocCanteenBusiness;
import com.bonus.canteen.core.allocation.canteen.custom.CanteenCustomBusiness;
import com.bonus.canteen.core.allocation.canteen.dto.*;
import com.bonus.canteen.core.allocation.canteen.enums.AllocCanteenTreeTypeEnum;
import com.bonus.canteen.core.allocation.canteen.mapper.AllocCanteenMapper;
import com.bonus.canteen.core.allocation.canteen.mapper.AllocKindMapper;
import com.bonus.canteen.core.allocation.canteen.mapper.AllocLabelMapper;
import com.bonus.canteen.core.allocation.canteen.mapper.AllocStallMapper;
import com.bonus.canteen.core.allocation.canteen.model.*;
import com.bonus.canteen.core.allocation.canteen.param.AllocCanteenNumParam;
import com.bonus.canteen.core.allocation.canteen.service.*;
import com.bonus.canteen.core.allocation.constants.QRTypeEnum;
import com.bonus.canteen.core.allocation.util.MetadataUtil;
import com.bonus.canteen.core.allocation.util.PayQRCodeUtil;
import com.bonus.canteen.core.common.constant.LeMqConstant;
import com.bonus.canteen.core.common.enums.AllocBusinessStateEnum;
import com.bonus.canteen.core.common.enums.AllocMealtimeTypeEnum;
import com.bonus.canteen.core.common.enums.DeliveryTypeEnum;
import com.bonus.canteen.core.common.enums.MetadataModelTypeEnum;
import com.bonus.canteen.core.common.utils.AesEncryptUtil;
import com.bonus.canteen.core.customer.api.CustInfoApi;
import com.bonus.canteen.core.customer.model.CustInfo;
import com.bonus.canteen.core.device.api.DeviceApi;
import com.bonus.canteen.core.menu.api.MenuRecipeApi;
import com.bonus.canteen.core.menu.model.AllocMealtimeModel;
import com.bonus.canteen.core.order.api.OrderAllocApi;
import com.bonus.canteen.core.order.mq.MqUtil;
import com.bonus.canteen.core.pay.channel.abc.entity.dto.AbcMerchantAddOrUpdateDTO;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.houqin.constant.LeConstants;
import com.bonus.common.houqin.i18n.I18n;
import com.bonus.common.houqin.utils.id.Id;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.invoke.SerializedLambda;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

@Service
public class AllocCanteenBusinessImpl implements AllocCanteenBusiness {
   private static final Logger log = LoggerFactory.getLogger(AllocCanteenBusinessImpl.class);
   @Autowired
   @Lazy
   private GlobalMetadataApi globalMetadataApi;
   @Autowired
   @Lazy
   private AllocPayMetadataApi allocPayMetadataApi;
   @Autowired
   @Lazy
   private AllocMealtimeApi allocMealtimeApi;
   @Autowired
   @Lazy
   private OrderAllocApi orderAllocApi;
//   @Autowired
//   @Lazy
//   private AbcPayApi abcPayApi;
//   @Autowired
//   @Lazy
//   private AllocDeliveryApi allocDeliveryApi;
   @Autowired
   @Lazy
   private CustInfoApi custInfoApi;
   @Autowired
   @Lazy
   private AllocAreaService allocAreaService;
   @Autowired
   @Lazy
   private AllocCanteenService allocCanteenService;
   @Autowired
   @Lazy
   private AllocStallService allocStallService;
   @Autowired
   @Lazy
   private AllocMealLineService allocMealLineService;
   @Autowired
   @Lazy
   private AllocLabelService allocLabelService;
   @Autowired
   @Lazy
   private AllocKindService allocKindService;
   @Autowired
   @Lazy
   private DeviceApi deviceApi;
   @Autowired
   @Lazy
   private MenuRecipeApi menuRecipeApi;
//   @Autowired
//   @Lazy
//   private AllocOrderMetadataApi allocOrderMetadataApi;
   @Autowired
   @Lazy
   private CanteenCustomBusiness canteenCustomBusiness;
   @Autowired
   @Lazy
   private PayQRCodeUtil payQRCodeUtil;
   @Resource
   private AllocCanteenMapper allocCanteenMapper;
   @Resource
   private AllocStallMapper allocStallMapper;
   @Resource
   private AllocLabelMapper allocLabelMapper;
   @Resource
   private AllocKindMapper allocKindMapper;
   @Resource
   private AesEncryptUtil aesEncryptUtil;

   public String getCanteenNum(AllocCanteenNumParam param) {
      Long superId = param.getSuperId();
      AllocCanteenTreeTypeEnum canteenTreeTypeEnum = AllocCanteenTreeTypeEnum.getTypeEnum(param.getCanteenTreeType());
      switch (canteenTreeTypeEnum) {
         case MERCHANT:
            return this.allocAreaService.getLatestFirstAreaNum();
         case AREA:
            return this.allocAreaService.getLatestAreaNum(superId);
         case CANTEEN:
            return this.allocCanteenService.getLatestCanteenNum(superId);
         case STALL:
            return this.allocStallService.getLatestStallNum(superId);
         case MEAL_LINE:
            return this.allocMealLineService.getLatestStallNum(superId);
         default:
            return "";
      }
   }

   public AllocCanteenModifyModel getCanteenForModify(Long canteenId) {
      AllocCanteen allocCanteen = this.allocCanteenService.getOne(Wrappers.lambdaQuery(AllocCanteen.class)
              .eq(AllocCanteen::getCanteenId, canteenId));
      allocCanteen.setContactTel(this.aesEncryptUtil.aesEncrypt(allocCanteen.getContactTel()));
      AllocCanteenSaveDTO canteenSaveDTO = new AllocCanteenSaveDTO();
      BeanUtils.copyProperties(allocCanteen, canteenSaveDTO);
      if (ObjectUtil.isNotNull(canteenSaveDTO.getCustId())) {
         CustInfo custInfo = this.custInfoApi.getCustInfoByCustId(canteenSaveDTO.getCustId());
         if (ObjectUtil.isNotNull(custInfo)) {
            canteenSaveDTO.setCustName(custInfo.getCustName());
         }
      }

      List<String> labelNameList = this.allocLabelMapper.listRelationLabelName(canteenId, (Long)null);
      canteenSaveDTO.setLabelNameList(labelNameList);
      AllocCanteenPayDTO payDTO = this.getAllocCanteenPayDTO(canteenId);
      List<AllocMetadata> metadataList = this.globalMetadataApi.getList(MetadataModelTypeEnum.DELIVERY, canteenId, (Long)null);
      AllocCanteenDeliveryModel deliveryModel = MetadataUtil.meteDataListToDelivery(metadataList);
      AllocCanteenOrderDTO orderDTO = this.getAllocCanteenOrderDTO(canteenId, (Long)null);
      List<AllocMealtimeModel> mealtimeList = this.allocMealtimeApi.listMealtime(canteenId, (Long)null);
      if (CollUtil.isEmpty(mealtimeList)) {
         mealtimeList = this.allocMealtimeApi.listUseAvailableMealtime(canteenId, (Long)null, (Integer)null);
      }

      this.canteenCustomBusiness.canteenGroupQueryHandler(canteenId, canteenSaveDTO);
      return new AllocCanteenModifyModel(canteenId, canteenSaveDTO, payDTO, deliveryModel, orderDTO, mealtimeList);
   }

   private AllocCanteenPayDTO getAllocCanteenPayDTO(Long canteenId) {
      return this.allocPayMetadataApi.getAllocCanteenPayDTO(canteenId);
   }

   private AllocCanteenOrderDTO getAllocCanteenOrderDTO(Long canteenId, Long stallId) {
      return (AllocCanteenOrderDTO)this.globalMetadataApi.getModel(MetadataModelTypeEnum.ORDER_RESERVE, new AllocCanteenOrderDTO(), canteenId, stallId);
   }

   public AllocStallModifyModel getStallForModify(Long stallId) {
      AllocStall allocStall = (AllocStall)this.allocStallService.getOne(Wrappers.lambdaQuery(AllocStall.class)
              .eq(AllocStall::getStallId, stallId));
      allocStall.setContactTel(this.aesEncryptUtil.aesEncrypt(allocStall.getContactTel()));
      AllocStallSaveDTO stallSaveDTO = new AllocStallSaveDTO();
      BeanUtils.copyProperties(allocStall, stallSaveDTO);
      if (ObjectUtil.isNotNull(stallSaveDTO.getCustId())) {
         CustInfo custInfo = this.custInfoApi.getCustInfoByCustId(stallSaveDTO.getCustId());
         if (ObjectUtil.isNotNull(custInfo)) {
            stallSaveDTO.setCustName(custInfo.getCustName());
         }
      }

      List<String> labelNameList = this.allocLabelMapper.listRelationLabelName((Long)null, stallId);
      List<String> kindNameList = this.allocKindMapper.listStallKindName(stallId);
      stallSaveDTO.setLabelNameList(labelNameList);
      stallSaveDTO.setKindNameList(kindNameList);
      List<AllocMetadata> metadataList = this.globalMetadataApi.getList(MetadataModelTypeEnum.DELIVERY, (Long)null, stallId);
      AllocCanteenDeliveryModel deliveryModel = MetadataUtil.meteDataListToDelivery(metadataList);
      AllocCanteenOrderDTO orderDTO = this.getAllocCanteenOrderDTO((Long)null, stallId);
      List<AllocMealtimeModel> mealtimeList = this.allocMealtimeApi.listMealtime((Long)null, stallId);
      if (CollUtil.isEmpty(mealtimeList)) {
         mealtimeList = this.allocMealtimeApi.listUseAvailableMealtime((Long)null, stallId, (Integer)null);
      }

      this.canteenCustomBusiness.stallGroupQueryHandler(stallId, stallSaveDTO);
      return new AllocStallModifyModel(stallId, stallSaveDTO, deliveryModel, orderDTO, mealtimeList);
   }
//
//   public AllocCanteenAppModel getCanteenConfig(Long stallId) {
//      AllocCanteen canteen = (AllocCanteen)this.allocCanteenService.getOne(Wrappers.lambdaQuery(AllocCanteen.class));
//      Long canteenId = canteen.getCanteenId();
//      AllocCanteenPayDTO payDTO = this.getAllocCanteenPayDTO(canteenId);
//      AllocCanteenDeliveryModel deliveryModel = this.allocDeliveryApi.queryDeliveryModel((Long)null, stallId);
//      AllocCanteenOrderDTO orderDTO = this.allocOrderMetadataApi.queryAvailableOrder((Long)null, stallId);
//      List<AllocMealtimeModel> mealtimeList = this.allocMealtimeApi.listUseAvailableMealtime(canteenId, stallId, LeConstants.COMMON_YES);
//      return new AllocCanteenAppModel(payDTO, deliveryModel, orderDTO, mealtimeList);
//   }
//
//   public AllocCanteenPayDTO queryCanteenPay(AllocCanteenStallParam param) {
//      return this.getAllocCanteenPayDTO(param.getCanteenId());
//   }
//
//   public AllocCanteenDeliveryModel queryCanteenDelivery(AllocCanteenStallParam param) {
//      List<AllocMetadata> metadataList = this.globalMetadataApi.getList(MetadataModelTypeEnum.DELIVERY, param.getCanteenId(), param.getStallId());
//      return MetadataUtil.meteDataListToDelivery(metadataList);
//   }
//
//   public AllocCanteenOrderModel queryCanteenOrder(AllocCanteenStallParam param) {
//      AllocCanteenOrderDTO orderDTO = (AllocCanteenOrderDTO)this.globalMetadataApi.getModel(MetadataModelTypeEnum.ORDER_RESERVE, new AllocCanteenOrderDTO(), param.getCanteenId(), param.getStallId());
//      List<AllocMealtimeModel> mealtimeList = new ArrayList();
//      if (ObjectUtil.isNotNull(param.getCanteenId())) {
//         mealtimeList = this.allocMealtimeApi.listMealtime(param.getCanteenId(), (Long)null);
//      } else if (ObjectUtil.isNotNull(param.getStallId())) {
//         mealtimeList = this.allocMealtimeApi.listMealtime((Long)null, param.getStallId());
//      }
//
//      return new AllocCanteenOrderModel(orderDTO, (List)mealtimeList);
//   }
//
//   public AllocPackingFeeVO queryCanteenPackingFee(AllocCanteenStallParam param) {
//      List<AllocMetadata> deliveryMetadataList = this.globalMetadataApi.getList(MetadataModelTypeEnum.DELIVERY, param.getCanteenId(), param.getStallId());
//      if (CollUtil.isEmpty(deliveryMetadataList)) {
//         return new AllocPackingFeeVO(param);
//      } else {
//         Iterator var3 = deliveryMetadataList.iterator();
//
//         AllocCanteenDeliveryDTO deliveryDTO;
//         do {
//            if (!var3.hasNext()) {
//               return new AllocPackingFeeVO(param);
//            }
//
//            AllocMetadata allocMetadata = (AllocMetadata)var3.next();
//            deliveryDTO = (AllocCanteenDeliveryDTO)JSONUtil.toBean(allocMetadata.getModelValue(), AllocCanteenDeliveryDTO.class);
//         } while(!DeliveryTypeEnum.TAKE_OUT.getKey().equals(deliveryDTO.getDeliveryType()));
//
//         return new AllocPackingFeeVO(param, DeliveryTypeEnum.TAKE_OUT.getKey(), deliveryDTO.getPackingFee());
//      }
//   }

   @Transactional(
      rollbackFor = {RuntimeException.class}
   )
   public void addCanteen(AllocCanteenModel canteenModel) {
      Long canteenId = Id.next();
      Integer ifEnableOrder = (Integer)Optional.ofNullable(canteenModel.getOrderDTO().getIfEnableOrder()).orElse(LeConstants.COMMON_NO);
      this.allocCanteenService.checkCanteenNameExist(canteenModel.getCanteenSaveDTO().getCanteenName(), (Long)null);
      this.saveCanteenCheck(canteenModel);
      AllocCanteen allocCanteen = new AllocCanteen(canteenId);
      BeanUtils.copyProperties(canteenModel.getCanteenSaveDTO(), allocCanteen);
      Integer ifEnablePay = (Integer)Optional.ofNullable(canteenModel.getPayDTO().getIfEnablePay()).orElse(LeConstants.COMMON_NO);
      allocCanteen.setIfEnablePay(ifEnablePay);
      allocCanteen.setPayTypes(canteenModel.getPayDTO().getPayTypes());
      Integer ifEnableDelivery = (Integer)Optional.ofNullable(canteenModel.getDeliveryModel().getIfEnableDelivery()).orElse(LeConstants.COMMON_NO);
      allocCanteen.setIfEnableDelivery(ifEnableDelivery);
      allocCanteen.setDeliveries(canteenModel.getDeliveryModel().getDeliveries());
      allocCanteen.setIfEnableOrder(ifEnableOrder);
      allocCanteen.setContactTel(this.aesEncryptUtil.aesDecode(allocCanteen.getContactTel()));
      if (LeConstants.COMMON_YES.equals(allocCanteen.getIfEnablePayCode())) {
         String payCodeUrl = this.payQRCodeUtil.generateQRCode(allocCanteen.getCanteenId(), allocCanteen.getCanteenName()
                 , QRTypeEnum.CANTEEN_COLLECTION);
         allocCanteen.setPayCodeUrl(payCodeUrl);
      }

      allocCanteen.setBusinessState(AllocBusinessStateEnum.OPEN.getKey());
      log.info("[食堂]新增保存信息_{}", JSON.toJSON(allocCanteen));
      this.allocCanteenService.saveCanteen(allocCanteen);
      this.allocLabelService.saveRelationLabel(canteenId, (Long)null, canteenModel.getCanteenSaveDTO().getLabelNameList());
      this.allocPayMetadataApi.saveCanteenPay(canteenModel.getPayDTO(), canteenId);
      this.globalMetadataApi.saveList(MetadataUtil.deliveryListToMetadata(canteenModel.getDeliveryModel(), canteenId, (Long)null));
      this.globalMetadataApi.saveModel(MetadataModelTypeEnum.ORDER_RESERVE, canteenModel.getOrderDTO(), canteenId, (Long)null);
      List<AllocMealtimeModel> mealtimeList = canteenModel.getMealtimeList();
      if (CollUtil.isEmpty(mealtimeList)) {
         mealtimeList = this.allocMealtimeApi.listUseAvailableMealtime(canteenId, (Long)null, (Integer)null);
      }

      this.allocMealtimeApi.saveBatchMealtime(mealtimeList, ifEnableOrder, canteenId, (Long)null);
      this.allocCanteenService.correctCanteenNum();
//      AbcMerchantAddOrUpdateDTO abcDTO = MetadataUtil.transferAbcPayToDTO(canteenModel.getPayDTO().getPayMap(), canteenId);
//      if (ObjectUtil.isNotNull(abcDTO)) {
//         this.abcPayApi.saveAbcMerchantInfo(abcDTO);
//      } 2025-03-03 注释农行

      this.canteenCustomBusiness.canteenAddHandler(canteenId, canteenModel.getCanteenSaveDTO().getExtendMap());
      MqUtil.sendDataChange(allocCanteen, LeMqConstant.DataChangeType.ADD, LeMqConstant.Topic.DATA_CHANGE_CANTEEN);
   }

   private void saveCanteenCheck(AllocCanteenModel canteenModel) {
      LocalTime startTime = canteenModel.getCanteenSaveDTO().getStartBusinessTime();
      LocalTime endTime = canteenModel.getCanteenSaveDTO().getEndBusinessTime();
      if (ObjectUtil.isNotNull(startTime) && ObjectUtil.isNotNull(endTime) && startTime.compareTo(endTime) >= 0) {
         throw new ServiceException(I18n.getMessage("alloc_canteen_business_time_error", new Object[0]));
      } else {
         this.allocMealtimeApi.checkTimeValidityForBatch(canteenModel.getMealtimeList());
      }
   }

   @Transactional(
      rollbackFor = {RuntimeException.class}
   )
   public void modifyCanteen(AllocCanteenModifyModel canteenModel) {
      Long canteenId = canteenModel.getCanteenId();
      this.allocCanteenService.checkCanteenNameExist(canteenModel.getCanteenSaveDTO().getCanteenName(), canteenId);
      this.saveCanteenCheck(canteenModel);
      this.modifyCanteenCheck(canteenModel.getDeliveryModel().getIfEnableDelivery(), canteenModel.getOrderDTO().getIfEnableOrder(), canteenModel.getMealtimeList(), canteenId, (Long)null);
      AllocCanteenModifyDTO canteenModifyDTO = new AllocCanteenModifyDTO();
      BeanUtils.copyProperties(canteenModel.getCanteenSaveDTO(), canteenModifyDTO);
      canteenModifyDTO.ifEnableHandler(canteenModel);
      canteenModifyDTO.setContactTel(this.aesEncryptUtil.aesDecode(canteenModifyDTO.getContactTel()));
      Long oldAreaId = this.allocCanteenMapper.getAreaId(canteenId);
      if (LeConstants.COMMON_YES.equals(canteenModifyDTO.getIfEnablePayCode())) {
         AllocCanteen tempCanteen = (AllocCanteen)this.allocCanteenService.getOne(Wrappers.lambdaQuery(AllocCanteen.class).eq(AllocCanteen::getCanteenId, canteenId));
         if (CharSequenceUtil.isBlank(tempCanteen.getPayCodeUrl()) || !canteenModifyDTO.getCanteenName().equals(tempCanteen.getCanteenName())) {
            String payCodeUrl = this.payQRCodeUtil.generateQRCode(canteenId, canteenModifyDTO.getCanteenName(), QRTypeEnum.CANTEEN_COLLECTION);
            canteenModifyDTO.setPayCodeUrl(payCodeUrl);
         }
      }

      if (LeConstants.COMMON_NO.equals(canteenModifyDTO.getIfEnablePayCode())) {
         canteenModifyDTO.setPayCodeUrl((String)null);
      }

      log.info("[食堂]修改保存信息_{}, canteenId:{}", JSON.toJSON(canteenModifyDTO), canteenId);
      this.allocCanteenService.modifyByCanteenId(canteenModifyDTO, canteenId);
      this.allocLabelService.saveRelationLabel(canteenId, (Long)null, canteenModel.getCanteenSaveDTO().getLabelNameList());
      this.allocPayMetadataApi.saveCanteenPay(canteenModel.getPayDTO(), canteenId);
      this.globalMetadataApi.saveList(MetadataUtil.deliveryListToMetadata(canteenModel.getDeliveryModel(), canteenId, (Long)null));
      this.globalMetadataApi.saveModel(MetadataModelTypeEnum.ORDER_RESERVE, canteenModel.getOrderDTO(), canteenId, (Long)null);
      this.allocMealtimeApi.saveBatchMealtime(canteenModel.getMealtimeList(), canteenModel.getOrderDTO().getIfEnableOrder(), canteenId, (Long)null);
//      AbcMerchantAddOrUpdateDTO abcDTO = MetadataUtil.transferAbcPayToDTO(canteenModel.getPayDTO().getPayMap(), canteenId);
//      if (ObjectUtil.isNotNull(abcDTO)) {
//         this.abcPayApi.saveAbcMerchantInfo(abcDTO);
//      } 2025-03-03 注释 农行

      this.canteenCustomBusiness.canteenModifyHandler(canteenId, canteenModel.getCanteenSaveDTO().getExtendMap());
      canteenModifyDTO.setCanteenId(canteenId);
      canteenModifyDTO.setOldAreaId(oldAreaId);
      MqUtil.sendDataChange(canteenModifyDTO, LeMqConstant.DataChangeType.UPDATE, LeMqConstant.Topic.DATA_CHANGE_CANTEEN);
   }

   private void modifyCanteenCheck(Integer ifEnableDelivery, Integer ifEnableOrder, List<AllocMealtimeModel> mealtimeList, Long canteenId, Long stallId) {
      if (ObjectUtil.isNotNull(stallId)) {
         AllocStall allocStall = this.allocStallService.getOne(Wrappers.lambdaQuery(AllocStall.class).eq(AllocStall::getStallId, stallId));
         if (LeConstants.COMMON_NO.equals(ifEnableDelivery) && LeConstants.COMMON_YES.equals(allocStall.getIfEnableDelivery()) && this.orderAllocApi.existOrderUnTake((Long)null, stallId)) {
            throw new ServiceException(I18n.getMessage("alloc_canteen_delivery_close_check"));
         }

         if (LeConstants.COMMON_NO.equals(ifEnableOrder) && LeConstants.COMMON_YES.equals(allocStall.getIfEnableOrder())) {
            if (this.orderAllocApi.existReserveOrderUnPrint((Long)null, stallId, (Integer)null)) {
               throw new ServiceException(I18n.getMessage("alloc_canteen_order_close_check"));
            }

            this.checkReservePrintTime(mealtimeList, (Long)null, stallId);
         }
      } else {
         AllocCanteen allocCanteen = this.allocCanteenService.getOne(Wrappers.lambdaQuery(AllocCanteen.class)
                 .eq(AllocCanteen::getCanteenId, canteenId));
         if (LeConstants.COMMON_NO.equals(ifEnableDelivery)
                 && LeConstants.COMMON_YES.equals(allocCanteen.getIfEnableDelivery())
                 && this.orderAllocApi.existOrderUnTake(canteenId, (Long)null)) {
            throw new ServiceException(I18n.getMessage("alloc_canteen_delivery_close_check", new Object[0]));
         }

         if (LeConstants.COMMON_NO.equals(ifEnableOrder) && LeConstants.COMMON_YES.equals(allocCanteen.getIfEnableOrder())) {
            if (this.orderAllocApi.existReserveOrderUnPrint(canteenId, (Long)null, (Integer)null)) {
               throw new ServiceException(I18n.getMessage("alloc_canteen_order_close_check", new Object[0]));
            }

            this.checkReservePrintTime(mealtimeList, canteenId, (Long)null);
         }
      }

   }

   private void checkReservePrintTime(List<AllocMealtimeModel> mealtimeList, Long canteenId, Long stallId) {
      List<AllocMealtimeModel> mealtimeModelList = this.allocMealtimeApi.listMealtime(canteenId, stallId);
      Iterator var5 = mealtimeModelList.iterator();

      while(var5.hasNext()) {
         AllocMealtimeModel mealtimeModel = (AllocMealtimeModel)var5.next();
         Iterator var7 = mealtimeList.iterator();

         while(var7.hasNext()) {
            AllocMealtimeModel mealtimeDTO = (AllocMealtimeModel)var7.next();
            if (mealtimeModel.getMealtimeType().equals(mealtimeDTO.getMealtimeType())
                    && ObjectUtil.isNotNull(mealtimeModel.getReservePrintTime())
                    && !mealtimeModel.getReservePrintTime().equals(mealtimeDTO.getReservePrintTime())
                    && this.orderAllocApi.existReserveOrderUnPrint(canteenId, stallId, mealtimeModel.getMealtimeType())) {
               throw new ServiceException(I18n.getMessage("alloc_canteen_reserve_print_close_check",
                       AllocMealtimeTypeEnum.getDescByKey(mealtimeModel.getMealtimeType())));
            }
         }
      }

   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public void addStall(AllocStallModel stallModel) {
      Long stallId = Id.next();
      Integer ifEnableOrder = (Integer)Optional.ofNullable(stallModel.getOrderDTO().getIfEnableOrder()).orElse(LeConstants.COMMON_NO);
      AllocCanteen allocCanteen = this.allocCanteenService.checkCanteenIdExist(stallModel.getStallSaveDTO().getCanteenId());
      this.allocStallService.checkStallNameExist(stallModel.getStallSaveDTO().getStallName(), (Long)null);
      this.saveStallCheck(stallModel);
      AllocStall allocStall = new AllocStall(stallId);
      BeanUtils.copyProperties(stallModel.getStallSaveDTO(), allocStall);
      Integer ifEnableDelivery = (Integer)Optional.ofNullable(stallModel.getDeliveryModel().getIfEnableDelivery()).orElse(LeConstants.COMMON_NO);
      allocStall.setIfEnableDelivery(ifEnableDelivery);
      allocStall.setDeliveries(stallModel.getDeliveryModel().getDeliveries());
      allocStall.setIfEnableOrder(ifEnableOrder);
      allocStall.setContactTel(this.aesEncryptUtil.aesDecode(allocStall.getContactTel()));
      allocStall.setAreaId(allocCanteen.getAreaId());
      if (LeConstants.COMMON_YES.equals(allocStall.getIfEnablePayCode())) {
         String payCodeUrl = this.payQRCodeUtil.generateQRCode(allocStall.getStallId(), allocStall.getStallName(), QRTypeEnum.STALL_COLLECTION);
         allocStall.setPayCodeUrl(payCodeUrl);
      }

      allocStall.setBusinessState(AllocBusinessStateEnum.OPEN.getKey());
      log.info("[档口]新增保存信息_{}", JSON.toJSON(allocStall));
      this.allocStallService.saveStall(allocStall);
      this.allocLabelService.saveRelationLabel((Long)null, stallId, stallModel.getStallSaveDTO().getLabelNameList());
      this.allocKindService.saveStallKind(stallModel.getStallSaveDTO().getKindNameList(), stallId);
      this.globalMetadataApi.saveList(MetadataUtil.deliveryListToMetadata(stallModel.getDeliveryModel(), stallModel.getStallSaveDTO().getCanteenId(), stallId));
      this.globalMetadataApi.saveModel(MetadataModelTypeEnum.ORDER_RESERVE, stallModel.getOrderDTO(), (Long)null, stallId);
      List<AllocMealtimeModel> mealtimeList = stallModel.getMealtimeList();
      if (CollUtil.isEmpty(mealtimeList)) {
         mealtimeList = this.allocMealtimeApi.listUseAvailableMealtime((Long)null, stallId, (Integer)null);
      }

      this.allocMealtimeApi.saveBatchMealtime(mealtimeList, ifEnableOrder, allocStall.getCanteenId(), stallId);
      this.canteenCustomBusiness.stallAddHandler(stallId, stallModel.getStallSaveDTO().getExtendMap());
      this.allocStallService.correctStallNum();
      MqUtil.sendDataChange(allocStall, LeMqConstant.DataChangeType.ADD, LeMqConstant.Topic.DATA_CHANGE_SHOP_STALL);
   }

   private void saveStallCheck(AllocStallModel stallModel) {
      LocalTime startTime = stallModel.getStallSaveDTO().getStartBusinessTime();
      LocalTime endTime = stallModel.getStallSaveDTO().getEndBusinessTime();
      if (ObjectUtil.isNotNull(startTime) && ObjectUtil.isNotNull(endTime) && startTime.compareTo(endTime) >= 0) {
         throw new ServiceException(I18n.getMessage("alloc_canteen_business_time_error", new Object[0]));
      } else {
         this.allocMealtimeApi.checkTimeValidityForBatch(stallModel.getMealtimeList());
         this.saveStallIfBookCheck(stallModel.getStallSaveDTO());
      }
   }

   private void saveStallIfBookCheck(AllocStallSaveDTO stallSaveDTO) {
      if (LeConstants.COMMON_YES.equals(stallSaveDTO.getIfBook())) {
         boolean openCheck = LeConstants.COMMON_NO.equals(this.allocCanteenMapper.getIfBook(stallSaveDTO.getCanteenId()));
         if (openCheck) {
            throw new ServiceException(I18n.getMessage("alloc_stall_book_check", new Object[0]));
         }
      }

   }

   public void modifyStall(AllocStallModifyModel stallModel) {
      Long stallId = stallModel.getStallId();
      Long canteenId = stallModel.getStallSaveDTO().getCanteenId();
      this.allocStallService.checkStallNameExist(stallModel.getStallSaveDTO().getStallName(), stallId);
      this.saveStallCheck(stallModel);
      this.modifyCanteenCheck(stallModel.getDeliveryModel().getIfEnableDelivery(), stallModel.getOrderDTO().getIfEnableOrder(), stallModel.getMealtimeList(), (Long)null, stallId);
      AllocStallModifyDTO stallModifyDTO = new AllocStallModifyDTO();
      BeanUtils.copyProperties(stallModel.getStallSaveDTO(), stallModifyDTO);
      stallModifyDTO.ifEnableHandler(stallModel);
      stallModifyDTO.setContactTel(this.aesEncryptUtil.aesDecode(stallModifyDTO.getContactTel()));
      Long oldCanteenId = this.allocStallMapper.getCanteenId(stallId);
      if (LeConstants.COMMON_YES.equals(stallModifyDTO.getIfEnablePayCode())) {
         AllocStall tempStall = (AllocStall)this.allocStallService.getOne((Wrapper)Wrappers.lambdaQuery(AllocStall.class).eq(AllocStall::getStallId, stallId));
         if (CharSequenceUtil.isBlank(tempStall.getPayCodeUrl()) || !stallModifyDTO.getStallName().equals(tempStall.getStallName())) {
            String payCodeUrl = this.payQRCodeUtil.generateQRCode(stallId, stallModifyDTO.getStallName(), QRTypeEnum.STALL_COLLECTION);
            stallModifyDTO.setPayCodeUrl(payCodeUrl);
         }
      }

      if (LeConstants.COMMON_NO.equals(stallModifyDTO.getIfEnablePayCode())) {
         stallModifyDTO.setPayCodeUrl((String)null);
      }

      log.info("[档口]修改保存信息_{}, stallId:{}", JSON.toJSON(stallModifyDTO), stallId);
      this.allocStallService.modifyByStallId(stallModifyDTO, stallId);
      this.allocLabelService.saveRelationLabel((Long)null, stallId, stallModel.getStallSaveDTO().getLabelNameList());
      this.allocKindService.saveStallKind(stallModel.getStallSaveDTO().getKindNameList(), stallId);
      this.globalMetadataApi.saveList(MetadataUtil.deliveryListToMetadata(stallModel.getDeliveryModel(), canteenId, stallId));
      this.globalMetadataApi.saveModel(MetadataModelTypeEnum.ORDER_RESERVE, stallModel.getOrderDTO(), (Long)null, stallId);
      this.allocMealtimeApi.saveBatchMealtime(stallModel.getMealtimeList(), stallModel.getOrderDTO().getIfEnableOrder(), (Long)null, stallId);
      this.canteenCustomBusiness.stallModifyHandler(stallId, stallModel.getStallSaveDTO().getExtendMap());
      stallModifyDTO.setStallId(stallId);
      stallModifyDTO.setOldCanteenId(oldCanteenId);
      MqUtil.sendDataChange(stallModifyDTO, LeMqConstant.DataChangeType.UPDATE, LeMqConstant.Topic.DATA_CHANGE_SHOP_STALL);
   }

   public void modifyBusinessState(ModifyCanteenStateDTO stateDTO) {
      if (AllocCanteenTreeTypeEnum.CANTEEN.getKey().equals(stateDTO.getCanteenTreeType())) {
         this.allocCanteenService.modifyBusinessState(stateDTO.getModifyId(), stateDTO.getBusinessState());
         if (AllocBusinessStateEnum.REST.getKey().equals(stateDTO.getBusinessState())) {
            this.allocStallService.modifyBusinessState(stateDTO.getModifyId(), stateDTO.getBusinessState());
         }
      } else if (AllocCanteenTreeTypeEnum.STALL.getKey().equals(stateDTO.getCanteenTreeType())) {
         if (AllocBusinessStateEnum.OPEN.getKey().equals(stateDTO.getBusinessState())
                 && AllocBusinessStateEnum.REST.getKey().equals(this.allocStallMapper
                 .getCanteenStateByStallId(stateDTO.getModifyId()))) {
            throw new ServiceException(I18n.getMessage("alloc_canteen_is_rest", new Object[0]));
         }

         this.allocStallService.modifyBusinessState(stateDTO.getModifyId(), stateDTO.getBusinessState());
      }

   }
//
//   public void saveCanteenPay(AllocCanteenPayDTO payDTO) {
//      this.allocPayMetadataApi.saveCanteenPay(payDTO, (Long)null);
//   }
//
//   public void saveCanteenDelivery(AllocCanteenDeliveryModel deliveryModel) {
//      this.globalMetadataApi.saveList(MetadataUtil.deliveryListToMetadata(deliveryModel, (Long)null, (Long)null));
//   }

   public void removeArea(Long areaId) {
      Long canteenCount = this.allocCanteenService.count(Wrappers.lambdaQuery(AllocCanteen.class)
              .eq(AllocCanteen::getAreaId, areaId).eq(AllocCanteen::getIfDel, LeConstants.COMMON_NO));
      if (canteenCount > 0L) {
         throw new ServiceException(I18n.getMessage("alloc_area_remove_check_canteen", new Object[0]));
      } else {
         Long areaCount = this.allocAreaService.count(Wrappers.lambdaQuery(AllocArea.class)
                 .eq(AllocArea::getSuperId, areaId).eq(AllocArea::getIfDel, LeConstants.COMMON_NO));
         if (areaCount > 0L) {
            throw new ServiceException(I18n.getMessage("alloc_area_remove_check_son", new Object[0]));
         } else {
            this.allocAreaService.deleteArea(areaId);
         }
      }
   }

   public void removeCanteen(Long canteenId) {
      if (this.menuRecipeApi.checkCanteenStallRelation(canteenId, (Long)null)) {
         throw new ServiceException(I18n.getMessage("alloc_canteen_remove_check_menu", new Object[0]));
      } else if (this.deviceApi.checkCanteenStallRelation(canteenId, (Long)null, (Long)null)) {
         throw new ServiceException(I18n.getMessage("alloc_canteen_remove_check_device", new Object[0]));
      } else if (this.allocStallService.checkCanteenStallRelation(canteenId)) {
         throw new ServiceException(I18n.getMessage("alloc_canteen_remove_check_stall", new Object[0]));
      } else {
         this.allocLabelService.removeLabelRelation(canteenId, (Long)null);
         this.globalMetadataApi.delete(canteenId, (Long)null);
         this.allocCanteenService.deleteCanteen(canteenId);
         this.canteenCustomBusiness.canteenRemoveHandler(canteenId);
         MqUtil.sendDataChange(canteenId, LeMqConstant.DataChangeType.REMOVE, LeMqConstant.Topic.DATA_CHANGE_CANTEEN);
      }
   }

   public void removeStall(Long stallId) {
      if (this.menuRecipeApi.checkCanteenStallRelation((Long)null, stallId)) {
         throw new ServiceException(I18n.getMessage("alloc_stall_remove_check_menu", new Object[0]));
      } else if (this.deviceApi.checkCanteenStallRelation((Long)null, stallId, (Long)null)) {
         throw new ServiceException(I18n.getMessage("alloc_stall_remove_check_device", new Object[0]));
      } else {
         this.allocLabelService.removeLabelRelation((Long)null, stallId);
         this.allocKindService.removeStallKind(stallId);
         this.globalMetadataApi.delete((Long)null, stallId);
         this.allocStallService.deleteStall(stallId);
         this.canteenCustomBusiness.stallRemoveHandler(stallId);
         MqUtil.sendDataChange(stallId, LeMqConstant.DataChangeType.REMOVE, LeMqConstant.Topic.DATA_CHANGE_SHOP_STALL);
      }
   }
}
