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.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.canteen.core.allocation.api.AllocCanteenApi;
import com.bonus.canteen.core.common.config.excel.EasyExcelUtil;
import com.bonus.canteen.core.common.constant.LeMqConstant;
import com.bonus.canteen.core.common.enums.LeLevelEnum;
import com.bonus.canteen.core.common.redis.RedisUtil;
import com.bonus.canteen.core.common.utils.TenantContextHolder;
import com.bonus.canteen.core.common.utils.TreeNodeUtil;
import com.bonus.canteen.core.drp.api.DrpAuthorityApi;
import com.bonus.canteen.core.drp.api.DrpServiceApi;
import com.bonus.canteen.core.drp.api.DrpUnitServiceApi;
import com.bonus.canteen.core.drp.mapper.DrpInventoryMapper;
import com.bonus.canteen.core.drp.mapper.DrpMaterialProcureMapper;
import com.bonus.canteen.core.drp.model.DrpInventory;
import com.bonus.canteen.core.drp.model.DrpMaterialProcure;
import com.bonus.canteen.core.drp.model.DrpUnit;
import com.bonus.canteen.core.drp.po.LeastPriceAndDateModel;
import com.bonus.canteen.core.drp.service.DrpMaterialProcureService;
import com.bonus.canteen.core.menu.api.MenuDishesApi;
import com.bonus.canteen.core.menu.constant.*;
import com.bonus.canteen.core.menu.dto.*;
import com.bonus.canteen.core.menu.easyexcel.MenuMaterialProductImportListener;
import com.bonus.canteen.core.menu.entity.*;
import com.bonus.canteen.core.menu.mapper.*;
import com.bonus.canteen.core.menu.po.MenuMaterialCategoryModel;
import com.bonus.canteen.core.menu.service.*;
import com.bonus.canteen.core.menu.utils.PinyinUtil;
import com.bonus.canteen.core.menu.vo.*;
import com.bonus.canteen.core.order.mq.MqUtil;
import com.bonus.canteen.core.supermarket.api.SupermarketApi;
import com.bonus.canteen.core.supermarket.model.SupermarketProduct;
import com.bonus.canteen.core.supermarket.vo.MqSupermarketProductVO;
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.constant.LeConstants;
import com.bonus.common.houqin.i18n.I18n;
import com.bonus.common.houqin.utils.LeBeanUtil;
import com.bonus.common.houqin.utils.id.Id;
import com.bonus.common.security.utils.SecurityUtils;
import com.github.pagehelper.page.PageMethod;
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.core.task.AsyncTaskExecutor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.bonus.canteen.core.common.utils.BaseTreeNode;

@Service
public class MenuMaterialServiceImpl extends ServiceImpl<MenuMaterialMapper, MenuMaterial> implements MenuMaterialService {
    private static final Logger log = LoggerFactory.getLogger(MenuMaterialServiceImpl.class);
    @Resource
    @Lazy
    private MenuMaterialService menuMaterialService;
    @Resource
    @Lazy
    private MenuMaterialNutritionMapper menuMaterialNutritionMapper;
    @Resource
    @Lazy
    private MenuNutritionMapper menuNutritionMapper;
    @Resource
    @Lazy
    private MenuMaterialCategoryMapper menuMaterialCategoryMapper;
    @Resource
    @Lazy
    private MenuMaterialCategoryService menuMaterialCategoryService;
    @Resource
    @Lazy
    private MenuMaterialFoodSafeConfigMapper menuMaterialFoodSafeConfigMapper;
    @Resource
    @Lazy
    private MenuMaterialFunctionMapper menuMaterialFunctionMapper;
    @Resource
    @Lazy
    private DrpMaterialProcureService drpMaterialProcureService;
    @Resource
    @Lazy
    private DrpMaterialProcureMapper drpMaterialProcureMapper;
    @Resource
    @Lazy
    private DrpAuthorityApi drpAuthorityApi;
    @Resource
    @Lazy
    private DrpServiceApi drpServiceApi;
    @Resource
    @Lazy
    private SupermarketApi supermarketApi;
    @Resource
    private MenuDishesApi menuDishesApi;
    @Resource
    @Lazy
    private MenuMaterialDishesMapper menuMaterialDishesMapper;
    @Resource
    @Lazy
    private DrpInventoryMapper drpInventoryMapper;
    @Resource
    private MenuMaterialRegisterPicService menuMaterialRegisterPicService;
    @Resource
    @Lazy
    private MenuCustomAsyncService menuCustomAsyncService;
    @Resource(
            name = "yunshitangTaskExecutor"
    )
    @Lazy
    private AsyncTaskExecutor asyncTaskExecutor;

    @Resource
    @Lazy
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    @Lazy
    private AllocCanteenApi allocCanteenApi;
    @Resource
    @Lazy
    private MenuMaterialMapper menuMaterialMapper;
    @Resource
    @Lazy
    private DrpUnitServiceApi drpUnitServiceApi;
    @Autowired
    @Lazy
    private MenuDishesService menuDishesService;

    @Override
    public Map<Long, MenuMaterialNutrition> getMenuMaterialNutrition(List<Long> materialIdList) {
        List<MenuMaterialNutrition> menuMaterialNutritions = this.menuMaterialNutritionMapper
                .selectList(Wrappers.lambdaQuery(MenuMaterialNutrition.class)
                        .in(MenuMaterialNutrition::getMaterialId, materialIdList));
        Iterator var4;
        Long materialId;
        if (CollUtil.isNotEmpty(menuMaterialNutritions)) {
            Map<Long, MenuMaterialNutrition> collect = (Map) menuMaterialNutritions.stream().collect(Collectors.toMap(MenuMaterialNutrition::getMaterialId, (e) -> {
                return e;
            }, (o, n) -> {
                return o;
            }));
            if (menuMaterialNutritions.size() == materialIdList.size()) {
                return collect;
            } else {
                var4 = materialIdList.iterator();

                while (var4.hasNext()) {
                    materialId = (Long) var4.next();
                    Long finalMaterialId = materialId;
                    collect.computeIfAbsent(materialId, (k) -> {
                        MenuNutritionDetailVO result = this.menuMaterialService
                                .getMenuNutritionDetailById(this.getByMaterialId(finalMaterialId).getNutritionId());
                        MenuMaterialNutrition menuMaterialNutrition = new MenuMaterialNutrition();
                        BeanUtil.copyProperties(result, menuMaterialNutrition, new String[0]);
                        return menuMaterialNutrition;
                    });
                }

                return collect;
            }
        } else {
            Map<Long, MenuMaterialNutrition> collect = new HashMap();
            var4 = materialIdList.iterator();

            while (var4.hasNext()) {
                materialId = (Long) var4.next();
                MenuNutritionDetailVO result = this.menuMaterialService
                        .getMenuNutritionDetailById(this.getByMaterialId(materialId).getNutritionId());
                MenuMaterialNutrition menuMaterialNutrition = new MenuMaterialNutrition();
                BeanUtil.copyProperties(result, menuMaterialNutrition, new String[0]);
                collect.put(materialId, menuMaterialNutrition);
            }

            return collect;
        }
    }


