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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.canteen.core.allocation.api.AllocCanteenApi;
import com.bonus.canteen.core.common.constant.LeMqConstant;
import com.bonus.canteen.core.common.enums.LeLevelEnum;
import com.bonus.canteen.core.common.utils.TreeNodeUtil;
import com.bonus.canteen.core.drp.api.DrpAuthorityApi;
import com.bonus.canteen.core.menu.dto.CategoryTreeListDTO;
import com.bonus.canteen.core.menu.dto.MenuMaterialCategoryAddDTO;
import com.bonus.canteen.core.menu.dto.MenuMaterialCategoryEditDTO;
import com.bonus.canteen.core.menu.dto.MenuMaterialCategoryPageDTO;
import com.bonus.canteen.core.menu.entity.MenuMaterial;
import com.bonus.canteen.core.menu.entity.MenuMaterialCategory;
import com.bonus.canteen.core.menu.mapper.MenuMaterialCategoryMapper;
import com.bonus.canteen.core.menu.mapper.MenuMaterialMapper;
import com.bonus.canteen.core.menu.mapper.MenuNutritionMapper;
import com.bonus.canteen.core.menu.service.MenuMaterialCategoryService;
import com.bonus.canteen.core.menu.vo.MenuCategoryChild;
import com.bonus.canteen.core.menu.vo.MenuCategoryTreeVO;
import com.bonus.canteen.core.menu.vo.MenuInitCategoryVO;
import com.bonus.canteen.core.menu.vo.MenuMaterialCategoryPageVO;
import com.bonus.canteen.core.order.mq.MqUtil;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.houqin.constant.DelFlagEnum;
import com.bonus.common.houqin.i18n.I18n;
import com.bonus.common.houqin.utils.id.Id;
import com.bonus.common.security.utils.SecurityUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
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 org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MenuMaterialCategoryServiceImpl extends ServiceImpl<MenuMaterialCategoryMapper, MenuMaterialCategory> implements MenuMaterialCategoryService {
   private static final Logger log = LoggerFactory.getLogger(MenuMaterialCategoryServiceImpl.class);
   @Resource
   @Lazy
   private MenuNutritionMapper menuNutritionMapper;
   @Resource
   @Lazy
   private MenuMaterialMapper menuMaterialMapper;
   @Resource
   @Lazy
   private DrpAuthorityApi drpAuthorityApi;
   @Resource
   @Lazy
   private AllocCanteenApi allocCanteenApi;
//   @Autowired
//   @Lazy
//   private DrpMaterialService drpMaterialService;

   @Override
   @Transactional(rollbackFor = {Exception.class})
   public void addMenuMaterialCategory(MenuMaterialCategoryAddDTO content) {
      Long count = this.baseMapper.selectCount(Wrappers.lambdaQuery(MenuMaterialCategory.class)
              .eq(MenuMaterialCategory::getCategoryName, content.getCategoryName())
              .eq(content.getAreaId() != null, MenuMaterialCategory::getAreaId,
                      content.getAreaId())
              .isNull(content.getAreaId() == null, MenuMaterialCategory::getAreaId)
              .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
      if (ObjectUtil.isNotNull(count) && count > 0L) {
         throw new ServiceException("menu_material_name_repeat");
      } else {
         Long parentId = content.getParentId();
         if (ObjectUtil.isNotNull(parentId) && parentId != -1L) {
            Long countParent = this.baseMapper.selectCount(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                    .eq(MenuMaterialCategory::getCategoryId, parentId));
            if (ObjectUtil.isNull(countParent) || countParent <= 0L) {
               throw new ServiceException("menu_parent_type_not_exist");
            }
         }

         String username = SecurityUtils.getUsername();
         MenuMaterialCategory materialCategory = new MenuMaterialCategory();
         BeanUtil.copyProperties(content, materialCategory, new String[0]);
         materialCategory.setCategoryId(Id.next());
         materialCategory.setCrby(username);
         this.syncAllCategoryBigCategoryAndLevel();
         MenuMaterialCategory parentCategory = this.baseMapper.selectOne(
                 Wrappers.lambdaQuery(MenuMaterialCategory.class)
                         .eq(MenuMaterialCategory::getCategoryId, content.getParentId())
                 .select(MenuMaterialCategory::getCategoryId, MenuMaterialCategory::getLevel,
                         MenuMaterialCategory::getBigCategoryId));
         materialCategory.setLevel(parentCategory.getLevel() + 1);
         materialCategory.setBigCategoryId(parentCategory.getBigCategoryId());
         this.baseMapper.insert(materialCategory);
         MqUtil.pushToTenantAllDevice(materialCategory, LeMqConstant.Topic.DRP_SYNC_MATERIAL_BIG_CATEGORY);
         this.generateCategoryNum(materialCategory.getCategoryId(), materialCategory.getParentId(), materialCategory.getCategoryType());
      }
   }

//   public Integer insertAllParentCategoryLevel(Long categoryId, Long parentId) {
//      MenuMaterialCategory parentCategory = (MenuMaterialCategory)((MenuMaterialCategoryMapper)this.baseMapper).selectOne(((LambdaQueryWrapper)Wrappers.lambdaQuery(MenuMaterialCategory.class).eq(MenuMaterialCategory::getCategoryId, parentId)).select(new SFunction[]{MenuMaterialCategory::getCategoryId, MenuMaterialCategory::getLevel, MenuMaterialCategory::getParentId}));
//      if (ObjectUtil.isNotEmpty(parentCategory) && ObjectUtil.isNotEmpty(parentCategory.getLevel())) {
//         ((MenuMaterialCategoryMapper)this.baseMapper).update((Object)null, (Wrapper)((LambdaUpdateWrapper)Wrappers.lambdaUpdate(MenuMaterialCategory.class).eq(MenuMaterialCategory::getCategoryId, categoryId)).set(MenuMaterialCategory::getLevel, parentCategory.getLevel() + 1));
//         return parentCategory.getLevel() + 1;
//      } else {
//         Integer parentLevel = this.insertAllParentCategoryLevel(parentCategory.getCategoryId(), parentCategory.getParentId());
//         ((MenuMaterialCategoryMapper)this.baseMapper).update((Object)null, (Wrapper)((LambdaUpdateWrapper)Wrappers.lambdaUpdate(MenuMaterialCategory.class).eq(MenuMaterialCategory::getCategoryId, parentCategory.getCategoryId())).set(MenuMaterialCategory::getLevel, parentLevel));
//         return parentLevel + 1;
//      }
//   }

   @Override
   public void generateCategoryNum(Long categoryId, Long parentId, Integer categoryType) {
      MenuMaterialCategory parentCategory = this.baseMapper.selectOne(Wrappers.lambdaQuery(MenuMaterialCategory.class)
              .eq(MenuMaterialCategory::getCategoryId, parentId)
              .eq(MenuMaterialCategory::getCategoryType, categoryType)
              .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key())
              .select(MenuMaterialCategory::getCategoryId, MenuMaterialCategory::getParentId,
                      MenuMaterialCategory::getCategoryNum));
      if (ObjectUtil.isNotEmpty(parentCategory)) {
         if (CharSequenceUtil.isNotEmpty(parentCategory.getCategoryNum())) {
            String maxCategoryNum = this.baseMapper.getCategoryChildMaxNum(parentCategory.getCategoryId(), categoryType,
                    DelFlagEnum.DEL_FALSE.key());
            String categoryNum = "";
            if (CharSequenceUtil.isNotEmpty(maxCategoryNum)) {
               String lastStr = maxCategoryNum.substring(maxCategoryNum.lastIndexOf("-") + 1);
               String lastNum = String.format("%02d", Integer.parseInt(lastStr) + 1);
               String var10000 = parentCategory.getCategoryNum();
               categoryNum = var10000 + "-" + lastNum;
            } else {
               categoryNum = parentCategory.getCategoryNum() + "-01";
            }

           this.baseMapper.update(null, Wrappers.lambdaUpdate(MenuMaterialCategory.class)
                    .eq(MenuMaterialCategory::getCategoryId, categoryId)
                    .set(MenuMaterialCategory::getCategoryNum, categoryNum));
         } else {
            this.generateCategoryNum(parentCategory.getCategoryId(), parentCategory.getParentId(), categoryType);
         }
      } else {
         this.baseMapper.update(null,Wrappers.lambdaUpdate(MenuMaterialCategory.class)
                 .eq(MenuMaterialCategory::getParentId, -1).eq(MenuMaterialCategory::getCategoryType, categoryType)
                 .set(MenuMaterialCategory::getCategoryNum, categoryType));
      }

      MenuMaterialCategory menuMaterialCategory = this.baseMapper.selectOne(Wrappers.lambdaQuery(MenuMaterialCategory.class)
              .eq(MenuMaterialCategory::getCategoryId, categoryId).eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key())
              .select(MenuMaterialCategory::getCategoryNum));
      if (!ObjectUtil.isNotEmpty(menuMaterialCategory) || !CharSequenceUtil.isNotEmpty(menuMaterialCategory.getCategoryNum())) {
         this.generateCategoryNum(categoryId, parentId, categoryType);
      }
   }

   @Override
   public void areaInitMenuCategory(Long areaId) {
      Long l = this.baseMapper.selectCount(Wrappers.lambdaQuery(MenuMaterialCategory.class)
              .eq(MenuMaterialCategory::getAreaId, areaId)
              .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
      if (l <= 0L) {
         MenuMaterialCategory materialCategory = new MenuMaterialCategory();
         materialCategory.setCategoryId(Id.next());
         materialCategory.setCategoryName("原料");
         materialCategory.setParentId(-1L);
         materialCategory.setCategoryType(1);
         materialCategory.setDelFlag(2);
         materialCategory.setAreaId(areaId);
         this.baseMapper.insert(materialCategory);
         materialCategory.setCategoryId(Id.next());
         materialCategory.setCategoryName("商品");
         materialCategory.setParentId(-1L);
         materialCategory.setCategoryType(2);
         materialCategory.setDelFlag(2);
         materialCategory.setAreaId(areaId);
         this.baseMapper.insert(materialCategory);
      }
   }

   @Override
   public Long getBigCategoryIdById(Long categoryId) {
      MenuMaterialCategory menuMaterialCategory =this.baseMapper.selectOne(Wrappers.lambdaQuery(MenuMaterialCategory.class)
              .eq(MenuMaterialCategory::getCategoryId, categoryId)
              .select(MenuMaterialCategory::getCategoryId, MenuMaterialCategory::getBigCategoryId, MenuMaterialCategory::getParentId, MenuMaterialCategory::getLevel));
      if (ObjectUtil.isNotEmpty(menuMaterialCategory.getBigCategoryId())) {
         return menuMaterialCategory.getBigCategoryId();
      } else if (ObjectUtil.isNotEmpty(menuMaterialCategory.getLevel()) && Objects.equals(menuMaterialCategory.getLevel(), LeLevelEnum.FIRST.getKey())) {
         this.baseMapper.update(null, Wrappers.lambdaUpdate(MenuMaterialCategory.class)
                 .eq(MenuMaterialCategory::getCategoryId, categoryId)
                 .set(MenuMaterialCategory::getBigCategoryId, categoryId));
         return categoryId;
      } else {
         return this.getBigCategoryId(menuMaterialCategory.getCategoryId(), menuMaterialCategory.getParentId());
      }
   }

   protected Long getBigCategoryId(Long categoryId, Long parentId) {
      MenuMaterialCategory menuMaterialCategory = this.baseMapper.selectOne(Wrappers.lambdaQuery(MenuMaterialCategory.class)
              .eq(MenuMaterialCategory::getCategoryId, parentId).select(MenuMaterialCategory::getCategoryId,
                      MenuMaterialCategory::getBigCategoryId, MenuMaterialCategory::getParentId, MenuMaterialCategory::getLevel));
      if (ObjectUtil.isNotEmpty(menuMaterialCategory.getLevel()) && Objects.equals(menuMaterialCategory.getLevel(), 0)) {
         this.baseMapper.update(null, Wrappers.lambdaUpdate(MenuMaterialCategory.class)
                 .eq(MenuMaterialCategory::getCategoryId, categoryId)
                 .set(MenuMaterialCategory::getLevel, LeLevelEnum.FIRST.getKey())
                 .set(MenuMaterialCategory::getBigCategoryId, categoryId));
         return categoryId;
      } else if (ObjectUtil.isNotEmpty(menuMaterialCategory.getBigCategoryId())) {
         return menuMaterialCategory.getBigCategoryId();
      } else {
         return ObjectUtil.isNotEmpty(menuMaterialCategory.getLevel()) && Objects.equals(menuMaterialCategory.getLevel(), LeLevelEnum.FIRST.getKey()) ? categoryId : this.getBigCategoryId(menuMaterialCategory.getCategoryId(), menuMaterialCategory.getParentId());
      }
   }

//   public void generateCategoryLevel(Long categoryId, Long parentId, Integer categoryType) {
//      MenuMaterialCategory topCategory = (MenuMaterialCategory)((MenuMaterialCategoryMapper)this.baseMapper).selectOne(((LambdaQueryWrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(MenuMaterialCategory.class).eq(MenuMaterialCategory::getParentId, -1)).eq(MenuMaterialCategory::getCategoryType, categoryType)).select(new SFunction[]{MenuMaterialCategory::getCategoryId, MenuMaterialCategory::getLevel}));
//      if (ObjectUtil.isNotEmpty(topCategory) && ObjectUtil.isEmpty(topCategory.getLevel())) {
//         ((MenuMaterialCategoryMapper)this.baseMapper).update((Object)null, (Wrapper)((LambdaUpdateWrapper)Wrappers.lambdaUpdate(MenuMaterialCategory.class).eq(MenuMaterialCategory::getCategoryId, topCategory.getCategoryId())).set(MenuMaterialCategory::getLevel, 0));
//      }
//
//      MenuMaterialCategory parentCategory = (MenuMaterialCategory)((MenuMaterialCategoryMapper)this.baseMapper).selectOne(((LambdaQueryWrapper)Wrappers.lambdaQuery(MenuMaterialCategory.class).eq(MenuMaterialCategory::getCategoryId, parentId)).select(new SFunction[]{MenuMaterialCategory::getCategoryId, MenuMaterialCategory::getLevel}));
//      if (ObjectUtil.isNotEmpty(parentCategory) && ObjectUtil.isEmpty(parentCategory.getLevel())) {
//         this.insertAllParentCategoryLevel(parentCategory.getCategoryId(), parentId);
//      }
//
//   }

//   public List<AndroidBigCategorySyncVO> syncBigCategory(AndroidCategoryDTO content) {
//      List<AndroidCategoryVO> androidCategoryVOS = this.drpMaterialService.listTop10Category((List)null, content);
//      return BeanUtil.copyToList(androidCategoryVOS, AndroidBigCategorySyncVO.class);
//   }
//
//   public List<AndroidMenuMaterialSyncVO> syncMenuMaterial(AndroidMenuMaterialSyncDTO content) {
//      String updateId = StringUtils.isNotEmpty(content.getUpdateId()) ? content.getUpdateId() : "0";
//      content.setUpdateId(updateId);
//      PageMethod.startPage(content);
//      return this.menuMaterialMapper.syncMenuMaterial(content);
//   }
//
//   public void recoveryCategory(Set<Long> categoryIds) {
//      if (ObjectUtil.isNotEmpty(categoryIds)) {
//         List<MenuMaterialCategory> categoryList = ((MenuMaterialCategoryMapper)this.baseMapper).selectList((Wrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(MenuMaterialCategory.class).in(MenuMaterialCategory::getCategoryId, categoryIds)).eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_TRUE.key()));
//         List<Long> recoverCategoryIds = (List)categoryList.stream().map(MenuMaterialCategory::getCategoryId).collect(Collectors.toList());
//         if (CollUtil.isNotEmpty(recoverCategoryIds)) {
//            ((MenuMaterialCategoryMapper)this.baseMapper).update((Object)null, (Wrapper)((LambdaUpdateWrapper)Wrappers.lambdaUpdate(MenuMaterialCategory.class).in(MenuMaterialCategory::getCategoryId, recoverCategoryIds)).set(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
//         }
//
//         Set<Long> parentIds = (Set)categoryList.stream().map(MenuMaterialCategory::getParentId).collect(Collectors.toSet());
//         this.recoveryCategory(parentIds);
//      }
//
//   }
//
   @Override
   public Page<MenuMaterialCategoryPageVO> getMenuMaterialCategoryPage(MenuMaterialCategoryPageDTO content) {
      Page<MenuMaterialCategoryPageVO> resultPage = new Page(content.getCurrent(), content.getSize());
      LambdaQueryWrapper<MenuMaterialCategory> wrapper = Wrappers.lambdaQuery();
      Long categoryId = content.getCategoryId();
      String categoryName = content.getCategoryName();
      if (ObjectUtil.isNotNull(categoryId)) {
         wrapper.eq(MenuMaterialCategory::getCategoryId, categoryId);
      }

      if (StringUtils.isNotBlank(categoryName)) {
         wrapper.like(MenuMaterialCategory::getCategoryName, categoryName);
      }

      if (ObjectUtil.isNotEmpty(content.getCategoryType())) {
         wrapper.eq(MenuMaterialCategory::getCategoryType, content.getCategoryType());
      }

      if (ObjectUtil.isNotEmpty(content.getAreaId())) {
         wrapper.and((i) -> {
            i.eq(MenuMaterialCategory::getAreaId, content.getAreaId()).or()
                    .isNull(MenuMaterialCategory::getAreaId);
         });
      }

      resultPage = this.baseMapper.selectAllList(resultPage, wrapper);
      List<MenuMaterialCategoryPageVO> records = resultPage.getRecords();
      if (CollUtil.isNotEmpty(records)) {
         Iterator var7 = records.iterator();

         while(var7.hasNext()) {
            MenuMaterialCategoryPageVO item = (MenuMaterialCategoryPageVO)var7.next();
            List<MenuCategoryChild> children = this.baseMapper.selectByParentId(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                    .eq(MenuMaterialCategory::getParentId, item.getCategoryId())
                    .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
            item.setChildren(children);
         }
      }

      return resultPage;
   }

   @Override
   public List<MenuCategoryTreeVO> getCategoryTreeList(CategoryTreeListDTO content) {
      LambdaQueryWrapper<MenuMaterialCategory> lambdaQueryWrapper = new LambdaQueryWrapper();
      lambdaQueryWrapper.eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key());
      content.setAreaAuth(this.drpAuthorityApi.listAreaAuth());
      if (ObjectUtil.isNotEmpty(content.getCategoryType())) {
         lambdaQueryWrapper.eq(MenuMaterialCategory::getCategoryType, content.getCategoryType());
      }

      if (ObjectUtil.isNotEmpty(content.getAreaId())) {
         lambdaQueryWrapper.and((i) -> {
            i.eq(MenuMaterialCategory::getAreaId, content.getAreaId()).or()
                    .isNull(MenuMaterialCategory::getAreaId);
         });
      }

      if (ObjectUtil.isNotEmpty(content.getAreaAuth())) {
         lambdaQueryWrapper.and((i) -> {
            i.in(MenuMaterialCategory::getAreaId, content.getAreaAuth()).or()
                    .isNull(MenuMaterialCategory::getAreaId);
         });
      }

      if (ObjectUtil.isNotEmpty(content.getIfAdd()) && ObjectUtil.isEmpty(content.getAreaId())) {
         lambdaQueryWrapper.isNull(MenuMaterialCategory::getAreaId);
      }

      List<MenuCategoryTreeVO> sqlList = this.baseMapper.selectCategoryTree(lambdaQueryWrapper);
      Map<Long, String> areaNameMap =
              this.allocCanteenApi.getAreaNameMap(sqlList.stream().map(MenuCategoryTreeVO::getAreaId).filter(Objects::nonNull).collect(Collectors.toList()));
      sqlList.forEach((d) -> {
         d.setAreaName(areaNameMap.get(d.getAreaId()));
         if (ObjectUtil.isNotEmpty(content.getIfAdd())) {
            String var10001 = d.getCategoryName();
            d.setCategoryName(var10001 + (StringUtils.isNotEmpty(d.getAreaName()) ? "-" + d.getAreaName() : ""));
         }

      });
      return TreeNodeUtil.assembleTree(sqlList);
   }
//
   @Override
   @Transactional(rollbackFor = {Exception.class})
   public void editMenuMaterialCategory(MenuMaterialCategoryEditDTO content) {
      Long count =
             this.baseMapper.selectCount(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                      .eq(MenuMaterialCategory::getCategoryName, content.getCategoryName())
                      .ne(MenuMaterialCategory::getCategoryId, content.getCategoryId())
                      .eq(content.getAreaId() != null, MenuMaterialCategory::getAreaId, content.getAreaId())
                      .isNull(content.getAreaId() == null, MenuMaterialCategory::getAreaId)
                      .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
      if (ObjectUtil.isNotNull(count) && count > 0L) {
         throw new ServiceException(I18n.getMessage("menu_material_name_repeat", new Object[0]));
      } else {
         MenuMaterialCategory materialCategory = new MenuMaterialCategory();
         BeanUtil.copyProperties(content, materialCategory, new String[0]);
         materialCategory.setParentId(content.getNewParentId());
         this.syncAllCategoryBigCategoryAndLevel();
         if (ObjectUtil.isNotEmpty(content.getNewParentId())) {
            MenuMaterialCategory parentCategory = this.baseMapper.selectOne(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                    .eq(MenuMaterialCategory::getCategoryId, content.getParentId())
                    .select(MenuMaterialCategory::getCategoryId, MenuMaterialCategory::getLevel,
                            MenuMaterialCategory::getBigCategoryId));
            materialCategory.setLevel(parentCategory.getLevel() + 1);
            materialCategory.setBigCategoryId(parentCategory.getBigCategoryId());
         }

         this.baseMapper.update(materialCategory, Wrappers.lambdaQuery(MenuMaterialCategory.class)
                 .eq(MenuMaterialCategory::getCategoryId, content.getCategoryId()));
         MqUtil.pushToTenantAllDevice(materialCategory, LeMqConstant.Topic.DRP_SYNC_MATERIAL_BIG_CATEGORY);
         ArrayList<Long> categoryIdList = Lists.newArrayList(new Long[]{materialCategory.getCategoryId()});
         if (ObjectUtil.isNotEmpty(content.getNewParentId())) {
            this.updateChildCategoryLevel(categoryIdList, materialCategory.getLevel());
         }

      }
   }

   protected void updateChildCategoryLevel(List<Long> categoryIdList, Integer level) {
      List<MenuMaterialCategory> childCategory = this.baseMapper.selectList(Wrappers.lambdaQuery(MenuMaterialCategory.class)
              .in(MenuMaterialCategory::getParentId, categoryIdList)
              .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
      if (CollUtil.isNotEmpty(childCategory)) {
         List<Long> childCategoryIdList = childCategory.stream().map(MenuMaterialCategory::getCategoryId).collect(Collectors.toList());
         this.baseMapper.update(null, Wrappers.lambdaUpdate(MenuMaterialCategory.class)
                 .in(MenuMaterialCategory::getCategoryId, childCategoryIdList)
                 .set(MenuMaterialCategory::getLevel, level + 1));
         this.updateChildCategoryLevel(childCategoryIdList, level + 1);
      }
   }

   @Override
   public void removeMenuMaterialCategory(Long categoryId) {
      this.removeCategoryById(categoryId);
      MqUtil.pushToTenantAllDevice((Object)null, LeMqConstant.Topic.DRP_SYNC_MATERIAL_BIG_CATEGORY);
   }
   @Override
   public void initMenuCategory() {
      List<MenuInitCategoryVO> initCategoryList = this.menuNutritionMapper.selectTypeList();
      if (CollUtil.isEmpty(initCategoryList)) {
         log.info("***[初始化原料类别]_未查询到基础表类别信息**********");
      } else {
         Map<String, Long> categoryMap = Maps.newHashMap();
         Long defaultCategoryId = this.baseMapper.selectCategoryIdByWrapper(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                 .eq(MenuMaterialCategory::getCategoryName, "默认")
                 .eq(MenuMaterialCategory::getParentId, -1L)
                 .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
         MenuMaterialCategory materialCategory = new MenuMaterialCategory();
         if (ObjectUtil.isNull(defaultCategoryId)) {
            defaultCategoryId = Id.next();
            materialCategory.setCategoryId(defaultCategoryId);
            materialCategory.setCategoryName("默认");
            materialCategory.setParentId(-1L);
            this.baseMapper.insert(materialCategory);
         }

         Long finalDefaultCategoryId = defaultCategoryId;
         initCategoryList.forEach((m) -> {
            String bigType = m.getBigType();
            String littleType = m.getLittleType();
            Long bigTypeCategoryId = categoryMap.get(bigType);
            Long littleTypeCategoryId = categoryMap.get(littleType);
            if (ObjectUtil.isNull(bigTypeCategoryId)) {
               bigTypeCategoryId = this.baseMapper.selectCategoryIdByWrapper(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                       .eq(MenuMaterialCategory::getCategoryName, bigType)
                       .eq(MenuMaterialCategory::getParentId, finalDefaultCategoryId)
                       .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
               if (ObjectUtil.isNull(bigTypeCategoryId)) {
                  bigTypeCategoryId = Id.next();
                  materialCategory.setCategoryId(bigTypeCategoryId);
                  materialCategory.setCategoryName(bigType);
                  materialCategory.setParentId(finalDefaultCategoryId);
                  this.baseMapper.insert(materialCategory);
                  categoryMap.put(bigType, bigTypeCategoryId);
               }
            }
            if (ObjectUtil.isNull(littleTypeCategoryId)) {
               littleTypeCategoryId = this.baseMapper.selectCategoryIdByWrapper(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                       .eq(MenuMaterialCategory::getCategoryName, littleType)
                       .eq(MenuMaterialCategory::getParentId, bigTypeCategoryId)
                       .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
               if (ObjectUtil.isNull(littleTypeCategoryId)) {
                  littleTypeCategoryId = Id.next();
                  materialCategory.setCategoryId(littleTypeCategoryId);
                  materialCategory.setCategoryName(littleType);
                  materialCategory.setParentId(bigTypeCategoryId);
                  this.baseMapper.insert(materialCategory);
                  categoryMap.put(littleType, littleTypeCategoryId);
               }
            }
         });
      }
   }

   private void removeCategoryById(Long categoryId) {
      if (ObjectUtil.isNull(categoryId)) {
         throw new ServiceException("menu_system_param_error");
      } else {
         List<Long> childIdList = this.baseMapper.selectChildId(categoryId);
         if (CollUtil.isNotEmpty(childIdList)) {
            Iterator var3 = childIdList.iterator();

            while(var3.hasNext()) {
               Long childId = (Long)var3.next();
               this.removeCategoryById(childId);
            }
         }

         Long count = this.menuMaterialMapper.selectCount(Wrappers.lambdaQuery(MenuMaterial.class)
                 .eq(MenuMaterial::getCategoryId, categoryId)
                 .eq(MenuMaterial::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
         if (ObjectUtil.isNotNull(count) && count > 0L) {
            throw new ServiceException("menu_category_use_del");
         } else {
            this.baseMapper.delete(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                    .eq(MenuMaterialCategory::getCategoryId, categoryId));
         }
      }
   }

   @Override
   public void syncAllCategoryBigCategoryAndLevel() {
      Long checkIfExistLevel = this.baseMapper.selectCount(new LambdaQueryWrapper<>(MenuMaterialCategory.class)
              .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key())
              .isNull(MenuMaterialCategory::getBigCategoryId).or()
              .isNull(MenuMaterialCategory::getLevel));
      log.info("[货品类别_所有货品类别的所属大类和等级]_未赋值大类id和等级的类别数量：{}", checkIfExistLevel);
      if (checkIfExistLevel <= 0L) {
         log.info("[货品类别_所有货品类别的所属大类和等级]_不需要同步,跳过!");
      } else {
         List<MenuMaterialCategory> topCategoryList = this.baseMapper.selectList(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                 .eq(MenuMaterialCategory::getParentId, -1).eq(MenuMaterialCategory::getDelFlag,
                         DelFlagEnum.DEL_FALSE.key()));
         Iterator var3 = topCategoryList.iterator();

         while(true) {
            List menuMaterialCategoryList;
            do {
               if (!var3.hasNext()) {
                  return;
               }

               MenuMaterialCategory topCategory = (MenuMaterialCategory)var3.next();
               this.baseMapper.update(null,Wrappers.lambdaUpdate(MenuMaterialCategory.class)
                       .eq(MenuMaterialCategory::getCategoryId, topCategory.getCategoryId())
                       .set(MenuMaterialCategory::getLevel, 0)
                       .set(MenuMaterialCategory::getBigCategoryId, topCategory.getCategoryId()));
               menuMaterialCategoryList = this.baseMapper.selectList(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                       .eq(MenuMaterialCategory::getParentId, topCategory.getCategoryId()));
            } while(CollUtil.isEmpty(menuMaterialCategoryList));

            Iterator var6 = menuMaterialCategoryList.iterator();

            while(var6.hasNext()) {
               MenuMaterialCategory menuMaterialCategory = (MenuMaterialCategory)var6.next();
              this.baseMapper.update(null, Wrappers.lambdaUpdate(MenuMaterialCategory.class)
                       .eq(MenuMaterialCategory::getCategoryId, menuMaterialCategory.getCategoryId())
                       .set(MenuMaterialCategory::getLevel, LeLevelEnum.FIRST.getKey())
                       .set(MenuMaterialCategory::getBigCategoryId, menuMaterialCategory.getCategoryId()));
               menuMaterialCategory.setLevel(LeLevelEnum.FIRST.getKey());
               menuMaterialCategory.setBigCategoryId(menuMaterialCategory.getCategoryId());
               this.setChildBigCategoryAndLevel(menuMaterialCategory, LeLevelEnum.FIRST.getKey() + 1, menuMaterialCategory.getCategoryId());
            }
         }
      }
   }

   public void setChildBigCategoryAndLevel(MenuMaterialCategory parentCategory, Integer level, Long bigCategoryId) {
      List<MenuMaterialCategory> childCategoryList = this.baseMapper.selectList(Wrappers.lambdaQuery(MenuMaterialCategory.class)
              .eq(MenuMaterialCategory::getParentId, parentCategory.getCategoryId()));
      if (!CollUtil.isEmpty(childCategoryList)) {
         Iterator var5 = childCategoryList.iterator();

         while(var5.hasNext()) {
            MenuMaterialCategory childCategory = (MenuMaterialCategory)var5.next();
            this.baseMapper.update(null, Wrappers.lambdaUpdate(MenuMaterialCategory.class)
                    .eq(MenuMaterialCategory::getCategoryId, childCategory.getCategoryId())
                    .set(MenuMaterialCategory::getLevel, level)
                    .set(MenuMaterialCategory::getBigCategoryId, bigCategoryId));
            this.setChildBigCategoryAndLevel(childCategory, level + 1, bigCategoryId);
         }

      }
   }

}
