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

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.canteen.core.data.dataset.Executors;
import com.bonus.canteen.core.menu.constant.MenuConstant;
import com.bonus.canteen.core.menu.constant.MenuCustomIfUseEnum;
import com.bonus.canteen.core.menu.entity.MenuCustomDict;
import com.bonus.canteen.core.menu.mapper.MenuCustomDictMapper;
import com.bonus.canteen.core.menu.service.MenuCustomDictService;
import com.bonus.canteen.core.merchant.api.MercMerchantApi;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.houqin.constant.LeConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class MenuCustomDictServiceImpl extends ServiceImpl<MenuCustomDictMapper, MenuCustomDict> implements MenuCustomDictService {
   private static final Logger log = LoggerFactory.getLogger(MenuCustomDictServiceImpl.class);
   @Resource
   private MercMerchantApi mercMerchantApi;

   @Override
   public void addMenuCustomDictBatch(Long merchantId) {
      Executors.doInTenant(merchantId, (status) -> {
         this.baseMapper.delete(null);
         List<Integer> customIdList = new ArrayList<>();

         for(int i = MenuConstant.MIN_CUSTOM_ID; i <= MenuConstant.MAX_CUSTOM_ID; ++i) {
            customIdList.add(i);
         }

         this.baseMapper.insertBatch(customIdList);
      });
   }

   @Override
   public synchronized Integer getNoRepeatCustomId(int criNum) {
      boolean limitFlag = this.mercMerchantApi.checkCurrentMerchantLimitFlag();
      Integer customId = this.baseMapper.selectMinCustomId(MenuCustomIfUseEnum.UNUSED.key());
      if (customId != null && customId <= LeConstants.MAX_CUST_LIMIT_ID) {
         int updateCount = this.baseMapper.update(null, Wrappers.lambdaUpdate(MenuCustomDict.class)
                 .eq(MenuCustomDict::getCustomId, customId)
                 .eq(MenuCustomDict::getIfUse, MenuCustomIfUseEnum.UNUSED.key())
                 .set(MenuCustomDict::getIfUse, MenuCustomIfUseEnum.IS_USED.key()));
         if (updateCount <= 0) {
            if (criNum >= MenuConstant.MAX_CUSTOM_ID) {
               throw new ServiceException("menu_out_while");
            } else {
               ++criNum;
               return this.getNoRepeatCustomId(criNum);
            }
         } else {
            return customId;
         }
      } else if (limitFlag) {
         throw new ServiceException("menu_custom_max_over");
      } else {
         return -1;
      }
   }
}