    @Override
    public MenuMaterial getByMaterialId(Long materialId) {
        return this.baseMapper.selectOne(new LambdaQueryWrapper<>(MenuMaterial.class)
                .eq(MenuMaterial::getMaterialId, materialId)
                .eq(MenuMaterial::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
    }

    @Override
    public MenuNutritionDetailVO getMenuNutritionDetailById(Long nutritionId) {
        return this.menuNutritionMapper.selectMenuNutritionDetailById(nutritionId);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Long addMenuMaterial(MenuMaterialAddDTO content) {
        Long checkNameUnit = this.baseMapper.selectCount(Wrappers.lambdaQuery(MenuMaterial.class)
                .eq(MenuMaterial::getMaterialName, content.getMaterialName())
                .eq(MenuMaterial::getUnitId, content.getUnitId())
                .eq(content.getAreaId() != null, MenuMaterial::getAreaId, content.getAreaId())
                .isNull(content.getAreaId() == null, MenuMaterial::getAreaId)
                .eq(MenuMaterial::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
        if (checkNameUnit > 0L) {
            throw new ServiceException("menu_material_name_unit_repeat");
        } else {
            if (CharSequenceUtil.isNotEmpty(content.getBarCode())) {
                Long checkBarCode = this.baseMapper.selectCount(Wrappers.lambdaQuery(MenuMaterial.class)
                        .eq(MenuMaterial::getBarCode, content.getBarCode())
                        .eq(content.getAreaId() != null, MenuMaterial::getAreaId, content.getAreaId())
                        .isNull(content.getAreaId() == null, MenuMaterial::getAreaId)
                        .eq(MenuMaterial::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
                if (checkBarCode > 0L) {
                    throw new ServiceException("menu_qr_code_repeat");
                }
            }

            MenuMaterial material = new MenuMaterial();
            BeanUtil.copyProperties(content, material, new String[0]);
            MenuMaterialCategoryModel categoryInfo = this.menuMaterialCategoryMapper.getCategoryInfoById(material.getCategoryId());
            if (CharSequenceUtil.isEmpty(categoryInfo.getCategoryNum())) {
                this.menuMaterialCategoryService.generateCategoryNum(material.getCategoryId(), categoryInfo.getParentId(), categoryInfo.getCategoryType());
            }

            String materialCode = generateMaterialCode();
            material.setPinyinInitials(PinyinUtil.getFirstLetterFromChinese(material.getMaterialName()));
            material.setPinyinFull(PinyinUtil.convertChineseToPinyin(material.getMaterialName()));
            material.setMaterialCode(materialCode);
            material.setMaterialId(Id.next());
            if (categoryInfo.getParentId() != -1L) {
                this.menuMaterialCategoryService.syncAllCategoryBigCategoryAndLevel();
                Long bigCategoryId = this.menuMaterialCategoryService.getBigCategoryIdById(material.getCategoryId());
                material.setBigCategoryId(bigCategoryId);
            }

            MqUtil.pushToTenantAllDevice(material, LeMqConstant.Topic.DRP_SYNC_MATERIAL);
            this.baseMapper.insert(material);
            if (content.getMenuMaterialNutritionDTO() != null) {
                MenuMaterialNutrition menuMaterialNutrition = new MenuMaterialNutrition();
                BeanUtil.copyProperties(content.getMenuMaterialNutritionDTO(), menuMaterialNutrition, new String[0]);
                menuMaterialNutrition.setMaterialId(material.getMaterialId());
                menuMaterialNutrition.setCategoryId(material.getCategoryId());
                this.menuMaterialNutritionMapper.insert(menuMaterialNutrition);
            }

            if (ObjectUtil.isNotEmpty(content.getSafeConfigDTO())) {
                MenuMaterialFoodSafeConfig menuMaterialFoodSafeConfig = new MenuMaterialFoodSafeConfig();
                BeanUtil.copyProperties(content.getSafeConfigDTO(), menuMaterialFoodSafeConfig, new String[0]);
                menuMaterialFoodSafeConfig.setMaterialId(material.getMaterialId());
                this.menuMaterialFoodSafeConfigMapper.insert(menuMaterialFoodSafeConfig);
            }

            HashSet cutProcessSet;
            if (CollUtil.isNotEmpty(content.getFirstProcessList())) {
                cutProcessSet = new HashSet(content.getFirstProcessList());
                if (cutProcessSet.size() != content.getFirstProcessList().size()) {
                    throw new ServiceException("menu_material_first_function_name_repeat");
                }

                content.getFirstProcessList().forEach((s) -> {
                    MenuMaterialFunction menuMaterialFunction = new MenuMaterialFunction();
                    menuMaterialFunction.setMaterialId(material.getMaterialId());
                    menuMaterialFunction.setType(MaterialProcessEnum.PRELIMINARY.key());
                    menuMaterialFunction.setContent(s);
                    this.menuMaterialFunctionMapper.insert(menuMaterialFunction);
                });
            }

            if (CollUtil.isNotEmpty(content.getCutProcessList())) {
                cutProcessSet = new HashSet(content.getCutProcessList());
                if (cutProcessSet.size() != content.getCutProcessList().size()) {
                    throw new ServiceException("menu_material_cut_function_name_repeat");
                }

                content.getCutProcessList().forEach((s) -> {
                    MenuMaterialFunction menuMaterialFunction = new MenuMaterialFunction();
                    menuMaterialFunction.setMaterialId(material.getMaterialId());
                    menuMaterialFunction.setType(MaterialProcessEnum.CUTTING_AND_MATCHING.key());
                    menuMaterialFunction.setContent(s);
                    this.menuMaterialFunctionMapper.insert(menuMaterialFunction);
                });
            }

            if (CollUtil.isNotEmpty(content.getDrpMaterialProcureAddDTOList())) {
                content.getDrpMaterialProcureAddDTOList().forEach((drpMaterialProcureAddDTO) -> {
                    drpMaterialProcureAddDTO.setMaterialId(material.getMaterialId());
                });
                this.drpMaterialProcureService.add(content.getDrpMaterialProcureAddDTOList());
            } else {
                this.drpMaterialProcureMapper.delete(Wrappers.lambdaQuery(DrpMaterialProcure.class).eq(DrpMaterialProcure::getMaterialId, material.getMaterialId()));
            }

            return material.getMaterialId();
        }
    }

    @Override
    public List<MenuMaterialPageVO> getMenuMaterialPage(MenuMaterialPageDTO content) {
        List<Long> categoryIdList = content.getCategoryIdList();
        List<MenuCategoryTreeVO> categoryTreeList;
        List<MenuMaterialFunction> preliminaryProcessFunctions;
        List<MenuMaterialFunction> cuttingProcessFunctions;
        if (CollUtil.isNotEmpty(categoryIdList)) {
            LambdaQueryWrapper<MenuMaterialCategory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key());
            if (ObjectUtil.isNotEmpty(content.getMaterialType())) {
                lambdaQueryWrapper.eq(MenuMaterialCategory::getCategoryType, content.getMaterialType());
            }

            categoryTreeList = this.menuMaterialCategoryMapper.selectCategoryTree(lambdaQueryWrapper);
            List<MenuCategoryTreeVO> childList = TreeNodeUtil.getChildList(categoryTreeList, categoryIdList);
            if (childList != null && !childList.isEmpty()) {
                categoryIdList = childList.stream()
                        .map(BaseTreeNode::getId)
                        .collect(Collectors.toList());
            }
        }

        content.setAreaAuth(this.drpAuthorityApi.listAreaAuth());
        PageMethod.startPage(content);
        List<MenuMaterialPageVO> records = this.baseMapper
                .selectAllList(DelFlagEnum.DEL_FALSE.key(), content, categoryIdList);
        List<Long> materialIdList = records.stream().map(MenuMaterialPageVO::getMaterialId).collect(Collectors.toList());
        if (CollUtil.isEmpty(materialIdList)) {
            return records;
        } else {
            preliminaryProcessFunctions = this.menuMaterialFunctionMapper.selectList(Wrappers.lambdaQuery(MenuMaterialFunction.class)
                    .in(MenuMaterialFunction::getMaterialId, materialIdList)
                    .eq(MenuMaterialFunction::getType, MaterialProcessEnum.PRELIMINARY.key())
                    .select(MenuMaterialFunction::getContent, MenuMaterialFunction::getMaterialId));
            cuttingProcessFunctions = this.menuMaterialFunctionMapper.selectList(Wrappers.lambdaQuery(MenuMaterialFunction.class)
                    .in(MenuMaterialFunction::getMaterialId, materialIdList)
                    .eq(MenuMaterialFunction::getType, MaterialProcessEnum.CUTTING_AND_MATCHING.key())
                    .select(MenuMaterialFunction::getContent, MenuMaterialFunction::getMaterialId));

            records.forEach(item -> {
                item.setFirstProcessList(preliminaryProcessFunctions.stream()
                        .filter(d -> Objects.equals(d.getMaterialId(), item.getMaterialId()))
                        .map(MenuMaterialFunction::getContent)
                        .collect(Collectors.toList()));
                item.setCutProcessList(cuttingProcessFunctions.stream()
                        .filter(d -> Objects.equals(d.getMaterialId(), item.getMaterialId()))
                        .map(MenuMaterialFunction::getContent)
                        .collect(Collectors.toList()));

                MenuMaterialFoodSafeConfigPageVO configVO = this.menuMaterialFoodSafeConfigMapper.getSafeConfig(item.getMaterialId());
                item.setSafeConfigDTO(configVO);
            });

            List<LeastPriceAndDateModel> leastPriceAndDateModelList = this.drpServiceApi.listLeastPriceAndDate(materialIdList);
            if (CollUtil.isEmpty(leastPriceAndDateModelList)) {
                return records;
            } else {
                Map<String, LeastPriceAndDateModel> leastPriceAndDateMap = leastPriceAndDateModelList.stream()
                        .collect(Collectors.toMap(
                                leastPriceAndDateModel -> leastPriceAndDateModel.getMaterialId() + "_" + leastPriceAndDateModel.getUnitId(),
                                leastPriceAndDateModel -> leastPriceAndDateModel
                        ));

                List<LeastPriceAndDateModel> monthPriceModels = this.drpServiceApi.listMonthPrice(materialIdList);
                if (CollUtil.isEmpty(monthPriceModels)) {
                    return records;
                } else {
                    Map<String, Integer> monthPriceMap = monthPriceModels.stream()
                            .collect(Collectors.toMap(
                                    leastPriceAndDateModel -> leastPriceAndDateModel.getMaterialId() + "_" + leastPriceAndDateModel.getUnitId(),
                                    LeastPriceAndDateModel::getMonthAvgPrice
                            ));

                    records.forEach(item -> {
                        String key = item.getMaterialId() + "_" + item.getUnitId();
                        LeastPriceAndDateModel leastPriceAndDateModel = leastPriceAndDateMap.get(key);
                        if (!ObjectUtil.isEmpty(leastPriceAndDateModel)) {
                            item.setLeastIntoPrice(leastPriceAndDateModel.getLeastIntoPrice());
                            item.setLeastIntoDate(leastPriceAndDateModel.getLeastIntoDate());
                            item.setMonthAvgPrice(monthPriceMap.get(key));
                        }
                    });

                    return records;
                }
            }
        }
    }

    @Override
    public MenuMaterialVO getMaterialByMaterialId(Long materialId) {
        if (ObjectUtil.isEmpty(materialId)) {
            throw new ServiceException("menu_material_id_is_null");
        } else {
            return this.baseMapper.getMaterialByMaterialId(materialId);
        }
    }

    @Override
    public void editMenuMaterial(MenuMaterialEditDTO content) {
        Long checkNameUnit = this.baseMapper.selectCount(Wrappers.lambdaQuery(MenuMaterial.class)
                .eq(MenuMaterial::getMaterialName, content.getMaterialName())
                .eq(MenuMaterial::getUnitId, content.getUnitId())
                .eq(content.getAreaId() != null, MenuMaterial::getAreaId, content.getAreaId())
                .isNull(content.getAreaId() == null, MenuMaterial::getAreaId)
                .eq(MenuMaterial::getDelFlag, DelFlagEnum.DEL_FALSE.key())
                .ne(MenuMaterial::getMaterialId, content.getMaterialId()));
        if (checkNameUnit > 0L) {
            throw new ServiceException("menu_material_name_unit_repeat");
        } else {
            if (CharSequenceUtil.isNotEmpty(content.getBarCode())) {
                Long checkBarCode = this.baseMapper.selectCount(Wrappers.lambdaQuery(MenuMaterial.class)
                        .eq(MenuMaterial::getBarCode, content.getBarCode())
                        .eq(content.getAreaId() != null, MenuMaterial::getAreaId, content.getAreaId())
                        .isNull(content.getAreaId() == null, MenuMaterial::getAreaId)
                        .eq(MenuMaterial::getDelFlag, DelFlagEnum.DEL_FALSE.key())
                        .ne(MenuMaterial::getMaterialId, content.getMaterialId()));
                if (checkBarCode > 0L) {
                    throw new ServiceException("ServiceException");
                }
            }

            MenuMaterial material = new MenuMaterial();
            BeanUtil.copyProperties(content, material, new String[0]);
            if (StringUtils.isNotBlank(content.getMaterialName())) {
                material.setPinyinInitials(PinyinUtil.getFirstLetterFromChinese(material.getMaterialName()));
                material.setPinyinFull(PinyinUtil.convertChineseToPinyin(material.getMaterialName()));
            }

            this.menuMaterialCategoryService.syncAllCategoryBigCategoryAndLevel();
            Long bigCategoryId = this.menuMaterialCategoryService.getBigCategoryIdById(material.getCategoryId());
            material.setBigCategoryId(bigCategoryId);
            this.baseMapper.update(material, Wrappers.lambdaQuery(MenuMaterial.class)
                    .eq(MenuMaterial::getMaterialId, content.getMaterialId()));
            MqUtil.pushToTenantAllDevice(material, LeMqConstant.Topic.DRP_SYNC_MATERIAL);
            this.menuMaterialNutritionMapper.delete(Wrappers.lambdaQuery(MenuMaterialNutrition.class)
                    .eq(MenuMaterialNutrition::getMaterialId, content.getMaterialId()));
            if (content.getMenuMaterialNutritionDTO() != null) {
                MenuMaterialNutrition menuMaterialNutrition = new MenuMaterialNutrition();
                BeanUtil.copyProperties(content.getMenuMaterialNutritionDTO(), menuMaterialNutrition, new String[0]);
                menuMaterialNutrition.setMaterialId(material.getMaterialId());
                menuMaterialNutrition.setCategoryId(material.getCategoryId());
                this.menuMaterialNutritionMapper.insert(menuMaterialNutrition);
            }

            if (ObjectUtil.equal(content.getMaterialType(), MaterialTypeEnum.GOODS.key())) {
                List<SupermarketProduct> supermarketProductList = this.supermarketApi.listSupermarketProductById(content.getMaterialId());
                if (CollUtil.isNotEmpty(supermarketProductList)) {
                    Iterator var6 = supermarketProductList.iterator();

                    while (var6.hasNext()) {
                        SupermarketProduct supermarketProduct = (SupermarketProduct) var6.next();
                        MqSupermarketProductVO mqSupermarketProductVO =LeBeanUtil.copyCreateProperties(supermarketProduct, MqSupermarketProductVO.class);
                        MqUtil.sendDataChange(mqSupermarketProductVO, LeMqConstant.DataChangeType.UPDATE, LeMqConstant.Topic.DATA_CHANGE_SUPERMARKET_GOODS);
                    }
                }
            }

            this.menuDishesApi.asyncUpdateDishesNutrition(content.getMaterialId());
            if (ObjectUtil.isNotEmpty(content.getSafeConfigDTO())) {
                this.menuMaterialFoodSafeConfigMapper.delete(Wrappers.lambdaQuery(MenuMaterialFoodSafeConfig.class)
                        .eq(MenuMaterialFoodSafeConfig::getMaterialId, material.getMaterialId()));
                MenuMaterialFoodSafeConfig menuMaterialFoodSafeConfig = new MenuMaterialFoodSafeConfig();
                BeanUtil.copyProperties(content.getSafeConfigDTO(), menuMaterialFoodSafeConfig, new String[0]);
                menuMaterialFoodSafeConfig.setMaterialId(material.getMaterialId());
                this.menuMaterialFoodSafeConfigMapper.insert(menuMaterialFoodSafeConfig);
            }

            if (CollUtil.isNotEmpty(content.getDrpMaterialProcureAddDTOList())) {
                content.getDrpMaterialProcureAddDTOList().forEach((drpMaterialProcureAddDTO) -> {
                    drpMaterialProcureAddDTO.setMaterialId(material.getMaterialId());
                });
                this.drpMaterialProcureService.add(content.getDrpMaterialProcureAddDTOList());
            } else {
                this.drpMaterialProcureMapper.delete(Wrappers.lambdaQuery(DrpMaterialProcure.class)
                        .eq(DrpMaterialProcure::getMaterialId, material.getMaterialId()));
            }

            this.dealMaterialFunction(content);
        }
    }

    protected void dealMaterialFunction(MenuMaterialEditDTO content) {
        List<MenuMaterialFunction> firstProcessFunctions = this.menuMaterialFunctionMapper.
                selectList(Wrappers.lambdaQuery(MenuMaterialFunction.class)
                        .eq(MenuMaterialFunction::getMaterialId, content.getMaterialId())
                        .eq(MenuMaterialFunction::getType, MaterialProcessEnum.PRELIMINARY.key())
                        .select(MenuMaterialFunction::getContent));
        List cutProcessFunctions;
        Iterator var4;
        String s;
        MenuMaterialFunction cutProcessFunction;
        Iterator var8;
        MenuMaterialFunction firstProcessFunction;
        if (CollUtil.isNotEmpty(content.getFirstProcessList())) {
            if (CollUtil.isNotEmpty(firstProcessFunctions)) {
                cutProcessFunctions = firstProcessFunctions.stream().map(MenuMaterialFunction::getContent).collect(Collectors.toList());
                var4 = content.getFirstProcessList().iterator();

                while(var4.hasNext()) {
                    s = (String)var4.next();
                    if (!cutProcessFunctions.contains(s)) {
                        cutProcessFunction = new MenuMaterialFunction();
                        cutProcessFunction.setMaterialId(content.getMaterialId());
                        cutProcessFunction.setType(MaterialProcessEnum.PRELIMINARY.key());
                        cutProcessFunction.setContent(s);
                        this.menuMaterialFunctionMapper.insert(cutProcessFunction);
                    }
                }

                var4 = firstProcessFunctions.iterator();

                while(var4.hasNext()) {
                    firstProcessFunction = (MenuMaterialFunction)var4.next();
                    if (!content.getFirstProcessList().contains(firstProcessFunction.getContent())) {
                        cutProcessFunction = this.menuMaterialFunctionMapper.selectOne(Wrappers.lambdaQuery(MenuMaterialFunction.class)
                                .eq(MenuMaterialFunction::getMaterialId, content.getMaterialId())
                                .eq(MenuMaterialFunction::getContent, firstProcessFunction.getContent())
                                .eq(MenuMaterialFunction::getType, MaterialProcessEnum.PRELIMINARY.key()));
                        if (this.menuDishesApi.existMaterialProcess(cutProcessFunction.getFunctionId())) {
                            throw new ServiceException("menu_material_first_function_is_use");
                        }

                        this.menuMaterialFunctionMapper.delete(Wrappers.lambdaQuery(MenuMaterialFunction.class)
                                .eq(MenuMaterialFunction::getMaterialId, content.getMaterialId())
                                .eq(MenuMaterialFunction::getContent, firstProcessFunction.getContent())
                                .eq(MenuMaterialFunction::getType, MaterialProcessEnum.PRELIMINARY.key()));
                    }
                }
            } else {
                var8 = content.getFirstProcessList().iterator();

                while(var8.hasNext()) {
                    String v8 = (String)var8.next();
                    firstProcessFunction = new MenuMaterialFunction();
                    firstProcessFunction.setMaterialId(content.getMaterialId());
                    firstProcessFunction.setType(MaterialProcessEnum.PRELIMINARY.key());
                    firstProcessFunction.setContent(v8);
                    this.menuMaterialFunctionMapper.insert(firstProcessFunction);
                }
            }
        } else if (CollUtil.isNotEmpty(firstProcessFunctions)) {
            var8 = firstProcessFunctions.iterator();

            while(var8.hasNext()) {
                MenuMaterialFunction v8Function = (MenuMaterialFunction)var8.next();
                v8Function = this.menuMaterialFunctionMapper.selectOne(Wrappers.lambdaQuery(MenuMaterialFunction.class)
                        .eq(MenuMaterialFunction::getMaterialId, content.getMaterialId())
                        .eq(MenuMaterialFunction::getContent, v8Function.getContent())
                        .eq(MenuMaterialFunction::getType, MaterialProcessEnum.PRELIMINARY.key()));
                if (this.menuDishesApi.existMaterialProcess(v8Function.getFunctionId())) {
                    throw new ServiceException("menu_material_first_function_is_use");
                }

                this.menuMaterialFunctionMapper.delete(Wrappers.lambdaQuery(MenuMaterialFunction.class)
                        .eq(MenuMaterialFunction::getMaterialId, content.getMaterialId())
                        .eq(MenuMaterialFunction::getContent, v8Function.getContent())
                        .eq(MenuMaterialFunction::getType, MaterialProcessEnum.PRELIMINARY.key()));
            }
        }

        List<MenuMaterialFunction> cutProcessFunctions_map =
                this.menuMaterialFunctionMapper.selectList(Wrappers.lambdaQuery(MenuMaterialFunction.class)
                .eq(MenuMaterialFunction::getMaterialId, content.getMaterialId())
                .eq(MenuMaterialFunction::getType, MaterialProcessEnum.CUTTING_AND_MATCHING.key())
                .select(MenuMaterialFunction::getContent));
        if (CollUtil.isNotEmpty(content.getCutProcessList())) {
            if (CollUtil.isNotEmpty(cutProcessFunctions_map)) {
                List<String> cutProcessList =
                        cutProcessFunctions_map.stream().map(MenuMaterialFunction::getContent).collect(Collectors.toList());
                Iterator var13 = content.getCutProcessList().iterator();

                MenuMaterialFunction menuMaterialFunction;
                while(var13.hasNext()) {
                    String v13 = (String)var13.next();
                    if (!cutProcessList.contains(v13)) {
                        menuMaterialFunction = new MenuMaterialFunction();
                        menuMaterialFunction.setMaterialId(content.getMaterialId());
                        menuMaterialFunction.setType(MaterialProcessEnum.CUTTING_AND_MATCHING.key());
                        menuMaterialFunction.setContent(v13);
                        this.menuMaterialFunctionMapper.insert(menuMaterialFunction);
                    }
                }

                var13 = cutProcessFunctions_map.iterator();

                while(var13.hasNext()) {
                    cutProcessFunction = (MenuMaterialFunction)var13.next();
                    if (!content.getCutProcessList().contains(cutProcessFunction.getContent())) {
                        menuMaterialFunction = (MenuMaterialFunction)this.menuMaterialFunctionMapper.selectOne(Wrappers.lambdaQuery(MenuMaterialFunction.class)
                                .eq(MenuMaterialFunction::getMaterialId, content.getMaterialId())
                                .eq(MenuMaterialFunction::getContent, cutProcessFunction.getContent())
                                .eq(MenuMaterialFunction::getType, MaterialProcessEnum.CUTTING_AND_MATCHING.key()));
                        if (this.menuDishesApi.existMaterialProcess(menuMaterialFunction.getFunctionId())) {
                            throw new ServiceException("menu_material_cut_function_is_use");
                        }

                        this.menuMaterialFunctionMapper.delete(Wrappers.lambdaQuery(MenuMaterialFunction.class)
                                .eq(MenuMaterialFunction::getMaterialId, content.getMaterialId())
                                .eq(MenuMaterialFunction::getContent, cutProcessFunction.getContent())
                                .eq(MenuMaterialFunction::getType, MaterialProcessEnum.CUTTING_AND_MATCHING.key()));
                    }
                }
            } else {
                var4 = content.getCutProcessList().iterator();

                while(var4.hasNext()) {
                    s = (String)var4.next();
                    cutProcessFunction = new MenuMaterialFunction();
                    cutProcessFunction.setMaterialId(content.getMaterialId());
                    cutProcessFunction.setType(MaterialProcessEnum.CUTTING_AND_MATCHING.key());
                    cutProcessFunction.setContent(s);
                    this.menuMaterialFunctionMapper.insert(cutProcessFunction);
                }
            }
        } else if (CollUtil.isNotEmpty(cutProcessFunctions_map)) {
            var4 = cutProcessFunctions_map.iterator();

            while(var4.hasNext()) {
                firstProcessFunction = (MenuMaterialFunction)var4.next();
                cutProcessFunction = (MenuMaterialFunction)this.menuMaterialFunctionMapper.selectOne(Wrappers.lambdaQuery(MenuMaterialFunction.class)
                        .eq(MenuMaterialFunction::getMaterialId, content.getMaterialId())
                        .eq(MenuMaterialFunction::getContent, firstProcessFunction.getContent())
                        .eq(MenuMaterialFunction::getType, MaterialProcessEnum.CUTTING_AND_MATCHING.key()));
                if (this.menuDishesApi.existMaterialProcess(cutProcessFunction.getFunctionId())) {
                    throw new ServiceException("menu_material_cut_function_is_use");
                }

                this.menuMaterialFunctionMapper.delete(Wrappers.lambdaQuery(MenuMaterialFunction.class)
                        .eq(MenuMaterialFunction::getMaterialId, content.getMaterialId())
                        .eq(MenuMaterialFunction::getContent, firstProcessFunction.getContent())
                        .eq(MenuMaterialFunction::getType, MaterialProcessEnum.CUTTING_AND_MATCHING.key()));
            }
        }

    }

    @Override
    public void removeByMaterialId(Long materialId) {
        this.deleteBatchByMaterialList(Collections.singletonList(materialId));
    }

    private void deleteBatchByMaterialList(List<Long> materialIdList) {
        Long materialDishesCount = this.menuMaterialDishesMapper.selectCount(Wrappers.lambdaQuery(MenuMaterialDishes.class)
                .in(MenuMaterialDishes::getMaterialId, materialIdList)
                .eq(MenuMaterialDishes::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
        if (ObjectUtil.isNotNull(materialIdList) && materialDishesCount > 0L) {
            throw new ServiceException("menu_material_use_del");
        } else {
            boolean checkIfUseInSupermarket = this.supermarketApi.checkIfUseInSupermarket(materialIdList);
            if (checkIfUseInSupermarket) {
                throw new ServiceException("menu_material_use_product_del");
            } else {
                Long checkIfUseDrp = this.drpInventoryMapper.selectCount(Wrappers.lambdaQuery(DrpInventory.class)
                        .in(DrpInventory::getMaterialId, materialIdList)
                        .eq(DrpInventory::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
                if (checkIfUseDrp > 0L) {
                    throw new ServiceException("menu_material_drp_is_use");
                } else {
                    this.baseMapper.update(null, new LambdaUpdateWrapper<MenuMaterial>()
                            .in(MenuMaterial::getMaterialId, materialIdList)
                            .set(MenuMaterial::getDelFlag, DelFlagEnum.DEL_TRUE.key()));
                    MqUtil.pushToTenantAllDevice((Object)null, LeMqConstant.Topic.DRP_SYNC_MATERIAL);
                    this.menuMaterialFoodSafeConfigMapper.delete(Wrappers.lambdaQuery(MenuMaterialFoodSafeConfig.class)
                            .in(MenuMaterialFoodSafeConfig::getMaterialId, materialIdList));
                    this.menuMaterialRegisterPicService.removeByMaterialId(materialIdList);
                }
            }
        }
    }
    @Override
    public void removeBatchByMaterialId(List<Long> content) {
        this.deleteBatchByMaterialList(content);
    }

    @Override
    public void leadInMaterial(MenuMaterialLeadInDTO content) {
        String username = SecurityUtils.getUsername();
        String importBaseMaterialKey = "yst:merchant-id:base-material:import:lock";
        boolean lock = RedisUtil.setNx(importBaseMaterialKey, 1, 200);
        if (!lock) {
            throw new ServiceException("menu_base_material_importing");
        } else {
            this.asyncTaskExecutor.execute(() -> {
                this.menuCustomAsyncService.leadInMaterial(content, username, importBaseMaterialKey);
            });
        }
    }

    @Override
    public List<MenuMaterialBasVO> getMenuMaterialById(Long dishesId) {
        return this.menuMaterialDishesMapper.getMenuMaterialById(dishesId);
    }

    @Override
    public void repairMaterialCategory() {
        List<MenuRepairMaterialVO> repairMaterialList = ((MenuMaterialMapper)this.baseMapper).selectAllRepairMaterialList(DelFlagEnum.DEL_FALSE.key());
        if (CollUtil.isEmpty(repairMaterialList)) {
            throw new ServiceException("menu_no_material");
        } else {
            Map<String, Long> categoryMap = Maps.newHashMap();
            Long defaultCategoryId = this.menuMaterialCategoryMapper.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.menuMaterialCategoryMapper.insert(materialCategory);
            }

            List<MenuMaterial> updateMaterialList = Lists.newArrayList();
            Long finalDefaultCategoryId = defaultCategoryId;
            repairMaterialList.forEach((m) -> {
                MenuMaterial material = new MenuMaterial();
                material.setId(m.getId());
                material.setMaterialCode(CharSequenceUtil.isBlank(m.getMaterialCode()) ? m.getNutritionCode() : m.getMaterialCode());
                Long bigTypeCategoryId = categoryMap.get(m.getBigType());
                if (ObjectUtil.isNull(bigTypeCategoryId)) {
                    bigTypeCategoryId = this.menuMaterialCategoryMapper.selectCategoryIdByWrapper(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                            .eq(MenuMaterialCategory::getCategoryName, m.getBigType())
                            .eq(MenuMaterialCategory::getParentId, finalDefaultCategoryId)
                            .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
                    if (ObjectUtil.isNull(bigTypeCategoryId)) {
                        bigTypeCategoryId = Id.next();
                        materialCategory.setCategoryId(bigTypeCategoryId);
                        materialCategory.setCategoryName(m.getBigType());
                        materialCategory.setParentId(finalDefaultCategoryId);
                        this.menuMaterialCategoryMapper.insert(materialCategory);
                        categoryMap.put(m.getBigType(), bigTypeCategoryId);
                    }
                }

                Long littleTypeCategoryId = categoryMap.get(m.getLittleType());
                if (ObjectUtil.isNull(littleTypeCategoryId)) {
                    littleTypeCategoryId = this.menuMaterialCategoryMapper.selectCategoryIdByWrapper(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                            .eq(MenuMaterialCategory::getCategoryName, m.getLittleType())
                            .eq(MenuMaterialCategory::getParentId, bigTypeCategoryId)
                            .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
                    if (ObjectUtil.isNull(littleTypeCategoryId)) {
                        littleTypeCategoryId = Id.next();
                        materialCategory.setCategoryId(littleTypeCategoryId);
                        materialCategory.setCategoryName(m.getLittleType());
                        materialCategory.setParentId(bigTypeCategoryId);
                        this.menuMaterialCategoryMapper.insert(materialCategory);
                        categoryMap.put(m.getLittleType(), littleTypeCategoryId);
                    }
                }

                material.setCategoryId(littleTypeCategoryId);
                updateMaterialList.add(material);
            });
            super.updateBatchById(updateMaterialList);
        }
    }

    @Override
    public void batchImportMaterial(MultipartFile excel) {
        String materialLockRedisKey = "yst:merchant-id:material-product:lock".replace("merchant-id", TenantContextHolder.getTenantId().toString());
        String asyncState = (String)this.stringRedisTemplate.opsForValue().get(materialLockRedisKey);
        if (StringUtils.isNotBlank(asyncState)) {
            throw new ServiceException("menu_material_import_not_commit_repeat");
        } else {
            List materialImportDTOList;
            try {
                materialImportDTOList = EasyExcelUtil.readSingleExcel(excel, new MenuMaterialImportDTO(), 1);
            } catch (Exception var9) {
                log.error("导入解析数据错误", var9);
                throw new ServiceException("acc_batch_import_data_exception");
            }

            List<MenuMaterialImportDTO> finalImportExcelList = new ArrayList<>();
            Iterator var6 = materialImportDTOList.iterator();

            while(var6.hasNext()) {
                MenuMaterialImportDTO i = (MenuMaterialImportDTO)var6.next();
                if (CharSequenceUtil.isBlank(i.getMaterialName()) && CharSequenceUtil.isBlank(i.getCategoryName()) && ObjectUtil.isEmpty(i.getUnitPrice()) && ObjectUtil.isEmpty(i.getUnitName()) && ObjectUtil.isEmpty(i.getBarCode()) && ObjectUtil.isEmpty(i.getSalesMode())) {
                    throw new ServiceException("Excel中包含空白行，请检查并删除空白行！");
                }

                if (CharSequenceUtil.isBlank(i.getMaterialName()) || CharSequenceUtil.isBlank(i.getCategoryName()) || ObjectUtil.isEmpty(i.getUnitPrice()) || ObjectUtil.isEmpty(i.getUnitName())) {
                    log.info("[导入]_存在属性为空!");
                    throw new ServiceException(I18n.getMessage("drp.into-import-file-value-is-empty", new Object[]{i.getMaterialName()}));
                }

                Long areaId = this.allocCanteenApi.getAreaIdByName(i.getAreaName());
                if (CharSequenceUtil.isNotEmpty(i.getAreaName()) && areaId == null) {
                    throw new ServiceException("区域不存在");
                }

                finalImportExcelList.add(i);
            }

            if (hasDuplicateMaterials(finalImportExcelList)) {
                throw new ServiceException("excel中原料名称单位组合重复");
            } else if (hasDuplicateBarCodes(finalImportExcelList)) {
                throw new ServiceException("excel中条码重复");
            } else {
                this.asyncImportMaterial(finalImportExcelList, MaterialTypeEnum.MATERIAL.key(), "导入原料错误信息：");
            }
        }
    }

    public static boolean hasDuplicateMaterials(List<MenuMaterialImportDTO> menuMaterials) {
        Map<String, Long> duplicates = (Map)menuMaterials.stream().filter((material) -> {
            return CharSequenceUtil.isNotBlank(material.getMaterialName());
        }).filter((material) -> {
            return CharSequenceUtil.isNotBlank(material.getUnitName());
        }).collect(Collectors.groupingBy((material) -> {
            String var10000 = material.getMaterialName();
            return var10000 + material.getUnitName();
        }, Collectors.counting()));
        return duplicates.values().stream().anyMatch((count) -> {
            return count > 1L;
        });
    }
    public static boolean hasDuplicateBarCodes(List<MenuMaterialImportDTO> menuMaterials) {
        Map<String, Long> duplicates = (Map)menuMaterials.stream().filter((s) -> {
            return CharSequenceUtil.isNotBlank(s.getBarCode());
        }).collect(Collectors.groupingBy(MenuMaterialImportDTO::getBarCode, Collectors.counting()));
        return duplicates.values().stream().anyMatch((count) -> {
            return count > 1L;
        });
    }
    private void asyncImportMaterial(List<MenuMaterialImportDTO> materialImportDTOList, Integer materialType, String errorMsg) {
        this.asyncTaskExecutor.execute(() -> {
            List<MenuMaterialImportDTO> materialImportDTOListNew = Lists.newArrayList();
            List<MenuDishesImportFail> materialImportFailList = Lists.newArrayList();
            materialImportDTOList.forEach((data) -> {
                log.info("导入查询数据库开始");
                Long areaId = this.allocCanteenApi.getAreaIdByName(data.getAreaName());
                data.setAreaId(areaId);

                try {
                    Long count = ((MenuMaterialMapper)this.baseMapper).checkMaterialNameAndUnit(data.getMaterialName(), data.getUnitName(), areaId);
                    if (count != null && count != 0L) {
                        MenuMaterial material = this.menuMaterialMapper.getMaterialByNameAndUnit(data.getMaterialName(), data.getUnitName(), DelFlagEnum.DEL_FALSE.key(), areaId);
                        BeanUtil.copyProperties(data, material, new String[0]);
                        if (data.getUnitPrice() != null) {
                            Integer unitPrice = data.getUnitPrice().multiply(new BigDecimal(100)).intValue();
                            material.setUnitPrice(unitPrice);
                        }

                        MenuMaterialCategory menuMaterialCategory = (MenuMaterialCategory)this.menuMaterialCategoryMapper
                                .selectOne(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                                        .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key())
                                        .eq(areaId != null, MenuMaterialCategory::getAreaId, areaId)
                                        .eq(MenuMaterialCategory::getCategoryName, data.getCategoryName())
                                        .select(MenuMaterialCategory::getCategoryId, MenuMaterialCategory::getParentId, MenuMaterialCategory::getCategoryType, MenuMaterialCategory::getBigCategoryId));
                        log.info("查询类别:{},{}", menuMaterialCategory.toString(), data.getCategoryName());
                        Long parentId;
                        Long categoryId;
                        if (ObjectUtil.isEmpty(menuMaterialCategory)) {
                            parentId = this.menuMaterialCategoryMapper.selectIdByType(materialType);
                            if (parentId == null) {
                                parentId = Id.next();
                                MenuMaterialCategory materialCategory = new MenuMaterialCategory();
                                materialCategory.setCategoryId(parentId);
                                materialCategory.setCategoryName("原料");
                                materialCategory.setParentId(-1L);
                                materialCategory.setCategoryType(materialType);
                                this.menuMaterialCategoryMapper.insert(materialCategory);
                            }

                            menuMaterialCategory = new MenuMaterialCategory();
                            categoryId = Id.next();
                            menuMaterialCategory.setCategoryId(categoryId);
                            menuMaterialCategory.setCategoryName(data.getCategoryName());
                            menuMaterialCategory.setParentId(parentId);
                            menuMaterialCategory.setAreaId(areaId);
                            menuMaterialCategory.setCategoryType(materialType);
                            menuMaterialCategory.setLevel(LeLevelEnum.FIRST.getKey());
                            menuMaterialCategory.setBigCategoryId(categoryId);
                            this.menuMaterialCategoryMapper.insert(menuMaterialCategory);
                            material.setCategoryId(categoryId);
                            material.setBigCategoryId(categoryId);
                        } else {
                            parentId = menuMaterialCategory.getCategoryId();
                            material.setCategoryId(parentId);
                            if (ObjectUtil.isEmpty(menuMaterialCategory.getBigCategoryId())) {
                                this.menuMaterialCategoryService.syncAllCategoryBigCategoryAndLevel();
                                categoryId = this.menuMaterialCategoryService.getBigCategoryIdById(parentId);
                                material.setBigCategoryId(categoryId);
                            } else {
                                material.setBigCategoryId(menuMaterialCategory.getBigCategoryId());
                            }
                        }

                        material.setSalesMode(data.getSalesMode());
                        material.setAreaId(areaId);
                        List<MenuNutrition> menuNutritionList = this.menuNutritionMapper.selectList(Wrappers.lambdaQuery(MenuNutrition.class)
                                .eq(MenuNutrition::getNutritionName, data.getNutritionName())
                                .select(MenuNutrition::getNutritionId));
                        if (CollUtil.isNotEmpty(menuNutritionList)) {
                            material.setNutritionId(((MenuNutrition)menuNutritionList.get(0)).getNutritionId());
                        }

                        this.menuMaterialMapper.updateById(material);
                        log.info("更新原料:{}", material);
                    } else {
                        Long checkBarCode = this.menuMaterialMapper.selectCount(Wrappers.lambdaQuery(MenuMaterial.class)
                                .eq(MenuMaterial::getBarCode, data.getBarCode()).eq(areaId != null, MenuMaterial::getAreaId, areaId)
                                .eq(MenuMaterial::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
                        if (checkBarCode > 0L) {
                            this.importMaterialFail(materialImportFailList, "条码重复!");
                            return;
                        }

                        data.setMaterialType(materialType);
                        data.setAreaId(areaId);
                        materialImportDTOListNew.add(data);
                    }
                } catch (Exception var11) {
                    this.importMaterialFail(materialImportFailList, var11.getLocalizedMessage());
                }

            });
            if (CollUtil.isNotEmpty(materialImportDTOListNew)) {
                this.importMaterial(materialImportDTOListNew);
                MqUtil.pushToTenantAllDevice((Object)null, LeMqConstant.Topic.DRP_SYNC_MATERIAL);
            }

            if (CollUtil.isNotEmpty(materialImportFailList)) {
                this.menuDishesService.importDishesFailSave(materialImportFailList);
            }

        });
    }
    private void importMaterialFail(List<MenuDishesImportFail> materialImportFailList, String localizedMessage) {
        MenuDishesImportFail materialImportFail = new MenuDishesImportFail();
        materialImportFail.setFailRow(0);
        materialImportFail.setFailType(MenuFailTypeEnum.MATERIAL.key());
        materialImportFail.setImportTime(LocalDateTime.now());
        materialImportFail.setFailReason(localizedMessage);
        materialImportFailList.add(materialImportFail);
    }
    public void importMaterial(List<MenuMaterialImportDTO> materialImportDTOList) {
        String dishesLockRedisKey = "yst:merchant-id:material-product:lock".replace("merchant-id", TenantContextHolder.getTenantId().toString());
        this.stringRedisTemplate.opsForValue().set(dishesLockRedisKey, "1", 20L, TimeUnit.MINUTES);
        try {
            materialImportDTOList.forEach((m) -> {
                MenuMaterial materialAdd = new MenuMaterial();
                BeanUtil.copyProperties(m, materialAdd, new String[0]);
                materialAdd.setMaterialId(Id.next());
                materialAdd.setPinyinInitials(PinyinUtil.getFirstLetterFromChinese(m.getMaterialName()));
                materialAdd.setPinyinFull(PinyinUtil.convertChineseToPinyin(m.getMaterialName()));
                MenuMaterialCategory menuMaterialCategory = (MenuMaterialCategory)this.menuMaterialCategoryMapper
                        .selectOne(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                                .eq(MenuMaterialCategory::getCategoryName, m.getCategoryName())
                                .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key())
                                .eq(m.getAreaId() != null, MenuMaterialCategory::getAreaId, m.getAreaId())
                                .isNull(m.getAreaId() == null, MenuMaterialCategory::getAreaId)
                                .select(MenuMaterialCategory::getCategoryId, MenuMaterialCategory::getParentId, MenuMaterialCategory::getCategoryType, MenuMaterialCategory::getBigCategoryId));
                Long unitId;
                Long categoryId;
                if (ObjectUtil.isEmpty(menuMaterialCategory)) {
                    unitId = this.menuMaterialCategoryMapper.selectIdByType(m.getMaterialType());
                    if (unitId == null) {
                        unitId = Id.next();
                        MenuMaterialCategory materialCategory2 = new MenuMaterialCategory();
                        materialCategory2.setCategoryId(unitId);
                        materialCategory2.setCategoryName("原料");
                        materialCategory2.setParentId(-1L);
                        materialCategory2.setCategoryType(m.getMaterialType());
                        this.menuMaterialCategoryMapper.insert(materialCategory2);
                    }

                    categoryId = Id.next();
                    MenuMaterialCategory materialCategory = new MenuMaterialCategory();
                    materialCategory.setCategoryId(categoryId);
                    materialCategory.setCategoryName(m.getCategoryName());
                    materialCategory.setCategoryType(m.getMaterialType());
                    materialCategory.setParentId(unitId);
                    materialCategory.setAreaId(m.getAreaId());
                    materialCategory.setLevel(LeLevelEnum.FIRST.getKey());
                    materialCategory.setBigCategoryId(categoryId);
                    this.menuMaterialCategoryMapper.insert(materialCategory);
                    this.menuMaterialCategoryService.generateCategoryNum(materialCategory.getCategoryId(), materialCategory.getParentId(), materialCategory.getCategoryType());
                    materialAdd.setCategoryId(categoryId);
                    materialAdd.setBigCategoryId(categoryId);
                } else {
                    unitId = menuMaterialCategory.getCategoryId();
                    if (ObjectUtil.isEmpty(menuMaterialCategory.getBigCategoryId())) {
                        this.menuMaterialCategoryService.syncAllCategoryBigCategoryAndLevel();
                        categoryId = this.menuMaterialCategoryService.getBigCategoryIdById(unitId);
                        materialAdd.setBigCategoryId(categoryId);
                    } else {
                        materialAdd.setBigCategoryId(menuMaterialCategory.getBigCategoryId());
                    }

                    materialAdd.setCategoryId(unitId);
                }

                unitId = this.drpUnitServiceApi.getUnitIdByNameAndArea(m.getUnitName(), m.getAreaId());
                if (ObjectUtil.isEmpty(unitId)) {
                    DrpUnit drpUnit = new DrpUnit();
                    unitId = Id.next();
                    drpUnit.setUnitId(unitId);
                    drpUnit.setAreaId(m.getAreaId());
                    drpUnit.setUnitName(m.getUnitName());
                    drpUnit.setAreaId(m.getAreaId());
                    this.drpUnitServiceApi.insertUnit(drpUnit);
                }

                materialAdd.setUnitId(unitId);
                materialAdd.setAreaId(m.getAreaId());
                materialAdd.setSalesMode(m.getSalesMode());
                if (null != m.getUnitPrice()) {
                    Integer unitPrice = m.getUnitPrice().multiply(new BigDecimal(100)).intValue();
                    materialAdd.setUnitPrice(unitPrice);
                }

                String materialCode = this.menuMaterialService.generateMaterialCode();
                materialAdd.setMaterialCode(materialCode);
                List<MenuNutrition> menuNutritionList = this.menuNutritionMapper.selectList(Wrappers.lambdaQuery(MenuNutrition.class)
                        .eq(MenuNutrition::getNutritionName, m.getNutritionName()).select(MenuNutrition::getNutritionId));
                if (CollUtil.isNotEmpty(menuNutritionList)) {
                    materialAdd.setNutritionId(((MenuNutrition)menuNutritionList.get(0)).getNutritionId());
                }

                ((MenuMaterialMapper)this.baseMapper).insert(materialAdd);
            });
        } catch (Exception var7) {
            log.error("导入原料错误", var7);
        } finally {
            this.stringRedisTemplate.delete(dishesLockRedisKey);
        }

    }

    @Override
    public MaterialImportCheckResult importDishesCheck(MultipartFile excel) {
        MaterialImportCheckResult result = new MaterialImportCheckResult();
        List<MaterialImportDTO> successList = new ArrayList();
        List<MaterialImportDTO> errorList = new ArrayList();

        List<MaterialImportDTO> materialImportDTOS;
        try {
            materialImportDTOS = EasyExcelUtil.readSingleExcel(excel, new MaterialImportDTO(), 1);
        } catch (Exception var21) {
            log.info("导入原料错误", var21);
            throw new ServiceException("导入原料错误");
        }

        if (CollUtil.isEmpty(materialImportDTOS)) {
            throw new ServiceException("导入原料为空");
        } else {
            long count = materialImportDTOS.stream().map(MaterialImportDTO::getMaterialName).distinct().count();
            if (count < (long)materialImportDTOS.size()) {
                throw new ServiceException("存在相同名称的原料");
            } else {
                long checkBarCode = materialImportDTOS.stream().map(MaterialImportDTO::getBarCode).distinct().count();
                if (checkBarCode < (long)materialImportDTOS.size()) {
                    throw new ServiceException("存在相同的条码");
                } else {
                    Map<String, List<MenuNutrition>> allNutrition = this.menuNutritionMapper.selectList(Wrappers.lambdaQuery(MenuNutrition.class).eq(MenuNutrition::getDelFlag, LeConstants.COMMON_NO)).stream().collect(Collectors.groupingBy(MenuNutrition::getNutritionName));
                    Map<String, List<MenuMaterial>> allMenuMaterials = this.baseMapper.selectList(Wrappers.lambdaQuery(MenuMaterial.class).eq(MenuMaterial::getDelFlag, LeConstants.COMMON_NO)).stream().collect(Collectors.groupingBy(MenuMaterial::getMaterialName));
                    Map<String, List<MenuMaterialCategory>> allCategory =
                            this.menuMaterialCategoryMapper.selectList(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                                    .eq(MenuMaterialCategory::getCategoryType, 1).eq(MenuMaterialCategory::getDelFlag, LeConstants.COMMON_NO)).stream().collect(Collectors.groupingBy(MenuMaterialCategory::getCategoryName));
                    Iterator var13 = materialImportDTOS.iterator();

                    while(true) {
                        while(var13.hasNext()) {
                            MaterialImportDTO materialImportDTO = (MaterialImportDTO)var13.next();
                            String materialName = materialImportDTO.getMaterialName();
                            String categoryName = materialImportDTO.getCategoryName();
                            String nutritionName = materialImportDTO.getNutritionName();
                            if (ObjectUtil.isEmpty(materialName)) {
                                materialImportDTO.setFailReason("原料名称不能为空");
                                errorList.add(materialImportDTO);
                            } else {
                                List<MenuMaterial> menuMaterials = (List)allMenuMaterials.get(materialName);
                                if (ObjectUtil.isNotEmpty(menuMaterials)) {
                                    materialImportDTO.setFailReason("原料名称重复");
                                    errorList.add(materialImportDTO);
                                } else if (ObjectUtil.isEmpty(categoryName)) {
                                    materialImportDTO.setFailReason("原料类别不能为空");
                                    errorList.add(materialImportDTO);
                                } else {
                                    List<MenuMaterialCategory> menuMaterialCategories = (List)allCategory.get(categoryName);
                                    if (ObjectUtil.isEmpty(menuMaterialCategories)) {
                                        materialImportDTO.setFailReason("原料类别不存在");
                                        errorList.add(materialImportDTO);
                                    } else {
                                        if (ObjectUtil.isNotEmpty(nutritionName)) {
                                            List<MenuNutrition> menuNutritions = (List)allNutrition.get(nutritionName);
                                            if (ObjectUtil.isEmpty(menuNutritions)) {
                                                materialImportDTO.setFailReason("营养信息不存在");
                                                errorList.add(materialImportDTO);
                                                continue;
                                            }
                                        }

                                        successList.add(materialImportDTO);
                                    }
                                }
                            }
                        }

                        result.setSuccessList(successList);
                        result.setErrorList(errorList);
                        return result;
                    }
                }
            }
        }
    }

    @Override
    public Boolean importMaterials(List<MaterialImportDTO> materialImportDTOS) {
        String dishesLockRedisKey = "yst:merchant-id:material:lock".replace("merchant-id", TenantContextHolder.getTenantId().toString());
        String asyncState = (String)this.stringRedisTemplate.opsForValue().get(dishesLockRedisKey);
        if (StringUtils.isNotBlank(asyncState)) {
            throw new ServiceException("导入原料进行中,不要重复操作哦 ^_^");
        } else {
            try {
                String username = SecurityUtils.getUsername();
                this.asyncTaskExecutor.execute(() -> {
                    this.importMaterialsDtos(materialImportDTOS, username);
                });
            } catch (Exception var6) {
                log.info("[批量导入原料]系统错误：{}", var6.getMessage(), var6);
                throw new ServiceException("批量导入原料发生错误");
            }

            return true;
        }
    }

    private void importMaterialsDtos(List<MaterialImportDTO> materialImportDTOS, String username) {
        String dishesLockRedisKey = "yst:merchant-id:material:lock".replace("merchant-id", TenantContextHolder.getTenantId().toString());
        MaterialImportCheckResult result = new MaterialImportCheckResult();
        List<MaterialImportDTO> successList = new ArrayList();
        ArrayList errorList = new ArrayList();
        boolean var18 = false;

        String resultRedisKey;
        label91: {
            try {
                var18 = true;
                this.stringRedisTemplate.opsForValue().set(dishesLockRedisKey, "1", 20L, TimeUnit.MINUTES);
                Map<String, List<MenuNutrition>> allNutrition =
                        this.menuNutritionMapper.selectList(Wrappers.lambdaQuery(MenuNutrition.class).eq(MenuNutrition::getDelFlag, LeConstants.COMMON_NO)).stream().collect(Collectors.groupingBy(MenuNutrition::getNutritionName));
                Map<String, List<MenuMaterialCategory>> allCategory =this.menuMaterialCategoryMapper.selectList(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                        .eq(MenuMaterialCategory::getCategoryType, 1)
                        .eq(MenuMaterialCategory::getDelFlag, LeConstants.COMMON_NO))
                        .stream().collect(Collectors.groupingBy(MenuMaterialCategory::getCategoryName));
                Iterator var9 = materialImportDTOS.iterator();

                while(var9.hasNext()) {
                    MaterialImportDTO materialImportDTO = (MaterialImportDTO)var9.next();

                    try {
                        MenuMaterial material = new MenuMaterial();
                        material.setMaterialName(materialImportDTO.getMaterialName());
                        material.setMaterialId(Id.next());
                        material.setMaterialCode(this.generateMaterialCode());
                        material.setMaterialType(1);
                        material.setCrby(username);
                        material.setCategoryId(((MenuMaterialCategory)((List)allCategory.get(materialImportDTO.getCategoryName())).get(0)).getCategoryId());
                        if (ObjectUtil.isNotEmpty(materialImportDTO.getNutritionName())) {
                            MenuNutrition menuNutrition = (MenuNutrition)((List)allNutrition.get(materialImportDTO.getNutritionName())).get(0);
                            material.setNutritionId(menuNutrition.getNutritionId());
                        }

                        material.setPinyinInitials(PinyinUtil.getFirstLetterFromChinese(material.getMaterialName()));
                        material.setPinyinFull(PinyinUtil.convertChineseToPinyin(material.getMaterialName()));
                        this.save(material);
                        successList.add(materialImportDTO);
                    } catch (Exception var19) {
                        errorList.add(materialImportDTO);
                        materialImportDTO.setFailReason("未知异常");
                        log.error("导入原料异常:{}", var19);
                    }
                }

                result.setErrorList(errorList);
                result.setSuccessList(successList);
                var18 = false;
                break label91;
            } catch (Exception var20) {
                log.error("导入原料异常:{}", var20.getLocalizedMessage());
                var18 = false;
            } finally {
                if (var18) {
                    String var14 = "yst:merchant-id:material:upgrade:result".replace("merchant-id", TenantContextHolder.getTenantId().toString());
                    RedisUtil.setString(var14, JSONUtil.toJsonStr(result), 60L);
                    this.stringRedisTemplate.delete(dishesLockRedisKey);
                }
            }

            resultRedisKey = "yst:merchant-id:material:upgrade:result".replace("merchant-id", TenantContextHolder.getTenantId().toString());
            RedisUtil.setString(resultRedisKey, JSONUtil.toJsonStr(result), 60L);
            this.stringRedisTemplate.delete(dishesLockRedisKey);
            return;
        }

        resultRedisKey = "yst:merchant-id:material:upgrade:result".replace("merchant-id", TenantContextHolder.getTenantId().toString());
        RedisUtil.setString(resultRedisKey, JSONUtil.toJsonStr(result), 60L);
        this.stringRedisTemplate.delete(dishesLockRedisKey);
    }

    @Override
    public void batchImportMaterialProduct(MultipartFile excel) {
        String materialLockRedisKey = "yst:merchant-id:material-product:lock".replace("merchant-id", TenantContextHolder.getTenantId().toString());
        String asyncState = (String)this.stringRedisTemplate.opsForValue().get(materialLockRedisKey);
        if (StringUtils.isNotBlank(asyncState)) {
            throw new ServiceException("menu_product_import_not_commit_repeat");
        } else {
            this.asyncImportMaterialProduct(excel, MaterialTypeEnum.GOODS.key());
        }
    }
    private void asyncImportMaterialProduct(MultipartFile excel, Integer materialType) {
        ExcelReaderSheetBuilder excelReaderSheetBuilder = null;

        try {
            excelReaderSheetBuilder =  EasyExcel.read(excel.getInputStream()).registerReadListener(new MenuMaterialProductImportListener(this, this.menuDishesService, materialType, (MenuMaterialMapper)this.baseMapper, this.menuMaterialCategoryMapper, this.allocCanteenApi))
                    .head(MenuMaterialProductImportDTO.class).sheet().headRowNumber(1);
            MqUtil.pushToTenantAllDevice((Object)null, LeMqConstant.Topic.DRP_SYNC_MATERIAL);
        } catch (Exception var5) {
            this.dishesImportFailInsert(var5);
        }

        ExcelReaderSheetBuilder finalExcelReaderSheetBuilder = excelReaderSheetBuilder;
        this.asyncTaskExecutor.execute(() -> {
            try {
                if (finalExcelReaderSheetBuilder != null) {
                    finalExcelReaderSheetBuilder.doReadSync();
                }
            } catch (Exception var3) {
                this.dishesImportFailInsert(var3);
            }

        });
    }
    private void dishesImportFailInsert(Exception e) {
        log.info("导入商品错误信息", e);
        MenuDishesImportFail dishesImportFail = new MenuDishesImportFail();
        dishesImportFail.setFailRow(1);
        dishesImportFail.setImportTime(LocalDateTime.now());
        dishesImportFail.setFailType(MenuFailTypeEnum.PRODUCT.key());
        dishesImportFail.setFailReason(e.getMessage());
        dishesImportFail.insert();
    }
    @Override
    public void batchUpdateMaterialCategory(MaterialCategoryBatchUpdateDTO content) {
        this.menuMaterialCategoryService.syncAllCategoryBigCategoryAndLevel();
        Long bigCategoryId = this.menuMaterialCategoryService.getBigCategoryIdById(content.getCategroyId());
        this.update(null, Wrappers.lambdaUpdate(MenuMaterial.class)
                .in(MenuMaterial::getMaterialId, content.getMaterialIdList())
                .set(MenuMaterial::getCategoryId, content.getCategroyId())
                .set(MenuMaterial::getBigCategoryId, bigCategoryId));
        MqUtil.pushToTenantAllDevice((Object)null, LeMqConstant.Topic.DRP_SYNC_MATERIAL);
    }

    @Override
    public List<MaterialFunctionListVO> listMaterialFunction(MaterialFunctionListDTO content) {
        return this.menuMaterialFunctionMapper.listMaterialFunction(content);
    }

    @Override
    public void materialDisable(MenuMaterialDisableDTO content) {
        if (CollUtil.isEmpty(content.getMaterialIdList())) {
            throw new ServiceException("原料id不能为空");
        } else if (content.getDisableStatus() == null) {
            throw new ServiceException("禁用状态不能为空");
        } else {
            this.menuMaterialMapper.update(null, Wrappers.lambdaUpdate(MenuMaterial.class)
                    .set(content.getDisableStatus() == 2, MenuMaterial::getDisableStatus, content.getDisableStatus())
                    .set(content.getDisableStatus() == 1, MenuMaterial::getDisableStatus, (Object)null)
                    .in(MenuMaterial::getMaterialId, content.getMaterialIdList()));
        }
    }

    @Override
    public List<DrpImportMaterialVO> importMaterialExcel(MultipartFile excel) {
        List<DrpImportMaterialDTO> drpImportMaterialDTOList;
        try {
            drpImportMaterialDTOList = EasyExcelUtil.readSingleExcel(excel, new DrpImportMaterialDTO(), 1);
        } catch (Exception var9) {
            log.error("解析数据错误", var9);
            throw new ServiceException("acc_batch_import_data_exception");
        }

        drpImportMaterialDTOList.forEach((m) -> {
            if (ObjectUtil.isEmpty(m.getMaterialName()) || ObjectUtil.isEmpty(m.getMaterialCode()) || ObjectUtil.isEmpty(m.getUnitName())) {
                throw new ServiceException("货品名称、单位、原料编码不能为空");
            }
        });
        if (CollUtil.isEmpty(drpImportMaterialDTOList)) {
            throw new ServiceException("导入数据为空");
        } else {
            List<String> materialCodeList = drpImportMaterialDTOList.stream()
                    .map(DrpImportMaterialDTO::getMaterialCode).collect(Collectors.toList());
            List<DrpImportMaterialVO> list = this.menuMaterialMapper.getMaterialByExcel(materialCodeList);
            if (CollUtil.isEmpty(list)) {
                throw new ServiceException("导入的货品编码不存在或已禁用");
            } else {
                Map<String, DrpImportMaterialDTO> dzMap = drpImportMaterialDTOList.stream()
                        .collect(Collectors.toMap(DrpImportMaterialDTO::getMaterialCode, Function.identity(), (k1, k2) -> {
                    return k1;
                }));
                Iterator var6 = list.iterator();

                while(var6.hasNext()) {
                    DrpImportMaterialVO drpImportMaterialVO = (DrpImportMaterialVO)var6.next();
                    DrpImportMaterialDTO materialDTO = (DrpImportMaterialDTO)dzMap.get(drpImportMaterialVO.getMaterialCode());
                    if (materialDTO != null) {
                        if (ObjectUtil.notEqual(materialDTO.getMaterialName(), drpImportMaterialVO.getMaterialName())) {
                            throw new ServiceException(materialDTO.getMaterialName() + " 货品编码与名称不匹配");
                        }

                        if (ObjectUtil.notEqual(materialDTO.getUnitName(), drpImportMaterialVO.getUnitName())) {
                            throw new ServiceException(materialDTO.getMaterialName() + " 货品编码与单位不匹配");
                        }

                        drpImportMaterialVO.setPurNum(materialDTO.getPurNum());
                        drpImportMaterialVO.setRemark(materialDTO.getRemark());
                        drpImportMaterialVO.setUnitPrice(materialDTO.getUnitPrice());
                    }
                }

                return list;
            }
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public String generateMaterialCode() {
        String maxMaterialNumStr = this.baseMapper.selectMaxMaterialCodeByCategoryNum(MenuConstant.MATERIAL_CODE_LENGTH, DelFlagEnum.DEL_FALSE.key());
        String materialCode;
        if (CharSequenceUtil.isEmpty(maxMaterialNumStr)) {
            materialCode = "00001";
        } else {
            Integer maxMaterialNum = Integer.valueOf(maxMaterialNumStr);
            materialCode = String.format("%05d", maxMaterialNum + 1);
        }
        return materialCode;
    }

    @Override
    public void importMaterialProduct(List<MenuMaterialProductImportDTO> materialImportProductDTOList) {
        String dishesLockRedisKey = "yst:merchant-id:material-product:lock".replace("merchant-id", TenantContextHolder.getTenantId().toString());
        this.stringRedisTemplate.opsForValue().set(dishesLockRedisKey, "1", 20L, TimeUnit.MINUTES);

        try {
            materialImportProductDTOList.forEach((m) -> {
                MenuMaterial materialAdd = new MenuMaterial();
                BeanUtil.copyProperties(m, materialAdd, new String[0]);
                materialAdd.setMaterialId(Id.next());
                materialAdd.setPinyinInitials(PinyinUtil.getFirstLetterFromChinese(m.getMaterialName()));
                materialAdd.setPinyinFull(PinyinUtil.convertChineseToPinyin(m.getMaterialName()));
                MenuMaterialCategory menuMaterialCategory = this.menuMaterialCategoryMapper
                        .selectOne(Wrappers.lambdaQuery(MenuMaterialCategory.class)
                                .eq(MenuMaterialCategory::getCategoryName, m.getCategoryName())
                                .eq(MenuMaterialCategory::getDelFlag, DelFlagEnum.DEL_FALSE.key())
                                .eq(m.getAreaId() != null, MenuMaterialCategory::getAreaId, m.getAreaId())
                                .isNull(m.getAreaId() == null, MenuMaterialCategory::getAreaId)
                                .select(MenuMaterialCategory::getCategoryId, MenuMaterialCategory::getParentId,
                                        MenuMaterialCategory::getCategoryType, MenuMaterialCategory::getBigCategoryId));
                Long unitId;
                Long bigCategoryId;
                if (ObjectUtil.isEmpty(menuMaterialCategory)) {
                    unitId = this.menuMaterialCategoryMapper.selectIdByType(m.getMaterialType());
                    bigCategoryId = Id.next();
                    menuMaterialCategory = new MenuMaterialCategory();
                    menuMaterialCategory.setCategoryId(bigCategoryId);
                    menuMaterialCategory.setCategoryName(m.getCategoryName());
                    menuMaterialCategory.setCategoryType(m.getMaterialType());
                    menuMaterialCategory.setParentId(unitId);
                    menuMaterialCategory.setAreaId(m.getAreaId());
                    menuMaterialCategory.setLevel(LeLevelEnum.FIRST.getKey());
                    menuMaterialCategory.setBigCategoryId(bigCategoryId);
                    this.menuMaterialCategoryMapper.insert(menuMaterialCategory);
                    this.menuMaterialCategoryService.generateCategoryNum(menuMaterialCategory.getCategoryId(), menuMaterialCategory.getParentId(), menuMaterialCategory.getCategoryType());
                    materialAdd.setCategoryId(bigCategoryId);
                    materialAdd.setBigCategoryId(bigCategoryId);
                } else {
                    unitId = menuMaterialCategory.getCategoryId();
                    if (ObjectUtil.isEmpty(menuMaterialCategory.getBigCategoryId())) {
                        this.menuMaterialCategoryService.syncAllCategoryBigCategoryAndLevel();
                        bigCategoryId = this.menuMaterialCategoryService.getBigCategoryIdById(unitId);
                        materialAdd.setBigCategoryId(bigCategoryId);
                    } else {
                        materialAdd.setBigCategoryId(menuMaterialCategory.getBigCategoryId());
                    }
                }

                unitId = this.drpUnitServiceApi.getUnitIdByNameAndArea(m.getUnitName(), m.getAreaId());
                if (ObjectUtil.isEmpty(unitId)) {
                    DrpUnit drpUnit = new DrpUnit();
                    unitId = Id.next();
                    drpUnit.setUnitId(unitId);
                    drpUnit.setUnitName(m.getUnitName());
                    drpUnit.setAreaId(m.getAreaId());
                    this.drpUnitServiceApi.insertUnit(drpUnit);
                }

                materialAdd.setUnitId(unitId);
                if (ObjectUtil.equal(m.getMaterialType(), MaterialTypeEnum.MATERIAL.key())) {
                    materialAdd.setSalesMode(MenuSalesTypeEnum.WEIGHT_ON.key());
                }

                Integer unitPrice;
                if (null != m.getSalePrice()) {
                    unitPrice = m.getSalePrice().multiply(new BigDecimal(100)).intValue();
                    materialAdd.setSalePrice(unitPrice);
                }

                if (null != m.getUnitPrice()) {
                    unitPrice = m.getUnitPrice().multiply(new BigDecimal(100)).intValue();
                    materialAdd.setUnitPrice(unitPrice);
                }

                String materialCode = this.menuMaterialService.generateMaterialCode();
                materialAdd.setMaterialCode(materialCode);
                ((MenuMaterialMapper)this.baseMapper).insert(materialAdd);
            });
        } catch (Exception var7) {
            log.error("导入商品错误", var7);
        } finally {
            this.stringRedisTemplate.delete(dishesLockRedisKey);
        }

    }

}