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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.canteen.core.allocation.api.AllocCanteenApi;
import com.bonus.canteen.core.allocation.api.AllocMetadataApi;
import com.bonus.canteen.core.allocation.canteen.model.AllocArea;
import com.bonus.canteen.core.allocation.canteen.model.AllocCanteen;
import com.bonus.canteen.core.allocation.canteen.model.AllocStall;
import com.bonus.canteen.core.allocation.canteen.service.AllocAreaService;
import com.bonus.canteen.core.allocation.canteen.service.AllocStallService;
import com.bonus.canteen.core.auth.api.MgrAuthApi;
import com.bonus.canteen.core.auth.po.MgrUserAuthPO;
import com.bonus.canteen.core.common.config.excel.EasyExcelUtil;
import com.bonus.canteen.core.common.constant.LeMqConstant;
import com.bonus.canteen.core.common.enums.FileUploadSourceEnum;
import com.bonus.canteen.core.common.enums.MetadataModelTypeEnum;
import com.bonus.canteen.core.common.page.PageVO;
import com.bonus.canteen.core.common.redis.RedisUtil;
import com.bonus.canteen.core.common.utils.LogUtil;
import com.bonus.canteen.core.common.utils.TenantContextHolder;
import com.bonus.canteen.core.drp.api.DrpServiceApi;
import com.bonus.canteen.core.drp.po.DishesMaterialCostModel;
import com.bonus.canteen.core.menu.constant.*;
import com.bonus.canteen.core.menu.dto.*;
import com.bonus.canteen.core.menu.entity.*;
import com.bonus.canteen.core.menu.mapper.*;
import com.bonus.canteen.core.menu.model.MenuBaseAndDishesModel;
import com.bonus.canteen.core.menu.model.MenuBaseDishesModel;
import com.bonus.canteen.core.menu.model.MenuDishesCostModel;
import com.bonus.canteen.core.menu.model.MenuMetadataModel;
import com.bonus.canteen.core.menu.service.*;
import com.bonus.canteen.core.menu.utils.NutritionEntity;
import com.bonus.canteen.core.menu.utils.NutritionEntityUtil;
import com.bonus.canteen.core.menu.utils.PinyinUtil;
import com.bonus.canteen.core.menu.vo.*;
import com.bonus.canteen.core.menuai.api.MenuaiServiceApi;
import com.bonus.canteen.core.menuai.dto.MenuaiDishesNameEditDTO;
import com.bonus.canteen.core.menuai.entity.MenuaiPicture;
import com.bonus.canteen.core.menuai.mapper.MenuaiPictureMapper;
import com.bonus.canteen.core.menuai.service.MenuaiV4Service;
import com.bonus.canteen.core.merchant.dto.MenuaiPictureRemoveDTO;
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.constant.LeConstants;
import com.bonus.common.houqin.i18n.I18n;
import com.bonus.common.houqin.oss.OssProperties;
import com.bonus.common.houqin.oss.service.OssTemplate;
import com.bonus.common.houqin.utils.CopyListUtil;
import com.bonus.common.houqin.utils.id.Id;
import com.bonus.common.security.utils.SecurityUtils;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
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.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

@Service
public class MenuDishesServiceImpl extends ServiceImpl<MenuDishesMapper, MenuDishes> implements MenuDishesService {
    private static final Logger log = LoggerFactory.getLogger(MenuDishesServiceImpl.class);
    @Lazy
    @Resource(
            name = "yunshitangTaskExecutor"
    )
    private AsyncTaskExecutor asyncTaskExecutor;
    @Resource
    @Lazy
    private MenuDishesService menuDishesService;

    @Resource
    @Lazy
    private MenuCollectionDishesMapper menuCollectionDishesMapper;
    @Resource
    @Lazy
    private MenuMaterialDishesMapper menuMaterialDishesMapper;
    @Resource
    @Lazy
    private MenuPackageDishesMapper menuPackageDishesMapper;
    @Resource
    @Lazy
    private MenuMaterialService menuMaterialService;
    @Resource
    private MenuMaterialNutritionMapper menuMaterialNutritionMapper;
    @Resource
    @Lazy
    private MenuMaterialDishesService menuMaterialDishesService;
    @Resource
    private MenuNutritionService menuNutritionService;
    @Resource
    @Lazy
    private MenuDishesImportFailService menuDishesImportFailService;
    @Lazy
    @Resource
    private AllocMetadataApi allocMetadataApi;
    @Resource
    private MenuDishesBaseMapper menuDishesBaseMapper;
    @Resource
    private MenuDishesBaseService menuDishesBaseService;
    @Resource
    private MenuDishesSizeService menuDishesSizeService;
    @Resource
    @Lazy
    private MenuDishesTypeMapper menuDishesTypeMapper;
    @Resource
    @Lazy
    private MenuDishesTypeService menuDishesTypeService;
    @Resource
    @Lazy
    private MenuDishesCookMapper menuDishesCookMapper;
    @Resource
    @Lazy
    private MenuSequenceService menuSequenceService;
    @Resource
    @Lazy
    private MenuLabelDishesMapper menuLabelDishesMapper;
    @Resource
    @Lazy
    private MenuSuitDishesMapper menuSuitDishesMapper;
    @Resource
    private MenuSeasonDishesService menuSeasonDishesService;
    @Resource
    private MenuMealtimeTypeDishesService menuMealtimeTypeDishesService;
    @Resource
    @Lazy
    private MenuCustomDictService menuCustomDictService;
    @Resource
    private MgrAuthApi mgrAuthApi;
    @Resource
    @Lazy
    private MenuMaterialMapper menuMaterialMapper;
    @Resource
    @Lazy
    private MenuDishesLabelMapper menuDishesLabelMapper;
    @Resource
    @Lazy
    private MenuDishesSuitMapper menuDishesSuitMapper;
    @Resource
    @Lazy
    private MenuTasteDishesMapper menuTasteDishesMapper;
    @Resource
    @Lazy
    private MenuDishesTasteMapper menuDishesTasteMapper;
    @Resource
    @Lazy
    private MenuDishesMapper menuDishesMapper;
    @Resource
    @Lazy
    private MenuaiServiceApi menuaiServiceApi;
    @Resource
    private MenuRecipeDishesService menuRecipeDishesService;
    @Resource
    @Lazy
    private MenuRecipeDishesMapper menuRecipeDishesMapper;
    @Resource
    @Lazy
    private MenuCustomDictMapper menuCustomDictMapper;
    @Resource
    private MenuaiPictureMapper menuaiPictureMapper;
    @Resource
    @Lazy
    private MenuaiV4Service menuaiV4Service;
    @Resource
    @Lazy
    private AllocCanteenApi allocCanteenApi;

    @Resource
    @Lazy
    private MenuLabelDishesService menuLabelDishesService;
    @Resource
    @Lazy
    private MenuSuitDishesService menuSuitDishesService;
    @Resource
    @Lazy
    private MenuTasteDishesService menuTasteDishesService;
    @Resource
    @Lazy
    private MenuPackageDishesService menuPackageDishesService;

    @Resource
    @Lazy
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private AllocAreaService allocAreaService;
    @Resource
    private AllocStallService allocStallService;
    @Resource
    private MenuDishesCookService menuDishesCookService;
    @Resource
    private DrpServiceApi drpServiceApi;
    @Resource
    @Lazy
    private OssProperties ossProperties;
    @Resource
    @Lazy
    private OssTemplate ossTemplate;


    @Override
    public AppletDishesDetailVO getDishesDetailByDishesId(AppletDishesDetailDTO dishesDetailDTO) {
        //AppletDishesDetailDTO dishesDetailDTO = (AppletDishesDetailDTO)JSON.parseObject(content, AppletDishesDetailDTO.class);
        dishesDetailDTO.setDelFlag(DelFlagEnum.DEL_FALSE.key());
        Long baseDishesId = dishesDetailDTO.getBaseDishesId();
        Long custId = dishesDetailDTO.getCustId();
        if (!ObjectUtil.isNull(custId) && custId != -1L) {
            AppletDishesDetailVO appletDishesDetailVO = ((MenuDishesMapper) this.baseMapper).selectDishesDetailByDishesId(dishesDetailDTO);
            Long countDishes = this.menuCollectionDishesMapper.selectCount(Wrappers.lambdaQuery(MenuCollectionDishes.class)
                    .eq(MenuCollectionDishes::getCustId, custId).eq(MenuCollectionDishes::getDishesId, baseDishesId));
            if (ObjectUtil.isNotNull(countDishes) && countDishes > 0L) {
                appletDishesDetailVO.setIsFavorites(1);
            } else {
                appletDishesDetailVO.setIsFavorites(2);
            }

            Long dishesId = ((AppletDishesSizeV2VO) appletDishesDetailVO.getDishesDetailList().get(0)).getDishesId();
            List materialList;
            if (appletDishesDetailVO.getMealType() == 1) {
                materialList = this.menuMaterialDishesMapper.getMenuMaterialById(dishesId);
                appletDishesDetailVO.setMaterialList(materialList);
            } else {
                materialList = this.menuPackageDishesMapper.selectDishesName(dishesId);
                appletDishesDetailVO.setPackageDishesList(materialList);
            }

            return appletDishesDetailVO;
        } else {
            throw new ServiceException(I18n.getMessage("menu_no_cust_info", new Object[0]));
        }
    }

    @Override
    public NutritionEntity getNutrientInfo(Map<Long, Double> dishesQuantityMap) {
        return this.menuDishesService.getNutrientInfo(dishesQuantityMap);
    }

    @Override
    public List<MenuDishes> getMenuDishesList(List<Long> dishesIdList) {
        return this.list(Wrappers.lambdaQuery(MenuDishes.class)
                .in(MenuDishes::getDishesId, dishesIdList).eq(MenuDishes::getDelFlag, LeConstants.COMMON_NO));
    }

    @Override
    public void updateDishesNutritionByNutritionId(Long nutritionId) {
        List<Long> materialIdList = this.menuMaterialService.listObjs(Wrappers.lambdaQuery(MenuMaterial.class)
                .select(MenuMaterial::getMaterialId)
                .eq(MenuMaterial::getNutritionId, nutritionId)
                .eq(MenuMaterial::getDelFlag, DelFlagEnum.DEL_FALSE.key()), (x) -> {
            return Long.valueOf(x.toString());
        });
        if (!ObjectUtil.isEmpty(materialIdList)) {
            this.menuMaterialNutritionMapper.delete((Wrapper) Wrappers.lambdaQuery(MenuMaterialNutrition.class).in(MenuMaterialNutrition::getMaterialId, materialIdList));
            this.updateDishesNutrition(materialIdList);
        }
    }

    @Override
    public void updateDishesNutrition(List<Long> materialIds) {
        List<MenuUpdateDishesModel> menuUpdateDishesModels = this.menuMaterialDishesService.selectDishesList(materialIds);
        this.updateNutrition(menuUpdateDishesModels);
    }

    public void updateNutrition(List<MenuUpdateDishesModel> menuUpdateDishesModels) {
        this.asyncTaskExecutor.execute(() -> {
            if (!CollUtil.isEmpty(menuUpdateDishesModels)) {
                Map<Long, Long> dishesMap = (Map) menuUpdateDishesModels.stream().collect(Collectors.toMap(MenuUpdateDishesModel::getId, MenuUpdateDishesModel::getDishesId));
                List<MenuDishes> updateDishesList = new ArrayList();
                dishesMap.forEach((id, dishesId) -> {
                    List<NutritionEntity> nutritionEntityList = this.menuNutritionService.selectNutritionWeightList(dishesId);
                    NutritionEntity nutritionEntity = NutritionEntityUtil.countNutrition(nutritionEntityList);
                    log.info("计算完毕营养信息整合结果nutritionEntity : {}", nutritionEntity);
                    MenuDishes dishes = new MenuDishes();
                    BeanUtils.copyProperties(nutritionEntity, dishes);
                    dishes.setId(id);
                    dishes.setWeight((Double) null);
                    updateDishesList.add(dishes);
                });
                super.updateBatchById(updateDishesList);
            }
        });
    }

    @Override
    public void importDishesFailSave(List<MenuDishesImportFail> dishesImportFailList) {
        this.menuDishesImportFailService.saveBatch(dishesImportFailList);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRES_NEW)
    public AddDishesVo addMenuDishesV2(MenuDishesV2AddDTO content) {
        this.checkParam(content);
        AddDishesVo addDishesVo = new AddDishesVo();
        List<Long> dishesIds = new ArrayList<>();
        List<MenuBaseDishesModel> menuBaseDishesModels = new ArrayList<>();
        addDishesVo.setDishesIds(dishesIds);
        addDishesVo.setMenuBaseDishes(menuBaseDishesModels);
        if (MenuSalesTypeEnum.PORTION_ON.key().equals(content.getSalesMode()) && content.getSizeType() == 2L) {
            Long baseDishesId = this.insertBaseAndSize(content.getDishesName(), "大份", "小份");
            addDishesVo.setBaseDishesId(baseDishesId);
            JSONObject sizeTypeJsonLa = new JSONObject();
            sizeTypeJsonLa.put("sizeType", "大份");
            String dishesName = content.getDishesName();
            content.setDishesName(dishesName + "-大份");
            Long largeDishesId = this.insertMenuDishes(content, baseDishesId, content.getLargePrice(), content.getLargeWeight(), sizeTypeJsonLa.toJSONString(), content.getConvertFlag());
            dishesIds.add(largeDishesId);
            MenuBaseDishesModel menuBaseDishesModel = new MenuBaseDishesModel();
            menuBaseDishesModel.setDishesId(largeDishesId);
            menuBaseDishesModel.setSizeJson(sizeTypeJsonLa.toJSONString());
            menuBaseDishesModels.add(menuBaseDishesModel);
            JSONObject sizeTypeJsonLi = new JSONObject();
            sizeTypeJsonLi.put("sizeType", "小份");
            content.setDishesName(dishesName + "-小份");
            Long littleDishesId = this.insertMenuDishes(content, baseDishesId, content.getLittlePrice(), content.getLittleWeight(), sizeTypeJsonLi.toJSONString(), content.getLittleConvertFlag());
            dishesIds.add(littleDishesId);
            MenuBaseDishesModel littleMenuBaseDishesModel = new MenuBaseDishesModel();
            littleMenuBaseDishesModel.setDishesId(littleDishesId);
            littleMenuBaseDishesModel.setSizeJson(sizeTypeJsonLi.toJSONString());
            menuBaseDishesModels.add(littleMenuBaseDishesModel);
        } else {
            String sizeTypeStr = "";
            Double weight = content.getWeight();
            if (MenuSalesTypeEnum.PORTION_ON.key().equals(content.getSalesMode())) {
                sizeTypeStr = "标准";
            } else if (content.getUnitPrice() == 50) {
                sizeTypeStr = "50g";
                weight = 50.0;
            } else if (content.getUnitPrice() == 100) {
                sizeTypeStr = "100g";
                weight = 100.0;
            }

            Long baseDishesId = this.insertBaseAndSize(content.getDishesName(), sizeTypeStr);
            addDishesVo.setBaseDishesId(baseDishesId);
            JSONObject sizeTypeJson = new JSONObject();
            sizeTypeJson.put("sizeType", sizeTypeStr);
            Long dishesId = this.insertMenuDishes(content, baseDishesId, content.getPrice(), weight, sizeTypeJson.toJSONString());
            dishesIds.add(dishesId);
            MenuBaseDishesModel menuBaseDishesModel = new MenuBaseDishesModel();
            menuBaseDishesModel.setDishesId(dishesId);
            menuBaseDishesModel.setSizeJson(sizeTypeJson.toJSONString());
            menuBaseDishesModels.add(menuBaseDishesModel);
        }

        return addDishesVo;
    }

    @Override
    public Page<MenuDishesV2PageVO> getMenuDishesV2Page(MenuDishesV2PageDTO content) {
        Page<MenuDishesV2PageVO> resultPage = new Page(content.getCurrent(), content.getSize());
        MenuMetadataModel menuMetadataModel = this.allocMetadataApi.queryMetadataModel(MetadataModelTypeEnum.MENU, new MenuMetadataModel());
        String ifDifCanteenManage = menuMetadataModel.getIfDifCanteenManage();
        MgrUserAuthPO authPo = this.mgrAuthApi.getUserAuthPO();
        log.info("获取登录用户权限authPO: {}", authPo);
        resultPage = this.baseMapper.selectAllV2List(resultPage, content, "1".equals(ifDifCanteenManage), authPo);
        List<MenuDishesV2PageVO> records = resultPage.getRecords();
        if (ObjectUtil.isNotEmpty(records)) {
            List<Long> baseDishesId = records.stream().map(MenuDishesV2PageVO::getDishesId).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(baseDishesId)) {
                Map<Long, Integer> littlePriceMap =
                        this.list(Wrappers.lambdaQuery(MenuDishes.class).select(MenuDishes::getBaseDishesId, MenuDishes::getPrice)
                                        .in(MenuDishes::getBaseDishesId, baseDishesId)
                                        .eq(MenuDishes::getSizeJson, "{\"sizeType\":\"小份\"}"))
                                .stream().collect(Collectors.toMap(MenuDishes::getBaseDishesId, MenuDishes::getPrice));
                Iterator var9 = records.iterator();
                while (var9.hasNext()) {
                    MenuDishesV2PageVO item = (MenuDishesV2PageVO) var9.next();
                    item.setLittlePrice(littlePriceMap.get(item.getDishesId()));
                }
            }
        }
        return resultPage;
    }

    @Override
    public MenuDishesDetailVO getMenuDishesDetail(Long dishesId) {
        MenuDishesDetailVO result = this.baseMapper.selectDishesDetailById(dishesId);
        if (ObjectUtil.isNull(result)) {
            return result;
        } else {
            List<MenuBaseDishesModel> dishesDetailList = this.baseMapper.selectBaseDishesIdSize(dishesId);
            result.setBaseDishesList(dishesDetailList);
            if (dishesDetailList.size() > 1) {
                Iterator var4 = dishesDetailList.iterator();

                while (var4.hasNext()) {
                    MenuBaseDishesModel dishes = (MenuBaseDishesModel) var4.next();
                    if (CharSequenceUtil.contains(dishes.getSizeJson(), "小份")) {
                        result.setLittleMaterialList(this.menuMaterialMapper.selectMaterialByDishesId(dishes.getDishesId()));
                        result.setLittleDishesNutrition(this.baseMapper.selectDishesNutrition(dishes.getDishesId()));
                        result.setLittleMaterialCost(this.baseMapper.selectMaterialCost(Wrappers.lambdaQuery(MenuDishes.class)
                                .eq(MenuDishes::getDishesId, dishes.getDishesId())));
                    } else {
                        result.setMaterialList(this.menuMaterialMapper.selectMaterialByDishesId(dishes.getDishesId()));
                        result.setDishesNutrition(this.baseMapper.selectDishesNutrition(dishes.getDishesId()));
                    }
                }
            } else {
                result.setMaterialList(this.menuMaterialMapper.selectMaterialByDishesId((dishesDetailList.get(0)).getDishesId()));
                result.setDishesNutrition(this.baseMapper.selectDishesNutrition((dishesDetailList.get(0)).getDishesId()));
            }

            result.setLabelIdList(this.menuDishesLabelMapper.selectLabelByDishesId((dishesDetailList.get(0)).getDishesId()));
            result.setTasteIdList(this.menuDishesTasteMapper.selectTasteByDishesId((dishesDetailList.get(0)).getDishesId()));
            result.setSuitIdList(this.menuDishesSuitMapper.selectSuitByDishesId((dishesDetailList.get(0)).getDishesId()));
            result.setPackageDishesList(this.menuDishesMapper.selectListByPackageId((dishesDetailList.get(0)).getDishesId()));
            result.setSeason(this.menuSeasonDishesService.selectSeasonByDishesId((dishesDetailList.get(0)).getDishesId()));
            result.setMealtimeTypes(this.menuMealtimeTypeDishesService.selectSeasonByDishesId((dishesDetailList.get(0)).getDishesId()));
            result.setAiPictureList(this.menuDishesMapper.selectAiPictureListByDishesId((dishesDetailList.get(0)).getDishesId()));
            return result;
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void editMenuDishesV2(MenuDishesV2EditDTO content) {
        this.checkUpdateParam(content);
        List<MenuDishes> dishesList = this.baseMapper.selectList(Wrappers.lambdaQuery(MenuDishes.class)
                .eq(MenuDishes::getBaseDishesId, content.getDishesId())
                .eq(MenuDishes::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
        if (MenuSalesTypeEnum.PORTION_ON.key().equals(content.getSalesMode()) && content.getSizeType() == 2L) {
            this.updateBaseAndSize(content.getDishesId(), content.getDishesName(), "大份", "小份");
            JSONObject sizeTypeJsonLa = new JSONObject();
            sizeTypeJsonLa.put("sizeType", "大份");
            JSONObject sizeTypeJsonLi = new JSONObject();
            sizeTypeJsonLi.put("sizeType", "小份");
            if (dishesList.size() == 2) {
                MenuDishes tempDishes = (MenuDishes) dishesList.get(0);
                Long dishesIdLa;
                Long dishesIdLi;
                if (CharSequenceUtil.contains(tempDishes.getSizeJson(), "大份")) {
                    dishesIdLa = tempDishes.getDishesId();
                    dishesIdLi = ((MenuDishes) dishesList.get(1)).getDishesId();
                } else {
                    dishesIdLi = tempDishes.getDishesId();
                    dishesIdLa = ((MenuDishes) dishesList.get(1)).getDishesId();
                }

                String dishesName = content.getDishesName();
                content.setDishesName(dishesName + "-大份");
                this.updateMenuDishes(content, content.getLargePrice(), content.getLargeWeight(), sizeTypeJsonLa.toJSONString(), dishesIdLa, content.getConvertFlag());
                content.setDishesName(dishesName + "-小份");
                this.updateMenuDishes(content, content.getLittlePrice(), content.getLittleWeight(), sizeTypeJsonLi.toJSONString(), dishesIdLi, content.getLittleConvertFlag());
            } else {
                Long dishesIdLa = ((MenuDishes) dishesList.get(0)).getDishesId();
                String dishesName = content.getDishesName();
                content.setDishesName(dishesName + "-大份");
                this.updateMenuDishes(content, content.getLargePrice(), content.getLargeWeight(), sizeTypeJsonLa.toJSONString(), dishesIdLa, content.getConvertFlag());
                MenuDishesV2AddDTO insertContent = new MenuDishesV2AddDTO();
                BeanUtil.copyProperties(content, insertContent, new String[0]);
                insertContent.setDishesName(dishesName + "-小份");
                this.insertMenuDishes(insertContent, content.getDishesId(), content.getLittlePrice(), content.getLittleWeight(), sizeTypeJsonLi.toJSONString(), content.getLittleConvertFlag());
                this.menuRecipeDishesService.update(Wrappers.lambdaUpdate(MenuRecipeDishes.class)
                        .eq(MenuRecipeDishes::getDishesId, dishesIdLa)
                        .set(MenuRecipeDishes::getSizeType, 2L));
            }
        } else {
            String sizeTypeStr = "";
            Double weight = content.getWeight();
            long sizeType = 1L;
            if (MenuSalesTypeEnum.PORTION_ON.key().equals(content.getSalesMode())) {
                sizeTypeStr = "标准";
            } else if (content.getUnitPrice() == 50) {
                sizeTypeStr = "50g";
                sizeType = 4L;
                weight = 50.0;
            } else if (content.getUnitPrice() == 100) {
                sizeTypeStr = "100g";
                sizeType = 5L;
                weight = 100.0;
            }

            this.updateBaseAndSize(content.getDishesId(), content.getDishesName(), sizeTypeStr);
            if (dishesList.size() == 2) {
                this.remove(Wrappers.lambdaQuery(MenuDishes.class)
                        .eq(MenuDishes::getDishesId, (dishesList.get(1)).getDishesId()));
                this.menuRecipeDishesService.remove(Wrappers.lambdaQuery(MenuRecipeDishes.class)
                        .eq(MenuRecipeDishes::getDishesId, (dishesList.get(1)).getDishesId()));
            }

            JSONObject sizeTypeJson = new JSONObject();
            sizeTypeJson.put("sizeType", sizeTypeStr);
            this.updateMenuDishes(content, content.getPrice(), weight, sizeTypeJson.toJSONString(), ((MenuDishes) dishesList.get(0)).getDishesId(), content.getConvertFlag());
            this.menuRecipeDishesService.update(Wrappers.lambdaUpdate(MenuRecipeDishes.class)
                    .eq(MenuRecipeDishes::getDishesId, (dishesList.get(0)).getDishesId())
                    .set(MenuRecipeDishes::getSizeType, sizeType));
        }

    }

    public void checkUpdateParam(MenuDishesV2EditDTO content) {
        MenuMetadataModel menuMetadataModel = this.allocMetadataApi.queryMetadataModel(MetadataModelTypeEnum.MENU,
                new MenuMetadataModel());
        String ifDifCanteenManage = menuMetadataModel.getIfDifCanteenManage();
        if ("1".equals(ifDifCanteenManage) && ObjectUtil.isNull(content.getCanteenId())) {
            throw new ServiceException(I18n.getMessage("menu_canteen_null", new Object[0]));
        } else {
            Integer dishesNameExist = this.menuDishesBaseMapper.selectExistNameById(content.getDishesName(), content.getCanteenId(), content.getDishesId());
            if (ObjectUtil.isNotNull(dishesNameExist)) {
                throw new ServiceException(I18n.getMessage("menu_dishes_name_repeat", new Object[0]));
            } else {
                if (CharSequenceUtil.isNotBlank(content.getDishesNum())) {
                    Integer dishesNumExist = this.menuDishesBaseMapper.selectExistNumById(content.getDishesNum(), content.getCanteenId(), content.getDishesId());
                    if (ObjectUtil.isNotNull(dishesNumExist)) {
                        throw new ServiceException(I18n.getMessage("menu_dishes_num_repeat", new Object[0]));
                    }
                }

            }
        }
    }

    public void updateBaseAndSize(Long baseDishesId, String dishesName, String... sizeTypeStrArr) {
        MenuDishesBase dishesBase = new MenuDishesBase();
        dishesBase.setBaseDishesId(baseDishesId);
        dishesBase.setDishesName(dishesName);
        this.menuDishesBaseService.updateById(dishesBase);
        this.menuDishesSizeService.remove(Wrappers.lambdaQuery(MenuDishesSize.class)
                .eq(MenuDishesSize::getBaseDishesId, baseDishesId));
        List<MenuDishesSize> dishesSizeList = Lists.newArrayList();
        String[] var6 = sizeTypeStrArr;
        int var7 = sizeTypeStrArr.length;

        for (int var8 = 0; var8 < var7; ++var8) {
            String sizeTypeStr = var6[var8];
            MenuDishesSize dishesSize = new MenuDishesSize();
            dishesSize.setBaseDishesId(baseDishesId);
            dishesSize.setSizeId(Id.next());
            dishesSize.setSizeName(sizeTypeStr);
            dishesSizeList.add(dishesSize);
        }

        this.menuDishesSizeService.saveBatch(dishesSizeList);
    }

    public void updateMenuDishes(MenuDishesV2EditDTO content, Integer price, Double weight, String sizeJson, Long dishesId, Integer convert) {
        String username = SecurityUtils.getUsername();
        this.menuMaterialDishesMapper.delete(Wrappers.lambdaQuery(MenuMaterialDishes.class)
                .eq(MenuMaterialDishes::getDishesId, dishesId));
        List<MenuDishesEditMaterialDTO> materialDTOList = content.getMaterialList();
        if (CharSequenceUtil.contains(sizeJson, "小份")) {
            materialDTOList = content.getLittleMaterialList();
        }

        MenuDishes menuDishes = new MenuDishes();
        Integer mealType = content.getMealType();
        List packageDishesList;
        List labelIdList;
        if (MenuMealTypeEnum.DISHES.key().equals(mealType) && CollUtil.isNotEmpty(materialDTOList)) {
            packageDishesList = CopyListUtil.copyListProperties(materialDTOList, MenuMaterialDishes.class);
            if (packageDishesList.size() > MenuConstant.MAX_MATERIAL_SIZE) {
                throw new ServiceException(I18n.getMessage("menu_label_over_size", new Object[0]));
            }

            this.insertMaterialDishesBatch(packageDishesList, dishesId, username);
            labelIdList = this.menuNutritionService.selectNutritionWeightList(dishesId);
            if (CollUtil.isNotEmpty(labelIdList)) {
                NutritionEntity nutritionEntity = NutritionEntityUtil.countNutrition(labelIdList);
                BeanUtils.copyProperties(nutritionEntity, menuDishes);
            }
        }

        List<MenuPackageDishesEditDTO> newpackageDishesList = content.getPackageDishesList();
        List tasteIdList;
        if (MenuMealTypeEnum.PACKAGE_MEAL.key().equals(mealType) && CollUtil.isNotEmpty(newpackageDishesList)) {
            this.menuPackageDishesMapper.delete(Wrappers.lambdaQuery(MenuPackageDishes.class)
                    .eq(MenuPackageDishes::getPackageId, dishesId));
            List<MenuPackageDishes> packageDishesAddList = Lists.newArrayList();
            newpackageDishesList.forEach((pd) -> {
                MenuPackageDishes packageDishes = new MenuPackageDishes();
                packageDishes.setPackageId(dishesId);
                packageDishes.setDishesId(pd.getDishesId());
                packageDishes.setProportion(pd.getProportion());
                packageDishes.setCrby(username);
                packageDishesAddList.add(packageDishes);
            });
            this.menuPackageDishesMapper.insertBatch(packageDishesAddList);
            tasteIdList = this.baseMapper.selectNutritionWeightList(dishesId);
            NutritionEntity nutritionEntity = NutritionEntityUtil.countNutrition(tasteIdList);
            log.info("计算完毕营养信息整合结果nutritionEntity : {}", nutritionEntity);
            BeanUtils.copyProperties(nutritionEntity, menuDishes);
        }

        this.menuLabelDishesMapper.delete(Wrappers.lambdaQuery(MenuLabelDishes.class)
                .eq(MenuLabelDishes::getDishesId, dishesId));
        labelIdList = content.getLabelIdList();
        if (CollUtil.isNotEmpty(labelIdList)) {
            this.insertLabelDishesBatch(labelIdList, dishesId, username);
        }

        this.menuTasteDishesMapper.delete(Wrappers.lambdaQuery(MenuTasteDishes.class)
                .eq(MenuTasteDishes::getDishesId, dishesId));
        tasteIdList = content.getTasteIdList();
        if (CollUtil.isNotEmpty(tasteIdList)) {
            this.insertTasteDishesBatch(tasteIdList, dishesId, username);
        }

        this.menuSuitDishesMapper.delete(Wrappers.lambdaQuery(MenuSuitDishes.class)
                .eq(MenuSuitDishes::getDishesId, dishesId));
        List<Long> suitIdList = content.getSuitIdList();
        if (CollUtil.isNotEmpty(suitIdList)) {
            this.insertSuitDishesBatch(suitIdList, dishesId, username);
        }

        List<Long> season = content.getSeason();
        List<Integer> mealtimeTypes = content.getMealtimeTypes();
        this.menuSeasonDishesService.deleteByDishesId(dishesId);
        if (CollUtil.isNotEmpty(season)) {
            this.menuSeasonDishesService.insertBatch(season, dishesId);
        }

        this.menuMealtimeTypeDishesService.deleteByDishesId(dishesId);
        if (CollUtil.isNotEmpty(mealtimeTypes)) {
            this.menuMealtimeTypeDishesService.insertBatch(mealtimeTypes, dishesId);
        }

        BeanUtils.copyProperties(content, menuDishes);
        menuDishes.setUpby(username);
        Long typeId = menuDishes.getTypeId();
        if (typeId != null && typeId != -1L) {
            MenuDishesType menuDishesType = this.menuDishesTypeMapper.selectOne(Wrappers.lambdaQuery(MenuDishesType.class)
                    .eq(MenuDishesType::getTypeId, typeId).eq(MenuDishesType::getDelFlag, LeConstants.COMMON_NO));
            if (!menuDishesType.getTypeName().contains("鱼") && !menuDishesType.getTypeName().contains("半荤")) {
                if (!menuDishesType.getTypeName().contains("油脂") && !menuDishesType.getTypeName().contains("甜") && !menuDishesType.getTypeName().contains("主荤")) {
                    menuDishes.setInitialScore(NutritionConstants.SCORE_EIGHTY);
                } else {
                    menuDishes.setInitialScore(NutritionConstants.SCORE_SIXTY);
                }
            } else {
                menuDishes.setInitialScore(NutritionConstants.SCORE_SEVENTY);
            }
        } else {
            typeId = this.menuDishesTypeMapper.selectDefaultTypeId(MenuDishesTypeDefaultFlagEnum.DEFAULT.key());
            menuDishes.setTypeId(typeId);
        }

        if (ObjectUtil.isNotNull(menuDishes.getSodium())) {
            if (menuDishes.getSodium() > NutritionConstants.SODIUM.doubleValue()) {
                if (menuDishes.getInitialScore() != null) {
                    menuDishes.setInitialScore(menuDishes.getInitialScore() - NutritionConstants.SCORE_TEN);
                } else {
                    menuDishes.setInitialScore(NutritionConstants.SCORE_SEVENTY);
                }
            } else {
                menuDishes.setInitialScore(NutritionConstants.SCORE_EIGHTY);
            }
        }

        Long cookId = menuDishes.getCookId();
        Integer initialScore;
        if (ObjectUtil.isNotNull(cookId)) {
            MenuDishesCook menuDishesCook = this.menuDishesCookMapper.selectOne(Wrappers.lambdaQuery(MenuDishesCook.class)
                    .eq(MenuDishesCook::getCookId, cookId).eq(MenuDishesCook::getDelFlag, LeConstants.COMMON_NO));
            if (ObjectUtil.isNotNull(menuDishes.getInitialScore())) {
                initialScore = menuDishes.getInitialScore();
            } else {
                initialScore = NutritionConstants.SCORE_EIGHTY;
            }

            String cookName = menuDishesCook.getCookName();
            if (cookName.contains(MenuDishesCookEnum.SALAD.value())) {
                menuDishes.setInitialScore(initialScore + NutritionConstants.SCORE_TEN);
            } else if (!cookName.contains(MenuDishesCookEnum.STEAM.value()) && !cookName.contains(MenuDishesCookEnum.COOK.value()) && !cookName.contains(MenuDishesCookEnum.STEW.value())) {
                if (!cookName.contains(MenuDishesCookEnum.BRAISED.value()) && !cookName.contains(MenuDishesCookEnum.DRY_STIR_FRY.value()) && !cookName.contains(MenuDishesCookEnum.SWEET_SOUR.value())) {
                    menuDishes.setInitialScore(NutritionConstants.SCORE_EIGHTY);
                } else {
                    menuDishes.setInitialScore(initialScore - NutritionConstants.SCORE_TEN);
                }
            } else {
                menuDishes.setInitialScore(initialScore + NutritionConstants.SCORE_FIVE);
            }
        }

        String sourceName = this.baseMapper.selectDishesNameByWrapper(Wrappers.lambdaQuery(MenuDishes.class)
                .eq(MenuDishes::getDishesId, dishesId));
        if (StringUtils.isNotBlank(content.getDishesName()) && !content.getDishesName().equals(sourceName)) {
            MenuaiDishesNameEditDTO dishesNameEditDTO = new MenuaiDishesNameEditDTO();
            dishesNameEditDTO.setDishesId(dishesId);
            dishesNameEditDTO.setOldDishesName(sourceName);
            dishesNameEditDTO.setNewDishesName(content.getDishesName());
            this.menuaiServiceApi.editMenuaiDishesName(dishesNameEditDTO);
        }

        menuDishes.setPinyinInitials(PinyinUtil.getFirstLetterFromChinese(menuDishes.getDishesName()));
        menuDishes.setPinyinFull(PinyinUtil.convertChineseToPinyin(menuDishes.getDishesName()));
        if (ObjectUtil.isNotNull(weight)) {
            menuDishes.setWeight(weight);
        }

        menuDishes.setPrice(price);
        initialScore = content.getMaterialCost();
        if (CharSequenceUtil.contains(sizeJson, "小份")) {
            initialScore = content.getLittleMaterialCost();
        }

        int grossProfit = price - initialScore;
        menuDishes.setMaterialCost(initialScore);
        menuDishes.setGrossProfit(grossProfit);
        if (price != 0) {
            BigDecimal grossProfitRate = BigDecimal.valueOf((long) grossProfit).divide(BigDecimal.valueOf((long) price), 2, RoundingMode.HALF_UP);
            menuDishes.setGrossProfitRate(grossProfitRate);
        }

        menuDishes.setSizeJson(sizeJson);
        menuDishes.setDishesId(dishesId);
        menuDishes.setConvertFlag(convert);
        this.baseMapper.update(menuDishes, Wrappers.lambdaUpdate(MenuDishes.class).eq(MenuDishes::getDishesId, dishesId)
                .set(ObjectUtil.isNull(menuDishes.getCookId()), MenuDishes::getCookId, -1L)
                .set(ObjectUtil.isNull(menuDishes.getPungencyDegree()), MenuDishes::getPungencyDegree, null)
                .set(ObjectUtil.isNull(menuDishes.getStyleId()), MenuDishes::getStyleId, null)
                .set(ObjectUtil.isNull(menuDishes.getEffectId()), MenuDishes::getEffectId, null)
                .set(ObjectUtil.isNull(menuDishes.getGrossProfitRate()), MenuDishes::getGrossProfitRate, null));
        String redisKey = String.format("yst:%s:recipe:%s:detail:%s", TenantContextHolder.getTenantId(), "*", "*");
        RedisUtil.deleteByPattern(redisKey);
        MqUtil.sendDataChange(menuDishes, LeMqConstant.DataChangeType.UPDATE, LeMqConstant.Topic.DATA_CHANGE_DISHES);
    }

    public void updateMenuDishes(MenuDishesV2EditDTO content, Integer price, Double weight, String sizeJson, Long dishesId) {
        this.updateMenuDishes(content, price, weight, sizeJson, dishesId, 1);
    }

    @Override
    public void removeByDishesIdV2(Long dishesId) {
        List<Long> dishesIdList = this.baseMapper.selectdishesIdList(Wrappers.lambdaQuery(MenuDishes.class)
                .eq(MenuDishes::getBaseDishesId, dishesId)
                .eq(MenuDishes::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
        if (!CollUtil.isEmpty(dishesIdList)) {
            Integer packageDishesExist = this.menuPackageDishesMapper.selectExistByWrapper(Wrappers.lambdaQuery(MenuPackageDishes.class)
                    .in(MenuPackageDishes::getDishesId, dishesIdList).last("limit 1"));
            Integer recipeDishesExist = this.menuRecipeDishesMapper.selectExistLeftJoinByDishesId(dishesIdList);
            if (!ObjectUtil.isNotNull(packageDishesExist) && !ObjectUtil.isNotNull(recipeDishesExist)) {
                List<MenuDishes> dishesList = this.menuDishesMapper.selectDishesIdAndNameListByWrapper(Wrappers.lambdaQuery(MenuDishes.class)
                        .in(MenuDishes::getDishesId, dishesIdList)
                        .eq(MenuDishes::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
                this.menuDishesBaseService.removeById(dishesId);
                this.menuDishesSizeService.remove(Wrappers.lambdaQuery(MenuDishesSize.class)
                        .eq(MenuDishesSize::getBaseDishesId, dishesId));
                List<Integer> customIdList = this.baseMapper.selectCustomIdByWrapper(Wrappers.lambdaQuery(MenuDishes.class)
                        .in(MenuDishes::getDishesId, dishesIdList));
                if (CollUtil.isNotEmpty(customIdList)) {
                    this.menuCustomDictMapper.update(null, Wrappers.lambdaUpdate(MenuCustomDict.class)
                                    .in(MenuCustomDict::getCustomId, customIdList)
                                    .set(MenuCustomDict::getIfUse, MenuCustomIfUseEnum.UNUSED.key()));
                }

                this.baseMapper.update(null, new LambdaUpdateWrapper<>(MenuDishes.class)
                        .in(MenuDishes::getDishesId, dishesIdList)
                        .set(MenuDishes::getDelFlag, DelFlagEnum.DEL_TRUE.key())
                        .set(MenuDishes::getCustomId, -1));
                this.menuMaterialDishesMapper.update(null, Wrappers.lambdaUpdate(MenuMaterialDishes.class)
                        .in(MenuMaterialDishes::getDishesId, dishesIdList)
                        .set(MenuMaterialDishes::getDelFlag, DelFlagEnum.DEL_TRUE.key()));
                this.menuLabelDishesMapper.update(null, Wrappers.lambdaUpdate(MenuLabelDishes.class)
                        .in(MenuLabelDishes::getDishesId, dishesIdList)
                        .set(MenuLabelDishes::getDelFlag, DelFlagEnum.DEL_TRUE.key()));
                this.menuTasteDishesMapper.update(null, Wrappers.lambdaUpdate(MenuTasteDishes.class)
                        .in(MenuTasteDishes::getDishesId, dishesIdList)
                        .set(MenuTasteDishes::getDelFlag, DelFlagEnum.DEL_TRUE.key()));
                this.menuSuitDishesMapper.update(null, Wrappers.lambdaUpdate(MenuSuitDishes.class)
                        .in(MenuSuitDishes::getDishesId, dishesIdList)
                        .set(MenuSuitDishes::getDelFlag, DelFlagEnum.DEL_TRUE.key()));
                this.menuPackageDishesMapper.delete(Wrappers.lambdaUpdate(MenuPackageDishes.class)
                        .in(MenuPackageDishes::getPackageId, dishesIdList));
                this.asyncTaskExecutor.execute(() -> {
                    this.removeDishesFromAiServer(dishesIdList, dishesList);
                });
                dishesIdList.forEach((dishesIdRe) -> {
                    MqUtil.sendDataChange(dishesId, LeMqConstant.DataChangeType.REMOVE, LeMqConstant.Topic.DATA_CHANGE_DISHES);
                });
            } else {
                throw new ServiceException(I18n.getMessage("menu_dishes_use_del", new Object[0]));
            }
        }
    }
    public void removeDishesFromAiServer(List<Long> dishesIdList, List<MenuDishes> deleteDishesList) {
        List<MenuaiPicture> menuaiPicturesList = this.menuaiPictureMapper.selectList(Wrappers.lambdaQuery(MenuaiPicture.class)
                .in(MenuaiPicture::getDishesId, dishesIdList));
        List<MenuaiPictureRemoveDTO> contentList = menuaiPicturesList.stream().map((e) -> {
            MenuaiPictureRemoveDTO dto = new MenuaiPictureRemoveDTO();
            dto.setPictureId(e.getId());
            dto.setPicType(e.getPictureType());
            return dto;
        }).collect(Collectors.toList());
        this.menuaiV4Service.removeDishesPictureBatch(contentList);
        deleteDishesList.forEach((e) -> {
            this.menuaiV4Service.removeDishesFromAi(e.getDishesId(), e.getDishesName());
        });
    }
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void copyMenuDishes(MenuDishesCopyDTO content) {
        Long canteenId = content.getCanteenId();
        List<Long> baseIdList = content.getDishesIdList();
        AllocCanteen allocCanteen = this.allocCanteenApi.getAllocCanteen(canteenId);
        List<MenuBaseAndDishesModel> baseDishesList = this.menuDishesMapper.selectBaseAndDetailList(baseIdList);
        List<Long> dishesIdList = baseDishesList.stream().map(MenuBaseAndDishesModel::getDishesId).collect(Collectors.toList());
        List<String> dishesNameList = baseDishesList.stream().map(MenuBaseAndDishesModel::getBaseDishesName).collect(Collectors.toList());
        Map<Long, String> baseNameMap = baseDishesList.stream().collect(Collectors.toMap(MenuBaseAndDishesModel::getDishesId, MenuBaseAndDishesModel::getBaseDishesName));
        List<MenuDishes> sourceDishesList = this.menuDishesMapper.selectList(Wrappers.lambdaQuery(MenuDishes.class).in(MenuDishes::getDishesId, dishesIdList));
        List<MenuDishes> repeatDishesList = this.menuDishesMapper.selectListByBase(dishesNameList, canteenId);
        Map<String, MenuDishes> repeatMap = Maps.newHashMap();
        if (CollUtil.isNotEmpty(repeatDishesList)) {
            repeatMap = repeatDishesList.stream().collect(Collectors.toMap(MenuDishes::getDishesName, Function.identity()));
        }

        int repeatCount = CollUtil.isEmpty(repeatDishesList) ? 0 : repeatDishesList.size();
        List<Integer> customIdList = this.menuCustomDictMapper.selectMinCustomIdList(dishesIdList.size() - repeatCount);
        if (dishesIdList.size() != repeatCount && CollUtil.isEmpty(customIdList)) {
            throw new ServiceException(I18n.getMessage("menu_custom_id_over_size", new Object[0]));
        } else {
            if (CollUtil.isNotEmpty(customIdList)) {
                this.menuCustomDictMapper.update(null, Wrappers.lambdaUpdate(MenuCustomDict.class)
                        .in(MenuCustomDict::getCustomId, customIdList)
                        .set(MenuCustomDict::getIfUse, 1));
            }

            List<MenuLabelDishes> sourceLabelList = this.menuLabelDishesMapper.selectList(Wrappers.lambdaQuery(MenuLabelDishes.class)
                    .in(MenuLabelDishes::getDishesId, dishesIdList));
            Map<Long, List<MenuLabelDishes>> labelMap = Maps.newHashMap();
            if (CollUtil.isNotEmpty(sourceLabelList)) {
                Set<Long> dishesIdSet =
                        sourceLabelList.stream()
                                .map(MenuLabelDishes::getDishesId).collect(Collectors.toSet());
                dishesIdSet.forEach((d) -> {
                    labelMap.put(d, sourceLabelList.stream().filter((s) -> {
                        return d.equals(s.getDishesId());
                    }).collect(Collectors.toList()));
                });
            }

            List<MenuTasteDishes> sourceTasteList = this.menuTasteDishesMapper.selectList(Wrappers.lambdaQuery(MenuTasteDishes.class)
                    .in(MenuTasteDishes::getDishesId, dishesIdList));
            Map<Long, List<MenuTasteDishes>> tasteMap = Maps.newHashMap();
            if (CollUtil.isNotEmpty(sourceTasteList)) {
                Set<Long> dishesIdSet = sourceTasteList.stream().map(MenuTasteDishes::getDishesId).collect(Collectors.toSet());
                dishesIdSet.forEach((d) -> {
                    tasteMap.put(d, sourceTasteList.stream().filter((s) -> {
                        return d.equals(s.getDishesId());
                    }).collect(Collectors.toList()));
                });
            }

            List<MenuSuitDishes> sourceSuitList = this.menuSuitDishesMapper.selectList(Wrappers.lambdaQuery(MenuSuitDishes.class)
                    .in(MenuSuitDishes::getDishesId, dishesIdList));
            Map<Long, List<MenuSuitDishes>> suitMap = Maps.newHashMap();
            if (CollUtil.isNotEmpty(sourceSuitList)) {
                Set<Long> dishesIdSet = sourceSuitList.stream().map(MenuSuitDishes::getDishesId).collect(Collectors.toSet());
                dishesIdSet.forEach((d) -> {
                    suitMap.put(d, sourceSuitList.stream().filter((s) -> {
                        return d.equals(s.getDishesId());
                    }).collect(Collectors.toList()));
                });
            }

            List<MenuMaterialDishes> sourceMaterialList = this.menuMaterialDishesMapper.selectList(Wrappers.lambdaQuery(MenuMaterialDishes.class).in(MenuMaterialDishes::getDishesId, dishesIdList));
            Map<Long, List<MenuMaterialDishes>> materialMap = Maps.newHashMap();
            if (CollUtil.isNotEmpty(sourceMaterialList)) {
                Set<Long> dishesIdSet = sourceMaterialList.stream().map(MenuMaterialDishes::getDishesId).collect(Collectors.toSet());
                dishesIdSet.forEach((d) -> {
                    materialMap.put(d, sourceMaterialList.stream().filter((s) -> {
                        return d.equals(s.getDishesId());
                    }).collect(Collectors.toList()));
                });
            }

            List<MenuPackageDishes> sourcePackageList = this.menuPackageDishesMapper.selectList(Wrappers.lambdaQuery(MenuPackageDishes.class).in(MenuPackageDishes::getPackageId, dishesIdList));
            Map<Long, List<MenuPackageDishes>> packageMap = Maps.newHashMap();
            if (CollUtil.isNotEmpty(sourcePackageList)) {
                Set<Long> dishesIdSet =
                        sourcePackageList.stream().map(MenuPackageDishes::getDishesId).collect(Collectors.toSet());
                dishesIdSet.forEach((d) -> {
                    packageMap.put(d, sourcePackageList.stream().filter((s) -> {
                        return d.equals(s.getPackageId());
                    }).collect(Collectors.toList()));
                });
            }

            List<MenuLabelDishes> targetLabelList = Lists.newArrayList();
            List<MenuTasteDishes> targetTasteList = Lists.newArrayList();
            List<MenuSuitDishes> targetSuitList = Lists.newArrayList();
            List<MenuMaterialDishes> targetMaterialList = Lists.newArrayList();
            List<MenuPackageDishes> targetPackageList = Lists.newArrayList();
            List<MenuDishesBase> dishesBaseList = Lists.newArrayList();
            List<MenuDishesSize> dishesSizeList = Lists.newArrayList();
            int index = 0;
            Set<Long> delDishesIdSet = Sets.newTreeSet();
            Set<Long> delBaseIdSet = Sets.newTreeSet();
            Map<Long, Long> processedBaseIdMap = Maps.newHashMap();
            Iterator var35 = sourceDishesList.iterator();

            while(var35.hasNext()) {
                MenuDishes sourceDishes = (MenuDishes)var35.next();
                Long sourceDishesId = sourceDishes.getDishesId();
                MenuDishes repeatDishes = (MenuDishes)((Map)repeatMap).get(sourceDishes.getDishesName());
                Long targetDishesId;
                Integer customId;
                if (ObjectUtil.isNotNull(repeatDishes)) {
                    targetDishesId = repeatDishes.getDishesId();
                    customId = repeatDishes.getCustomId();
                    delDishesIdSet.add(repeatDishes.getDishesId());
                    delBaseIdSet.add(repeatDishes.getBaseDishesId());
                    sourceDishes.setDishesNum(repeatDishes.getDishesNum());
                } else {
                    targetDishesId = Id.next();
                    customId = (Integer)customIdList.get(index++);
                    sourceDishes.setDishesNum((String)null);
                }

                Long baseDishesId = (Long)processedBaseIdMap.get(sourceDishes.getBaseDishesId());
                if (ObjectUtil.isNull(baseDishesId)) {
                    baseDishesId = Id.next();
                    MenuDishesBase dishesBase = new MenuDishesBase();
                    dishesBase.setBaseDishesId(baseDishesId);
                    dishesBase.setDishesName((String)baseNameMap.get(sourceDishes.getDishesId()));
                    dishesBaseList.add(dishesBase);
                    MenuDishesSize dishesSizeLa;
                    if (MenuSalesTypeEnum.PORTION_ON.key().equals(sourceDishes.getSalesMode()) && sourceDishes.getSizeType() == 2L) {
                        MenuDishesSize dishesSizeLas = new MenuDishesSize();
                        dishesSizeLas.setBaseDishesId(baseDishesId);
                        dishesSizeLas.setSizeId(Id.next());
                        dishesSizeLas.setSizeName("大份");
                        dishesSizeList.add(dishesSizeLas);
                        dishesSizeLas = new MenuDishesSize();
                        dishesSizeLas.setBaseDishesId(baseDishesId);
                        dishesSizeLas.setSizeId(Id.next());
                        dishesSizeLas.setSizeName("小份");
                        dishesSizeList.add(dishesSizeLas);
                    } else {
                        String sizeTypeStr = "";
                        if (MenuSalesTypeEnum.PORTION_ON.key().equals(sourceDishes.getSalesMode())) {
                            sizeTypeStr = "标准";
                        } else if (sourceDishes.getUnitPrice() == 50) {
                            sizeTypeStr = "50g";
                        } else if (sourceDishes.getUnitPrice() == 100) {
                            sizeTypeStr = "100g";
                        }

                        dishesSizeLa = new MenuDishesSize();
                        dishesSizeLa.setBaseDishesId(baseDishesId);
                        dishesSizeLa.setSizeId(Id.next());
                        dishesSizeLa.setSizeName(sizeTypeStr);
                        dishesSizeList.add(dishesSizeLa);
                    }

                    processedBaseIdMap.put(sourceDishes.getBaseDishesId(), baseDishesId);
                }

                sourceDishes.setId(null);
                sourceDishes.setBaseDishesId(baseDishesId);
                sourceDishes.setCanteenId(canteenId);
                sourceDishes.setAreaId(allocCanteen.getAreaId());
                sourceDishes.setShopstallId(null);
                sourceDishes.setCrtime(LocalDateTime.now());
                sourceDishes.setUptime(LocalDateTime.now());
                sourceDishes.setDishesId(targetDishesId);
                sourceDishes.setCustomId(customId);
                List<MenuLabelDishes> labelList = labelMap.get(sourceDishesId);
                if (CollUtil.isNotEmpty(labelList)) {
                    labelList.forEach((l) -> {
                        l.setId(null);
                        l.setDishesId(targetDishesId);
                    });
                    targetLabelList.addAll(labelList);
                }

                List<MenuTasteDishes> tasteList = tasteMap.get(sourceDishesId);
                if (CollUtil.isNotEmpty(tasteList)) {
                    tasteList.forEach((t) -> {
                        t.setId(null);
                        t.setDishesId(targetDishesId);
                    });
                    targetTasteList.addAll(tasteList);
                }

                List<MenuSuitDishes> suitList = suitMap.get(sourceDishesId);
                if (CollUtil.isNotEmpty(suitList)) {
                    suitList.forEach((s) -> {
                        s.setId(null);
                        s.setDishesId(targetDishesId);
                    });
                    targetSuitList.addAll(suitList);
                }

                List<MenuMaterialDishes> materialList = materialMap.get(sourceDishesId);
                if (CollUtil.isNotEmpty(materialList)) {
                    materialList.forEach((m) -> {
                        m.setId(null);
                        m.setDishesId(targetDishesId);
                    });
                    targetMaterialList.addAll(materialList);
                }

                List<MenuPackageDishes> packageList = packageMap.get(sourceDishesId);
                if (CollUtil.isNotEmpty(packageList)) {
                    packageList.forEach((p) -> {
                        p.setId(null);
                        p.setPackageId(targetDishesId);
                    });
                    targetPackageList.addAll(packageList);
                }
            }

            if (CollUtil.isNotEmpty(delDishesIdSet)) {
                this.remove(Wrappers.lambdaQuery(MenuDishes.class).in(MenuDishes::getDishesId, delDishesIdSet));
                this.menuDishesBaseService.removeBatchByIds(delBaseIdSet);
                this.menuDishesSizeService.remove(Wrappers.lambdaQuery(MenuDishesSize.class)
                        .in(MenuDishesSize::getBaseDishesId, delBaseIdSet));
                this.menuLabelDishesService.remove(Wrappers.lambdaQuery(MenuLabelDishes.class).in(MenuLabelDishes::getDishesId, delDishesIdSet));
                this.menuTasteDishesService.remove(Wrappers.lambdaQuery(MenuTasteDishes.class).in(MenuTasteDishes::getDishesId, delDishesIdSet));
                this.menuSuitDishesService.remove(Wrappers.lambdaQuery(MenuSuitDishes.class).in(MenuSuitDishes::getDishesId, delDishesIdSet));
                this.menuMaterialDishesService.remove(Wrappers.lambdaQuery(MenuMaterialDishes.class).in(MenuMaterialDishes::getDishesId, delDishesIdSet));
                this.menuPackageDishesService.remove(Wrappers.lambdaQuery(MenuPackageDishes.class).in(MenuPackageDishes::getDishesId, delDishesIdSet));
            }

            (sourceDishesList.stream().collect(Collectors.groupingBy(MenuDishes::getBaseDishesId))).forEach((k, value) -> {
                Iterator var3 = value.iterator();
                while(var3.hasNext()) {
                    MenuDishes menuDishes = (MenuDishes)var3.next();
                    if (ObjectUtil.isEmpty(menuDishes.getDishesNum())) {
                        String sequenceNo = this.menuSequenceService.getSequenceNo(2);
                        menuDishes.setDishesNum(sequenceNo);
                    }
                }

            });
            super.saveBatch(sourceDishesList);
            this.menuDishesBaseService.saveBatch(dishesBaseList);
            this.menuDishesSizeService.saveBatch(dishesSizeList);
            if (CollUtil.isNotEmpty(targetLabelList)) {
                this.menuLabelDishesService.saveBatch(targetLabelList);
            }

            if (CollUtil.isNotEmpty(targetTasteList)) {
                this.menuTasteDishesService.saveBatch(targetTasteList);
            }

            if (CollUtil.isNotEmpty(targetSuitList)) {
                this.menuSuitDishesService.saveBatch(targetSuitList);
            }

            if (CollUtil.isNotEmpty(targetMaterialList)) {
                this.menuMaterialDishesService.saveBatch(targetMaterialList);
            }

            if (CollUtil.isNotEmpty(targetPackageList)) {
                this.menuPackageDishesService.saveBatch(targetPackageList);
            }

        }
    }

    @Override
    public List<MenuAllTypeDishesVO> getTypeDishesList(MenuTypeDishesDTO content) {
        MgrUserAuthPO authPO = this.mgrAuthApi.getUserAuthPO();
        return this.getTypeDishesList(content, authPO);
    }
    public List<MenuAllTypeDishesVO> getTypeDishesList(MenuTypeDishesDTO content, MgrUserAuthPO authPO) {
        List<MenuAllTypeDishesVO> resultList = this.baseMapper.selectTypeDishesList(content, authPO);
        if (CollUtil.isEmpty(resultList)) {
            return resultList;
        } else {
            List<MenuDishesCostModel> costList = this.baseMapper.selectMaterialCostList(Wrappers.lambdaQuery(MenuDishes.class)
                    .in(MenuDishes::getBaseDishesId, resultList
                            .stream()
                            .map(MenuAllTypeDishesVO::getDishesId).collect(Collectors.toList()))
                    .eq(MenuDishes::getSizeJson, "{\"sizeType" +
                    "\":\"小份\"}"));
            if (CollUtil.isNotEmpty(costList)) {
                Map<Long, Integer> mostMap = costList.stream().collect(Collectors.toMap(MenuDishesCostModel::getBaseDishesId, MenuDishesCostModel::getMaterialCost));
                resultList.forEach((x) -> {
                    x.setLittleMaterialCost((Integer)mostMap.get(x.getDishesId()));
                });
            }

            return resultList;
        }
    }
    @Override
    public PageVO<MenuAllTypeDishesVO> getTypeDishesListByPage(MenuTypeDishesDTO content) {
        MgrUserAuthPO authPO = this.mgrAuthApi.getUserAuthPO();
        PageHelper.startPage(content.getPageNum(), content.getPageSize());
        List<MenuAllTypeDishesVO> resultList = this.getTypeDishesList(content, authPO);
        return PageVO.of(resultList);
    }
    @Override
    public String getDifCanteenManage() {
        MenuMetadataModel menuMetadataModel = this.allocMetadataApi.queryMetadataModel(MetadataModelTypeEnum.MENU,
                new MenuMetadataModel());
        String ifDifCanteenManage = menuMetadataModel.getIfDifCanteenManage();
        return Optional.ofNullable(ifDifCanteenManage).orElse("2");
    }
    @Override
    public void editDifCanteenManage(MenuDifCanteenManageEditDTO content) {
        if ("1".equals(content.getIfDifCanteenManage())) {
            this.baseMapper.update(null, Wrappers.lambdaUpdate(MenuDishes.class)
                    .set(MenuDishes::getHideFlag, 2));
        } else {
            this.baseMapper.update(null, Wrappers.lambdaUpdate(MenuDishes.class)
                    .ne(MenuDishes::getCanteenId, content.getCanteenId())
                    .ne(MenuDishes::getCanteenId, -1L)
                    .set(MenuDishes::getHideFlag, 1));
        }

        MenuMetadataDTO menuMetadataDTO = new MenuMetadataDTO();
        menuMetadataDTO.setIfDifCanteenManage(content.getIfDifCanteenManage());
        this.allocMetadataApi.saveMetadataModel(MetadataModelTypeEnum.MENU, menuMetadataDTO);
    }
    @Override
    public Boolean newImportDishes(List<MenuDishesImportDTO> menuDishesImportDTOS) {
        String dishesLockRedisKey = "yst:merchant-id:dishes:lock".replace("merchant-id", TenantContextHolder.getTenantId().toString());
        String asyncState = this.stringRedisTemplate.opsForValue().get(dishesLockRedisKey);
        if (StringUtils.isNotBlank(asyncState)) {
            throw new ServiceException("导入菜品进行中,不要重复操作哦 ^_^");
        } else {
            try {
                String currentTraceId = LogUtil.getCurrentTraceId();
                String username = SecurityUtils.getUsername();
                this.asyncTaskExecutor.execute(() -> {
                    LogUtil.putLogTraceId(currentTraceId);
                    log.info("[批量导入菜品]开始导入菜品");
                    this.importDishesDTO(menuDishesImportDTOS, username);
                });
            } catch (Exception var7) {
                log.info("[批量导入菜品]系统错误：{}", var7.getMessage(), var7);
                throw new ServiceException("批量导入菜品发生错误");
            }
            return true;
        }
    }
    public void importDishesDTO(List<MenuDishesImportDTO> importDishesList, String username) {
        DishesImportCheckResult dishesImportCheckResult = new DishesImportCheckResult();
        List<MenuDishesImportDTO> successList = new ArrayList<>();
        List<MenuDishesImportDTO> errorList = new ArrayList<>();
        String dishesLockRedisKey = "yst:merchant-id:dishes:lock".replace("merchant-id", TenantContextHolder.getTenantId().toString());
        this.stringRedisTemplate.opsForValue().set(dishesLockRedisKey, "1", 20L, TimeUnit.MINUTES);

        try {
            ImportDishesContext importDishesContext = this.getImportDishesContext(username);
            List<MenuDishes> dishesAddList = Lists.newArrayList();
            List<MenuDishesBase> dishesBaseList = Lists.newArrayList();
            List<MenuDishesSize> dishesSizeList = Lists.newArrayList();
            Iterator var11 = importDishesList.iterator();

            while(var11.hasNext()) {
                MenuDishesImportDTO importDishes = (MenuDishesImportDTO)var11.next();

                try {
                    String sizeTypeStr;
                    JSONObject sizeTypeJson;
                    if (MenuSalesTypeEnum.PORTION_ON.key().equals(importDishes.getSalesMode()) && importDishes.getSizeType() == 2L) {
                        MenuDishesBase dishesBase = this.generateBaseAndSize(dishesSizeList, importDishes.getDishesName(), "大份", "小份");
                        sizeTypeStr = importDishes.getDishesName();
                        MenuDishes dishesAddLa = this.generateDishes(importDishes, importDishesContext);
                        sizeTypeJson = new JSONObject();
                        sizeTypeJson.put("sizeType", "大份");
                        dishesAddLa.setBaseDishesId(dishesBase.getBaseDishesId());
                        dishesAddLa.setPrice(dishesAddLa.getLargePrice());
                        dishesAddLa.setWeight(dishesAddLa.getLargeWeight());
                        dishesAddLa.setSizeJson(sizeTypeJson.toJSONString());
                        dishesAddLa.setDishesName(sizeTypeStr + "-大份");
                        MenuDishes dishesAddLi = this.generateDishes(importDishes, importDishesContext);
                        JSONObject sizeTypeJsonLi = new JSONObject();
                        sizeTypeJsonLi.put("sizeType", "小份");
                        dishesAddLi.setBaseDishesId(dishesBase.getBaseDishesId());
                        dishesAddLi.setPrice(dishesAddLi.getLittlePrice());
                        dishesAddLi.setWeight(dishesAddLi.getLittleWeight());
                        dishesAddLi.setSizeJson(sizeTypeJsonLi.toJSONString());
                        dishesAddLi.setDishesName(sizeTypeStr + "-小份");
                        dishesBaseList.add(dishesBase);
                        dishesAddList.add(dishesAddLa);
                        dishesAddList.add(dishesAddLi);
                    } else {
                        MenuDishes dishesAdd = this.generateDishes(importDishes, importDishesContext);
                        sizeTypeStr = "";
                        if (MenuSalesTypeEnum.PORTION_ON.key().equals(importDishes.getSalesMode())) {
                            sizeTypeStr = "标准";
                        } else if (importDishes.getUnitPrice() == 50) {
                            sizeTypeStr = "50g";
                            dishesAdd.setWeight(50.0);
                        } else if (importDishes.getUnitPrice() == 100) {
                            sizeTypeStr = "100g";
                            dishesAdd.setWeight(100.0);
                        }

                        MenuDishesBase dishesBase = this.generateBaseAndSize(dishesSizeList, importDishes.getDishesName(), sizeTypeStr);
                        sizeTypeJson = new JSONObject();
                        sizeTypeJson.put("sizeType", sizeTypeStr);
                        dishesAdd.setBaseDishesId(dishesBase.getBaseDishesId());
                        dishesAdd.setSizeJson(sizeTypeJson.toJSONString());
                        dishesBaseList.add(dishesBase);
                        dishesAddList.add(dishesAdd);
                    }

                    successList.add(importDishes);
                } catch (Exception var23) {
                    log.error("导入菜品异常: ", var23);
                }
            }

            if (CollUtil.isNotEmpty(dishesAddList)) {
                MenuDishesMapper var10001 = this.menuDishesMapper;
                Objects.requireNonNull(var10001);
                dishesAddList.forEach(var10001::insert);
                this.menuDishesBaseService.saveBatch(dishesBaseList);
                this.menuDishesSizeService.saveBatch(dishesSizeList);
            }

            MqUtil.sendDataChange(dishesAddList, LeMqConstant.DataChangeType.ADD, LeMqConstant.Topic.DATA_CHANGE_DISHES);
            dishesImportCheckResult.setSuccessList(successList);
            dishesImportCheckResult.setErrorList(errorList);
            String resultRedisKey = "yst:merchant-id:dishes:upgrade:result".replace("merchant-id", TenantContextHolder.getTenantId().toString());
            RedisUtil.setString(resultRedisKey, JSONUtil.toJsonStr(dishesImportCheckResult), 60L);
        } catch (Exception var24) {
            this.stringRedisTemplate.delete(dishesLockRedisKey);
            log.error("导入异常: ", var24);
        } finally {
            this.stringRedisTemplate.delete(dishesLockRedisKey);
        }

    }
    public ImportDishesContext getImportDishesContext(String username) {
        ImportDishesContext importDishesContext = new ImportDishesContext();
        Map<String, Long> materialMap = this.menuMaterialService.list(Wrappers.lambdaQuery(MenuMaterial.class)
                .select(MenuMaterial::getMaterialId, MenuMaterial::getMaterialName)
                .eq(MenuMaterial::getDelFlag, DelFlagEnum.DEL_FALSE.key())).stream()
                .collect(Collectors.toMap(MenuMaterial::getMaterialName, MenuMaterial::getMaterialId, (x, y) -> {
            return x;
        }));
        Long defaultTypeId = this.menuDishesTypeService.getDefaultTypeId();
        Map<String, AllocArea> areaMap = this.allocAreaService.list(Wrappers.lambdaQuery(AllocArea.class)
                .eq(AllocArea::getIfDel, DelFlagEnum.DEL_FALSE.key())).stream()
                .collect(Collectors.toMap(AllocArea::getAreaName, Function.identity(), (k1, k2) -> {
            return k1;
        }));
        Map<String, AllocCanteen> canteenMap = this.allocCanteenApi.listAllCanteen(null).stream().collect(Collectors.toMap(AllocCanteen::getCanteenName, Function.identity()));
        Map<String, AllocStall> stallMap =this.allocStallService.list(Wrappers.lambdaQuery(AllocStall.class).eq(AllocStall::getIfDel, DelFlagEnum.DEL_FALSE.key())).stream().collect(Collectors.toMap(AllocStall::getStallName, Function.identity(), (k1, k2) -> {
            return k1;
        }));
        Map<String, Long> typeMap = this.menuDishesTypeMapper.selectAllListByWrapper(Wrappers.lambdaQuery(MenuDishesType.class).eq(MenuDishesType::getDelFlag, DelFlagEnum.DEL_FALSE.key())).stream().collect(Collectors.toMap(MenuDishesTypeAllVO::getTypeName, MenuDishesTypeAllVO::getTypeId));
        Map<String, Long> dishesCookMap = this.menuDishesCookService.list(Wrappers.lambdaQuery(MenuDishesCook.class)
                .select(MenuDishesCook::getCookId, MenuDishesCook::getCookName)
                .eq(MenuDishesCook::getDelFlag, DelFlagEnum.DEL_FALSE.key()))
                .stream().collect(Collectors.toMap(MenuDishesCook::getCookName, MenuDishesCook::getCookId, (k1, k2) -> {
            return k1;
        }));
        importDishesContext.setAllocAreaMap(areaMap);
        importDishesContext.setAllocStallMap(stallMap);
        importDishesContext.setAllocCanteenMap(canteenMap);
        importDishesContext.setTypeMap(typeMap);
        importDishesContext.setMaterialMap(materialMap);
        importDishesContext.setDefaultTypeId(defaultTypeId);
        importDishesContext.setUsername(username);
        importDishesContext.setDishesCookMap(dishesCookMap);
        return importDishesContext;
    }
    public MenuDishesBase generateBaseAndSize(List<MenuDishesSize> dishesSizeList, String dishesName, String... sizeTypeStrArr) {
        MenuDishesBase dishesBase = new MenuDishesBase();
        Long baseDishesId = Id.next();
        dishesBase.setBaseDishesId(baseDishesId);
        dishesBase.setDishesName(dishesName);
        String[] var6 = sizeTypeStrArr;
        int var7 = sizeTypeStrArr.length;

        for(int var8 = 0; var8 < var7; ++var8) {
            String sizeTypeStr = var6[var8];
            MenuDishesSize dishesSize = new MenuDishesSize();
            dishesSize.setBaseDishesId(baseDishesId);
            dishesSize.setSizeId(Id.next());
            dishesSize.setSizeName(sizeTypeStr);
            dishesSizeList.add(dishesSize);
        }

        return dishesBase;
    }
    public MenuDishes generateDishes(MenuDishesImportDTO importDishes, ImportDishesContext importDishesContext) {
        MenuDishes dishesAdd = new MenuDishes();
        Map<String, Long> typeMap = importDishesContext.getTypeMap();
        Map<String, Long> materialMap = importDishesContext.getMaterialMap();
        String username = importDishesContext.getUsername();
        Long defaultTypeId = importDishesContext.getDefaultTypeId();
        Map<String, Long> dishesCookMap = importDishesContext.getDishesCookMap();
        long dishesId = Id.next();
        dishesAdd.setDishesId(dishesId);
        dishesAdd.setDishesName(importDishes.getDishesName());
        String sequenceNo = this.menuSequenceService.getSequenceNo(2);
        dishesAdd.setDishesNum(sequenceNo);
        dishesAdd.setPrice(importDishes.getPrice().multiply(new BigDecimal("100")).intValue());
        dishesAdd.setSalesMode(importDishes.getSalesMode());
        dishesAdd.setCookId((Long)dishesCookMap.get(importDishes.getCookName()));
        dishesAdd.setCustomId(this.menuCustomDictService.getNoRepeatCustomId(0));
        dishesAdd.setTypeId((Long)Optional.ofNullable((Long)typeMap.get(importDishes.getDishesTypeName())).orElse(defaultTypeId));
        dishesAdd.setPinyinInitials(PinyinUtil.getFirstLetterFromChinese(importDishes.getDishesName()));
        dishesAdd.setPinyinFull(PinyinUtil.convertChineseToPinyin(importDishes.getDishesName()));
        Integer unitPrice = (Integer)Optional.ofNullable(importDishes.getUnitPrice()).orElse(100);
        dishesAdd.setUnitPrice(unitPrice);
        this.setAllocData(importDishes, dishesAdd, importDishesContext);
        if (MenuSalesTypeEnum.PORTION_ON.key().equals(importDishes.getSalesMode())) {
            Long sizeType = (Long)Optional.ofNullable(importDishes.getSizeType()).orElse(1L);
            if (sizeType == 2L) {
                dishesAdd.setLargePrice(importDishes.getLargePrice().multiply(new BigDecimal("100")).intValue());
                dishesAdd.setLittlePrice(importDishes.getLittlePrice().multiply(new BigDecimal("100")).intValue());
                dishesAdd.setLargeWeight(importDishes.getLargeWeight());
                dishesAdd.setLittleWeight(importDishes.getLittleWeight());
            }

            dishesAdd.setSizeType(sizeType);
        }

        String menuMaterialNames = importDishes.getMenuMaterialNames();
        Double importDishesWeight = importDishes.getWeight();
        Double totalWeight = 0.0;
        if (CharSequenceUtil.isNotBlank(menuMaterialNames)) {
            ArrayList<MenuMaterialDishes> menuMaterialDishesList = Lists.newArrayList();
            String[] menuMaterials = menuMaterialNames.split(";");
            String[] var18 = menuMaterials;
            int var19 = menuMaterials.length;

            for(int var20 = 0; var20 < var19; ++var20) {
                String menuMaterial = var18[var20];
                String[] materialSplit = menuMaterial.split("&");
                String materialName = materialSplit[0];
                String materialType = materialSplit[1];
                String materialWeight = materialSplit[2];
                BigDecimal weight = new BigDecimal(materialWeight);
                Long materialId = (Long)materialMap.get(materialName);
                MenuMaterialDishes menuMaterialDishes = new MenuMaterialDishes();
                menuMaterialDishes.setMaterialType(Integer.valueOf(materialType));
                menuMaterialDishes.setMaterialId(materialId);
                menuMaterialDishes.setWeight(Double.valueOf(materialWeight));
                menuMaterialDishes.setDishesId(dishesId);
                menuMaterialDishes.setCrby(username);
                menuMaterialDishesList.add(menuMaterialDishes);
                totalWeight = totalWeight + weight.doubleValue();
            }

            this.menuMaterialDishesMapper.insertBatch(menuMaterialDishesList);
            List<NutritionEntity> nutritionEntityList = this.menuNutritionService.selectNutritionWeightList(dishesId);
            if (CollUtil.isNotEmpty(nutritionEntityList)) {
                NutritionEntity nutritionEntity = NutritionEntityUtil.countNutrition(nutritionEntityList);
                BeanUtils.copyProperties(nutritionEntity, dishesAdd);
            }
        }

        if (ObjectUtil.isNotNull(importDishesWeight) && MenuSalesTypeEnum.PORTION_ON.key().equals(importDishes.getSalesMode())) {
            totalWeight = importDishesWeight;
        }

        dishesAdd.setWeight(totalWeight);
        return dishesAdd;
    }
    public void setAllocData(MenuDishesImportDTO importDishes, MenuDishes dishesAdd, ImportDishesContext importDishesContext) {
        Long stallId = -1L;
        Long canteenId = -1L;
        Long areaId = -1L;
        Map<String, Long> stallMap = importDishesContext.getStallMap();
        Map<Long, Long> canteenStallMap = importDishesContext.getCanteenStallMap();
        Map<Long, Long> areaCanteenMap = importDishesContext.getAreaCanteenMap();
        Map<String, Long> canteenMap = importDishesContext.getCanteenMap();
        Map<String, AllocArea> allocAreaMap = importDishesContext.getAllocAreaMap();
        if (ObjectUtil.isNotEmpty(importDishes.getStallName())) {
            stallId = (Long)stallMap.get(importDishes.getStallName());
            canteenId = (Long)canteenStallMap.get(stallId);
            areaId = (Long)areaCanteenMap.get(canteenId);
        } else if (ObjectUtil.isNotEmpty(importDishes.getCanteenName())) {
            canteenId = (Long)canteenMap.get(importDishes.getCanteenName());
            areaId = (Long)areaCanteenMap.get(canteenId);
        } else if (ObjectUtil.isNotEmpty(importDishes.getAreaName())) {
            areaId = ((AllocArea)allocAreaMap.get(importDishes.getAreaName())).getAreaId();
        }

        dishesAdd.setCanteenId(canteenId);
        dishesAdd.setAreaId(areaId);
        dishesAdd.setShopstallId(stallId);
    }

    @Override
    public DishesImportCheckResult importDishesCheck(MultipartFile excel) {
        List<MenuDishesImportDTO> menuDishesImportDTOS = null;
        DishesImportCheckResult dishesImportCheckResult = new DishesImportCheckResult();

        try {
            menuDishesImportDTOS = EasyExcelUtil.readSingleExcel(excel, new MenuDishesImportDTO(), 1);
        } catch (Exception var42) {
            log.info("导入新增菜品错误", var42);
            throw new ServiceException("导入新增菜品错误");
        }

        log.info("导入新增菜品检验->数据集合{}", menuDishesImportDTOS.size());
        if (CollectionUtils.isEmpty(menuDishesImportDTOS)) {
            throw new ServiceException("导入新增菜品为空");
        } else {
            List<String> sqlDishesNameList = this.menuDishesMapper.selectDishesNameAndCanteenName();
            ImportDishesContext importDishesContext = this.getImportDishesContext(null);
            Map<String, Long> areaMap = importDishesContext.getAreaMap();
            Map<String, Long> dishesCookMap = importDishesContext.getDishesCookMap();
            Map<String, Long> typeMap = importDishesContext.getTypeMap();
            Map<String, AllocStall> allocStallMap = importDishesContext.getAllocStallMap();
            Map<String, AllocCanteen> allocCanteenMap = importDishesContext.getAllocCanteenMap();
            Map<Long, AllocArea> allocAreaIdMap = importDishesContext.getAllocAreaIdMap();
            Map<Long, AllocCanteen> allocCanteenIdMap = importDishesContext.getAllocCanteenIdMap();
            Map<String, Long> materialMap = importDishesContext.getMaterialMap();
            List<Integer> salesModeKeyList = Arrays.stream(MenuSalesTypeEnum.values()).map(MenuSalesTypeEnum::key).collect(Collectors.toList());
            List<String> menuMaterialTypeList = Arrays.stream(MenuMaterialTypeEnum.values()).map(MenuMaterialTypeEnum::key).map(Object::toString).collect(Collectors.toList());
            List<String> dishesNameList = Lists.newArrayList();
            List<MenuDishesImportDTO> successList = new ArrayList<>();
            List<MenuDishesImportDTO> errorList = new ArrayList<>();
            Iterator var19 = menuDishesImportDTOS.iterator();

            while(var19.hasNext()) {
                MenuDishesImportDTO data = (MenuDishesImportDTO)var19.next();

                try {
                    BigDecimal price = data.getPrice();
                    if (BigDecimal.ZERO.compareTo(price) > 0) {
                        data.setFailReason("菜品价格为负数");
                        errorList.add(data);
                    } else {
                        Integer salesMode = data.getSalesMode();
                        if (!salesModeKeyList.contains(salesMode)) {
                            data.setFailReason("计价方式只能填写1或者2");
                            errorList.add(data);
                        } else {
                            String dishesTypeName = data.getDishesTypeName();
                            if (CharSequenceUtil.isNotBlank(dishesTypeName) && typeMap.get(dishesTypeName) == null) {
                                data.setFailReason(dishesTypeName + "菜品类别不存在");
                                errorList.add(data);
                            } else {
                                Long notNormSizeType = 2L;
                                if (MenuSalesTypeEnum.PORTION_ON.key().equals(salesMode) && notNormSizeType.equals(data.getSizeType())) {
                                    BigDecimal largePrice = data.getLargePrice();
                                    BigDecimal littlePrice = data.getLittlePrice();
                                    Double largeWeight = data.getLargeWeight();
                                    Double littleWeight = data.getLittleWeight();
                                    if (ObjectUtil.hasNull(new Object[]{largePrice, littlePrice, largeWeight, littleWeight})) {
                                        data.setFailReason("大小份菜品需要录入大份单价、小份单价、大份份量、小份份量");
                                        errorList.add(data);
                                        continue;
                                    }
                                }

                                String dishesName = data.getDishesName();
                                String canteenName = data.getCanteenName();
                                String stallName = data.getStallName();
                                String areaName = data.getAreaName();
                                String itemDishesName = Stream.of(data.getDishesName(), areaName, canteenName, stallName).map((x) -> {
                                    return CharSequenceUtil.isBlank(x) ? "*" : x;
                                }).collect(Collectors.joining("-"));
                                if (CharSequenceUtil.isBlank(dishesName)) {
                                    data.setFailReason("菜品名称为空");
                                    errorList.add(data);
                                } else if (dishesNameList.contains(itemDishesName)) {
                                    data.setFailReason("菜品名称重复");
                                    errorList.add(data);
                                } else if (CollUtil.isNotEmpty(sqlDishesNameList) && sqlDishesNameList.contains(itemDishesName)) {
                                    data.setFailReason("菜品名称数据库已存在");
                                    errorList.add(data);
                                } else {
                                    String menuMaterialNames = data.getMenuMaterialNames();
                                    BigDecimal totalWeight = BigDecimal.ZERO;
                                    if (CharSequenceUtil.isNotBlank(menuMaterialNames)) {
                                        String[] materialList = menuMaterialNames.replace("；", ";").split(";");
                                        String[] var33 = materialList;
                                        int var34 = materialList.length;

                                        for(int var35 = 0; var35 < var34; ++var35) {
                                            String material = var33[var35];
                                            String[] materialSplit = material.split("&");
                                            if (materialSplit.length != 3) {
                                                data.setFailReason(material + "原料格式不正确");
                                                errorList.add(data);
                                                break;
                                            }

                                            String materialName = materialSplit[0];
                                            String materialType = materialSplit[1];
                                            String materialWeight = materialSplit[2];
                                            if (materialMap.get(materialName) == null) {
                                                data.setFailReason(materialName + "原料不存在");
                                                errorList.add(data);
                                                break;
                                            }

                                            if (!menuMaterialTypeList.contains(materialType)) {
                                                data.setFailReason(materialType + "原料类型填写错误");
                                                errorList.add(data);
                                                break;
                                            }

                                            if (!NumberUtil.isNumber(materialWeight)) {
                                                data.setFailReason(materialWeight + "原料重量不是数字");
                                                errorList.add(data);
                                                break;
                                            }

                                            BigDecimal weight = new BigDecimal(materialWeight);
                                            totalWeight = totalWeight.add(weight);
                                            if (BigDecimal.ZERO.compareTo(weight) > 0) {
                                                data.setFailReason(materialWeight + "原料重量为负数");
                                                errorList.add(data);
                                            }
                                        }

                                        if (ObjectUtil.isNotEmpty(data.getFailReason())) {
                                            continue;
                                        }
                                    }

                                    if (ObjectUtil.isNotEmpty(data.getCookName()) && dishesCookMap.get(data.getCookName()) == null) {
                                        data.setFailReason(data.getCookName() + "灶类不存在!");
                                        errorList.add(data);
                                    } else if (ObjectUtil.isNotNull(data.getUnitPrice()) && data.getUnitPrice() != 50 && data.getUnitPrice() != 100) {
                                        data.setFailReason("称重单位仅支持输入50或者100");
                                        errorList.add(data);
                                    } else {
                                        Long areaId;
                                        if (ObjectUtil.isNotEmpty(stallName)) {
                                            AllocStall allocStall = allocStallMap.get(stallName);
                                            if (allocStall == null) {
                                                data.setFailReason("档口名称不存在");
                                                errorList.add(data);
                                                continue;
                                            }

                                            if (ObjectUtil.isEmpty(canteenName)) {
                                                data.setFailReason("食堂名称不能为空");
                                                errorList.add(data);
                                                continue;
                                            }

                                            areaId = allocStall.getCanteenId();
                                            AllocCanteen allocCanteen = allocCanteenIdMap.get(areaId);
                                            if (!allocCanteen.getCanteenName().equals(canteenName)) {
                                                data.setFailReason("食堂：" + canteenName + "填写错误");
                                                errorList.add(data);
                                                continue;
                                            }
                                        }

                                        if (ObjectUtil.isNotEmpty(canteenName)) {
                                            AllocCanteen allocCanteen = allocCanteenMap.get(canteenName);
                                            if (allocCanteen == null) {
                                                data.setFailReason("食堂名称不存在");
                                                errorList.add(data);
                                                continue;
                                            }

                                            if (ObjectUtil.isEmpty(areaName)) {
                                                data.setFailReason("区域名称不能为空");
                                                errorList.add(data);
                                                continue;
                                            }

                                            areaId = allocCanteen.getAreaId();
                                            AllocArea allocArea = allocAreaIdMap.get(areaId);
                                            if (!allocArea.getAreaName().equals(areaName)) {
                                                data.setFailReason("区域：" + allocArea.getAreaName() + "填写错误");
                                                errorList.add(data);
                                                continue;
                                            }
                                        }

                                        if (ObjectUtil.isNotEmpty(areaName) && !areaMap.containsKey(areaName)) {
                                            data.setFailReason("区域名称不存在");
                                            errorList.add(data);
                                        } else {
                                            dishesNameList.add(itemDishesName);
                                            successList.add(data);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception var43) {
                    data.setFailReason(var43.getMessage());
                    errorList.add(data);
                }
            }

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

    @Override
    public Integer getDishesMaterialCost(List<MenuMaterialCostDTO> content) {
        List<DishesMaterialCostModel> priceList =
                this.drpServiceApi.listDishesMaterialCost(content.stream().map(MenuMaterialCostDTO::getMaterialId).collect(Collectors.toList()));
        log.info("获取到的原料单价详情priceList: {}", JSON.toJSONString(priceList));
        if (CollUtil.isEmpty(priceList)) {
            return 0;
        } else {
            Map<Long, BigDecimal> priceMap = priceList.stream().collect(Collectors.toMap(DishesMaterialCostModel::getMaterialId, DishesMaterialCostModel::getCostPrice));
            BigDecimal result = BigDecimal.ZERO;

            BigDecimal materialPrice;
            for(Iterator var5 = content.iterator(); var5.hasNext(); result = result.add(materialPrice)) {
                MenuMaterialCostDTO material = (MenuMaterialCostDTO)var5.next();
                BigDecimal unitPrice = Optional.ofNullable(priceMap.get(material.getMaterialId())).orElse(BigDecimal.ZERO);
                materialPrice = material.getWeight().multiply(unitPrice);
            }

            return result.setScale(0, RoundingMode.HALF_UP).intValue();
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void autoUpdateDishesMaterialCost() {
        List<MenuDishes> dishesList = this.list(Wrappers.lambdaQuery(MenuDishes.class)
                .eq(MenuDishes::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
        if (!CollUtil.isEmpty(dishesList)) {
            List<Long> dishesIdList = dishesList.stream().map(MenuDishes::getDishesId).collect(Collectors.toList());
            List<MenuMaterialDishes> materialDishesList = this.menuMaterialDishesService.list(Wrappers.lambdaQuery(MenuMaterialDishes.class)
                    .eq(MenuMaterialDishes::getDelFlag, DelFlagEnum.DEL_FALSE.key())
                    .in(MenuMaterialDishes::getDishesId, dishesIdList));
            if (CollUtil.isEmpty(materialDishesList)) {
                this.updateDishesCostZero(dishesList);
            } else {
                List<Long> materialIdList = materialDishesList.stream().map(MenuMaterialDishes::getMaterialId).collect(Collectors.toList());
                List<DishesMaterialCostModel> priceList = this.drpServiceApi.listDishesMaterialCost(materialIdList);
                log.info("获取到的原料单价详情priceList: {}", JSON.toJSONString(priceList));
                if (CollUtil.isEmpty(materialIdList)) {
                    this.updateDishesCostZero(dishesList);
                } else {
                    Map<Long, List<MenuMaterialDishes>> materialDishesMap = materialDishesList.stream().collect(Collectors.groupingBy(MenuMaterialDishes::getDishesId));
                    Map<Long, BigDecimal> priceMap = priceList.stream().collect(Collectors.toMap(DishesMaterialCostModel::getMaterialId, DishesMaterialCostModel::getCostPrice));
                    List<MenuDishes> updateList = new ArrayList<>();

                    MenuDishes updateDishes;
                    for(Iterator var9 = dishesList.iterator(); var9.hasNext(); updateList.add(updateDishes)) {
                        MenuDishes dishes = (MenuDishes)var9.next();
                        List<MenuMaterialDishes> materialList = materialDishesMap.get(dishes.getDishesId());
                        BigDecimal materialCost = BigDecimal.ZERO;
                        BigDecimal materialPrice;
                        if (CollUtil.isNotEmpty(materialList)) {
                            for(Iterator var13 = materialList.iterator(); var13.hasNext(); materialCost = materialCost.add(materialPrice)) {
                                MenuMaterialDishes material = (MenuMaterialDishes)var13.next();
                                BigDecimal unitPrice = Optional.ofNullable(priceMap.get(material.getMaterialId())).orElse(BigDecimal.ZERO);
                                materialPrice = BigDecimal.valueOf(material.getWeight()).multiply(unitPrice).setScale(0, RoundingMode.HALF_UP);
                            }
                        }

                        BigDecimal price = BigDecimal.valueOf(Optional.ofNullable(dishes.getPrice()).orElse(0));
                        BigDecimal grossProfit = price.subtract(materialCost);
                        updateDishes = new MenuDishes();
                        updateDishes.setId(dishes.getId());
                        updateDishes.setMaterialCost(materialCost.intValue());
                        updateDishes.setGrossProfit(grossProfit.intValue());
                        if (!BigDecimal.ZERO.equals(price)) {
                            materialPrice = grossProfit.divide(price, 2, RoundingMode.HALF_UP);
                            updateDishes.setGrossProfitRate(materialPrice);
                        }
                    }
                    super.updateBatchById(updateList);
                    List<MenuDishes> collect = updateList.stream().filter((x) -> {
                        return ObjectUtil.isNull(x.getGrossProfitRate());
                    }).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(collect)) {
                        collect.forEach((c) -> {
                            this.update(Wrappers.lambdaUpdate(MenuDishes.class).eq(MenuDishes::getId, c.getId())
                                    .set(MenuDishes::getGrossProfitRate, null));
                        });
                    }
                }
            }
        }
    }
    @Transactional
    public void updateDishesCostZero(List<MenuDishes> dishesList) {
        List<MenuDishes> updateDishesList = new ArrayList();
        dishesList.forEach((dishes) -> {
            MenuDishes updateDishes = new MenuDishes();
            updateDishes.setId(dishes.getId());
            updateDishes.setMaterialCost(0);
            updateDishes.setGrossProfit(dishes.getPrice());
            updateDishes.setGrossProfitRate(BigDecimal.ONE);
            updateDishesList.add(updateDishes);
        });
        super.updateBatchById(updateDishesList);
    }


    @Override
    public Boolean uploadBatchDishes(MultipartFile[] files) {
        if (ObjectUtil.isEmpty(files)) {
            throw new ServiceException("上传文件不能为空");
        } else {
            String dishesLockRedisKey = "yst:merchant-id:dishes:pic:batch:lock".replace("merchant-id", TenantContextHolder.getTenantId().toString());
            String asyncState = this.stringRedisTemplate.opsForValue().get(dishesLockRedisKey);
            if (StringUtils.isNotBlank(asyncState)) {
                throw new ServiceException("导入图片进行中,不要重复操作哦 ^_^");
            } else {
                List<SyncMultipartFileDto> collect = Arrays.stream(files).map(SyncMultipartFileDto::new).collect(Collectors.toList());
                this.asyncTaskExecutor.execute(() -> {
                    ArrayList results = new ArrayList<>();
                    boolean var26 = false;

                    String resultRedisKey;
                    label161: {
                        try {
                            var26 = true;
                            Iterator var4 = collect.iterator();

                            while(var4.hasNext()) {
                                SyncMultipartFileDto file = (SyncMultipartFileDto)var4.next();
                                UploadDishesPicResult uploadDishesPicResult = new UploadDishesPicResult();

                                try {
                                    String name = file.getFileName();
                                    uploadDishesPicResult.setFineName(name);
                                    if (StringUtils.isBlank(name)) {
                                        uploadDishesPicResult.setSuccess(false);
                                        uploadDishesPicResult.setErrorMsg("文件名为空");
                                        results.add(uploadDishesPicResult);
                                        continue;
                                    }

                                    String[] split = name.split("_");
                                    if (split.length != 2) {
                                        uploadDishesPicResult.setSuccess(false);
                                        uploadDishesPicResult.setErrorMsg("文件名格式不正确");
                                        results.add(uploadDishesPicResult);
                                        continue;
                                    }

                                    String disheNum = split[0];
                                    String disheName = split[1].split("\\.")[0];
                                    boolean exists = this.menuDishesMapper.exists(Wrappers.lambdaQuery(MenuDishes.class)
                                            .eq(MenuDishes::getDelFlag, LeConstants.COMMON_NO)
                                            .eq(MenuDishes::getDishesNum, disheNum)
                                            .eq(MenuDishes::getDishesName, disheName));
                                    if (exists) {
                                        String var10000 = IdUtil.simpleUUID();
                                        String newFileName = var10000 + "." + FileUtil.extName(name);
                                        Long var34 = TenantContextHolder.getTenantId();
                                        String objectName = "" + var34 + "/" + FileUploadSourceEnum.CUST.key() + "/" + newFileName;
                                        String bucketName = this.ossProperties.getBucketName();

                                        try {
                                            InputStream inputStream = file.getInputStream();

                                            try {
                                                this.ossTemplate.putObject(bucketName, objectName, inputStream);
                                                String dishesImage = "/" + bucketName + "/" + objectName;
                                                this.menuDishesMapper.update(null, Wrappers.lambdaUpdate(MenuDishes.class).eq(MenuDishes::getDelFlag, LeConstants.COMMON_NO)
                                                        .eq(MenuDishes::getDishesNum, disheNum).eq(MenuDishes::getDishesName, disheName)
                                                        .set(MenuDishes::getImageUrl, dishesImage));
                                                uploadDishesPicResult.setSuccess(true);
                                            } catch (Throwable var28) {
                                                if (inputStream != null) {
                                                    try {
                                                        inputStream.close();
                                                    } catch (Throwable var27) {
                                                        var28.addSuppressed(var27);
                                                    }
                                                }

                                                throw var28;
                                            }

                                            if (inputStream != null) {
                                                inputStream.close();
                                            }
                                        } catch (Exception var29) {
                                            uploadDishesPicResult.setSuccess(false);
                                            uploadDishesPicResult.setErrorMsg(var29.getMessage());
                                        }
                                    } else {
                                        uploadDishesPicResult.setSuccess(false);
                                        uploadDishesPicResult.setErrorMsg("菜品不存在");
                                    }
                                } catch (Exception var30) {
                                    log.error("上传菜品图片失败", var30);
                                    uploadDishesPicResult.setSuccess(false);
                                    uploadDishesPicResult.setErrorMsg(var30.getMessage());
                                }

                                results.add(uploadDishesPicResult);
                            }

                            var26 = false;
                            break label161;
                        } catch (Exception var31) {
                            log.error("上传菜品图片失败", var31);
                            var26 = false;
                        } finally {
                            if (var26) {
                                String var19 = "yst:merchant-id:dishes:pic:batch:result".replace("merchant-id", TenantContextHolder.getTenantId().toString());
                                RedisUtil.setString(var19, JSONUtil.toJsonStr(results), 60L);
                                this.stringRedisTemplate.delete(dishesLockRedisKey);
                            }
                        }

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

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

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void replaceMaterialDishes(ReplaceMaterialDto content) {
        List<Long> baseDishesIds = content.getBaseDishesIds();
        if (!ObjectUtil.isEmpty(baseDishesIds)) {
            List<MenuDishes> menuDishes = this.list(Wrappers.lambdaQuery(MenuDishes.class).select(MenuDishes::getDishesId, MenuDishes::getId)
                    .in(MenuDishes::getBaseDishesId, baseDishesIds)
                    .eq(MenuDishes::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
            if (!CollUtil.isEmpty(menuDishes)) {
                List<Long> dishesIds = menuDishes.stream().map(MenuDishes::getDishesId).collect(Collectors.toList());
                List<MenuUpdateDishesModel> menuUpdateDishesModels = BeanUtil.copyToList(menuDishes, MenuUpdateDishesModel.class);
                this.menuMaterialDishesService.update(Wrappers.lambdaUpdate(MenuMaterialDishes.class)
                        .in(MenuMaterialDishes::getDishesId, dishesIds)
                        .eq(MenuMaterialDishes::getMaterialId, content.getOldMaterialId())
                        .set(MenuMaterialDishes::getMaterialId, content.getNewMaterialId()));
                this.updateNutrition(menuUpdateDishesModels);
            }
        }
    }

    @Override
    public List<MenuDishesExportVO> exportMenuDishes(MenuDishesExportDTO content) {
        MenuMetadataModel menuMetadataModel = this.allocMetadataApi.queryMetadataModel(MetadataModelTypeEnum.MENU, new MenuMetadataModel());
        String ifDifCanteenManage = menuMetadataModel.getIfDifCanteenManage();
        MgrUserAuthPO authPO = this.mgrAuthApi.getUserAuthPO();
        PageHelper.startPage(content);
        return this.baseMapper.selectDishesExportList(content, "1".equals(ifDifCanteenManage), authPO);
    }

    public void checkParam(MenuDishesV2AddDTO content) {
        MenuMetadataModel menuMetadataModel = this.allocMetadataApi.queryMetadataModel(MetadataModelTypeEnum.MENU, new MenuMetadataModel());
        String ifDifCanteenManage = menuMetadataModel.getIfDifCanteenManage();
        if ("1".equals(ifDifCanteenManage) && ObjectUtil.isNull(content.getCanteenId())) {
            throw new ServiceException(I18n.getMessage("menu_canteen_null", new Object[0]));
        } else {
            Integer dishesNameExist = this.menuDishesBaseMapper.selectExistName(content.getDishesName(), content.getCanteenId());
            if (ObjectUtil.isNotNull(dishesNameExist)) {
                throw new ServiceException(I18n.getMessage("menu_dishes_name_repeat", new Object[0]));
            } else {
                if (CharSequenceUtil.isNotBlank(content.getDishesNum())) {
                    Integer dishesNumExist = this.menuDishesBaseMapper.selectExistNum(content.getDishesNum(), content.getCanteenId());
                    if (ObjectUtil.isNotNull(dishesNumExist)) {
                        throw new ServiceException(I18n.getMessage("menu_dishes_num_repeat", new Object[0]));
                    }
                }

            }
        }
    }

    public Long insertBaseAndSize(String dishesName, String... sizeTypeStrArr) {
        MenuDishesBase dishesBase = new MenuDishesBase();
        Long baseDishesId = Id.next();
        dishesBase.setBaseDishesId(baseDishesId);
        dishesBase.setDishesName(dishesName);
        this.menuDishesBaseService.save(dishesBase);
        List<MenuDishesSize> dishesSizeList = Lists.newArrayList();
        String[] var6 = sizeTypeStrArr;
        int var7 = sizeTypeStrArr.length;

        for (int var8 = 0; var8 < var7; ++var8) {
            String sizeTypeStr = var6[var8];
            MenuDishesSize dishesSize = new MenuDishesSize();
            dishesSize.setBaseDishesId(baseDishesId);
            dishesSize.setSizeId(Id.next());
            dishesSize.setSizeName(sizeTypeStr);
            dishesSizeList.add(dishesSize);
        }
        this.menuDishesSizeService.saveBatch(dishesSizeList);
        return baseDishesId;
    }

    public Long insertMenuDishes(MenuDishesV2AddDTO content, Long baseDishesId, Integer price, Double weight, String sizeJson) {
        return this.insertMenuDishes(content, baseDishesId, price, weight, sizeJson, 1);
    }

    public Long insertMenuDishes(MenuDishesV2AddDTO content, Long baseDishesId, Integer price, Double weight, String sizeJson, Integer conver) {
        List<Long> labelIdList = content.getLabelIdList();
        List<Long> tasteIdList = content.getTasteIdList();
        List<Long> suitIdList = content.getSuitIdList();
        List<Long> seasonList = content.getSeason();
        List<Integer> mealtimeTypes = content.getMealtimeTypes();
        String username = SecurityUtils.getUsername();
        Long dishesId = Id.next();
        MenuDishes menuDishes = new MenuDishes();
        Integer mealType = content.getMealType();
        List<MenuDishesAddMaterialDTO> materialDTOList = content.getMaterialList();
        if (CharSequenceUtil.contains(sizeJson, "小份")) {
            materialDTOList = content.getLittleMaterialList();
        }

        List<MenuMaterialDishes> packageDishesList;
        if (MenuMealTypeEnum.DISHES.key().equals(mealType) && CollUtil.isNotEmpty(materialDTOList)) {
            packageDishesList = CopyListUtil.copyListProperties(materialDTOList, MenuMaterialDishes.class);
            this.insertMaterialDishesBatch(packageDishesList, dishesId, username);
            List<NutritionEntity> nutritionEntityList = this.menuNutritionService.selectNutritionWeightList(dishesId);
            if (CollUtil.isNotEmpty(nutritionEntityList)) {
                NutritionEntity nutritionEntity = NutritionEntityUtil.countNutrition(nutritionEntityList);
                BeanUtils.copyProperties(nutritionEntity, menuDishes);
            }
        }

        List<MenuPackageDishesAddDTO> newpackageDishesList = content.getPackageDishesList();
        if (MenuMealTypeEnum.PACKAGE_MEAL.key().equals(mealType) && CollUtil.isNotEmpty(newpackageDishesList)) {
            List<MenuPackageDishes> packageDishesAddList = Lists.newArrayList();
            newpackageDishesList.forEach((pd) -> {
                MenuPackageDishes packageDishes = new MenuPackageDishes();
                packageDishes.setPackageId(dishesId);
                packageDishes.setDishesId(pd.getDishesId());
                packageDishes.setProportion(pd.getProportion());
                packageDishes.setCrby(username);
                packageDishesAddList.add(packageDishes);
            });
            this.menuPackageDishesMapper.insertBatch(packageDishesAddList);
            List<NutritionEntity> nutritionEntityList = this.baseMapper.selectNutritionWeightList(dishesId);
            NutritionEntity nutritionEntity = NutritionEntityUtil.countNutrition(nutritionEntityList);
            log.info("计算完毕营养信息整合结果nutritionEntity : {}", nutritionEntity);
            BeanUtils.copyProperties(nutritionEntity, menuDishes);
        }

        if (CollUtil.isNotEmpty(labelIdList)) {
            this.insertLabelDishesBatch(labelIdList, dishesId, username);
        }

        if (CollUtil.isNotEmpty(tasteIdList)) {
            this.insertTasteDishesBatch(tasteIdList, dishesId, username);
        }

        if (CollUtil.isNotEmpty(suitIdList)) {
            this.insertSuitDishesBatch(suitIdList, dishesId, username);
        }

        if (CollUtil.isNotEmpty(seasonList)) {
            this.menuSeasonDishesService.insertBatch(seasonList, dishesId);
        }

        if (CollUtil.isNotEmpty(mealtimeTypes)) {
            this.menuMealtimeTypeDishesService.insertBatch(mealtimeTypes, dishesId);
        }

        BeanUtils.copyProperties(content, menuDishes);
        Integer customId = this.menuCustomDictService.getNoRepeatCustomId(0);
        menuDishes.setCustomId(customId);
        menuDishes.setDishesId(dishesId);
        menuDishes.setCrby(username);
        if (ObjectUtil.isNotNull(menuDishes.getSodium())) {
            if (menuDishes.getSodium() > NutritionConstants.SODIUM.doubleValue()) {
                if (menuDishes.getInitialScore() != null) {
                    menuDishes.setInitialScore(menuDishes.getInitialScore() - NutritionConstants.SCORE_TEN);
                } else {
                    menuDishes.setInitialScore(NutritionConstants.SCORE_SEVENTY);
                }
            } else {
                menuDishes.setInitialScore(NutritionConstants.SCORE_EIGHTY);
            }
        }

        Long typeId = menuDishes.getTypeId();
        if (typeId != null && typeId != -1L) {
            MenuDishesType menuDishesType = this.menuDishesTypeMapper.selectOne(Wrappers.lambdaQuery(MenuDishesType.class)
                    .eq(MenuDishesType::getTypeId, typeId).eq(MenuDishesType::getDelFlag, LeConstants.COMMON_NO));
            if (!menuDishesType.getTypeName().contains("鱼") && !menuDishesType.getTypeName().contains("半荤")) {
                if (!menuDishesType.getTypeName().contains("油脂") && !menuDishesType.getTypeName().contains("甜") && !menuDishesType.getTypeName().contains("主荤")) {
                    menuDishes.setInitialScore(NutritionConstants.SCORE_EIGHTY);
                } else {
                    menuDishes.setInitialScore(NutritionConstants.SCORE_SIXTY);
                }
            } else {
                menuDishes.setInitialScore(NutritionConstants.SCORE_SEVENTY);
            }
        } else {
            typeId = this.menuDishesTypeService.getDefaultTypeId();
            menuDishes.setTypeId(typeId);
        }

        Long cookId = menuDishes.getCookId();
        Integer initialScore;
        if (ObjectUtil.isNotNull(cookId)) {
            MenuDishesCook menuDishesCook = this.menuDishesCookMapper.selectOne(Wrappers.lambdaQuery(MenuDishesCook.class)
                    .eq(MenuDishesCook::getCookId, cookId)
                    .eq(MenuDishesCook::getDelFlag, LeConstants.COMMON_NO));
            if (ObjectUtil.isNotNull(menuDishes.getInitialScore())) {
                initialScore = menuDishes.getInitialScore();
            } else {
                initialScore = NutritionConstants.SCORE_EIGHTY;
            }

            if (menuDishesCook.getCookName().contains(MenuDishesCookEnum.SALAD.value())) {
                menuDishes.setInitialScore(initialScore + NutritionConstants.SCORE_TEN);
            } else if (!menuDishesCook.getCookName().contains(MenuDishesCookEnum.STEAM.value()) && !menuDishesCook.getCookName().contains(MenuDishesCookEnum.COOK.value()) && !menuDishesCook.getCookName().contains(MenuDishesCookEnum.STEW.value())) {
                if (!menuDishesCook.getCookName().contains(MenuDishesCookEnum.BRAISED.value()) && !menuDishesCook.getCookName().contains(MenuDishesCookEnum.DRY_STIR_FRY.value()) && !menuDishesCook.getCookName().contains(MenuDishesCookEnum.SWEET_SOUR.value())) {
                    menuDishes.setInitialScore(NutritionConstants.SCORE_EIGHTY);
                } else {
                    menuDishes.setInitialScore(initialScore - NutritionConstants.SCORE_TEN);
                }
            } else {
                menuDishes.setInitialScore(initialScore + NutritionConstants.SCORE_FIVE);
            }
        }

        menuDishes.setPinyinInitials(PinyinUtil.getFirstLetterFromChinese(menuDishes.getDishesName()));
        menuDishes.setPinyinFull(PinyinUtil.convertChineseToPinyin(menuDishes.getDishesName()));
        String sequenceNo = this.menuSequenceService.getSequenceNo(2);
        menuDishes.setDishesNum(sequenceNo);
        if (ObjectUtil.isNotNull(weight)) {
            menuDishes.setWeight(weight);
        }

        menuDishes.setPrice(price);
        initialScore = content.getMaterialCost();
        if (CharSequenceUtil.contains(sizeJson, "小份")) {
            initialScore = content.getLittleMaterialCost();
        }

        int grossProfit = price - initialScore;
        menuDishes.setMaterialCost(initialScore);
        menuDishes.setGrossProfit(grossProfit);
        if (price != 0) {
            BigDecimal grossProfitRate = BigDecimal.valueOf((long) grossProfit).divide(BigDecimal.valueOf((long) price), 2, RoundingMode.HALF_UP);
            menuDishes.setGrossProfitRate(grossProfitRate);
        }

        menuDishes.setBaseDishesId(baseDishesId);
        menuDishes.setSizeJson(sizeJson);
        menuDishes.setConvertFlag(conver);
        this.baseMapper.insert(menuDishes);
        MqUtil.sendDataChange(menuDishes, LeMqConstant.DataChangeType.ADD, LeMqConstant.Topic.DATA_CHANGE_DISHES);
        return dishesId;
    }

    public void insertMaterialDishesBatch(List<MenuMaterialDishes> materialList, Long dishesId, String username) {
        Iterator var4 = materialList.iterator();
        while (var4.hasNext()) {
            MenuMaterialDishes materialDishes = (MenuMaterialDishes) var4.next();
            materialDishes.setDishesId(dishesId);
            materialDishes.setCrby(username);
        }

        this.menuMaterialDishesMapper.insertBatch(materialList);
    }


    public void insertLabelDishesBatch(List<Long> labelIdList, Long dishesId, String username) {
        List<MenuLabelDishes> labelDishesList = new ArrayList<>();
        Iterator var5 = labelIdList.iterator();

        while (var5.hasNext()) {
            Long labelId = (Long) var5.next();
            MenuLabelDishes labelDishes = new MenuLabelDishes();
            labelDishes.setDishesId(dishesId);
            labelDishes.setLabelId(labelId);
            labelDishes.setCrby(username);
            labelDishesList.add(labelDishes);
        }

        this.menuLabelDishesMapper.insertBatch(labelDishesList);
    }

    public void insertTasteDishesBatch(List<Long> tasteIdList, Long dishesId, String username) {
        List<MenuTasteDishes> tasteDishesList = new ArrayList();
        Iterator var5 = tasteIdList.iterator();

        while (var5.hasNext()) {
            Long tasteId = (Long) var5.next();
            MenuTasteDishes tasteDishes = new MenuTasteDishes();
            tasteDishes.setDishesId(dishesId);
            tasteDishes.setTasteId(tasteId);
            tasteDishes.setCrby(username);
            tasteDishesList.add(tasteDishes);
        }

        this.menuTasteDishesMapper.insertBatch(tasteDishesList);
    }

    public void insertSuitDishesBatch(List<Long> suitIdList, Long dishesId, String username) {
        List<MenuSuitDishes> suitDishesList = new ArrayList();
        Iterator var5 = suitIdList.iterator();

        while (var5.hasNext()) {
            Long suitId = (Long) var5.next();
            MenuSuitDishes suitDishes = new MenuSuitDishes();
            suitDishes.setDishesId(dishesId);
            suitDishes.setSuitId(suitId);
            suitDishes.setCrby(username);
            suitDishesList.add(suitDishes);
        }

        this.menuSuitDishesMapper.insertBatch(suitDishesList);
    }

    @Override
    public List<MenuDishes> getByNames(Set<String> dishesNames) {
        return this.list(Wrappers.lambdaQuery(MenuDishes.class)
                .eq(MenuDishes::getDelFlag, DelFlagEnum.DEL_FALSE.key())
                .in(MenuDishes::getDishesName, dishesNames));
    }

    @Override
    public Map<Long, List<String>> selectDishesLabelByDishesIds(List<Long> dishesIds) {
        List<DishesLabelDto> dishesLabelDtos = this.baseMapper.selectDishesLabelByDishesIds(dishesIds);
        return dishesLabelDtos.stream().collect(Collectors.groupingBy(DishesLabelDto::getDishesId, Collectors.mapping(DishesLabelDto::getName, Collectors.toList())));
    }

    @Override
    public Map<String, List<String>> selectMaterialByTypeAndDishesIds(List<Long> dishesIds) {
        List<DishesLabelDto> dishesLabelDtos = this.baseMapper.selectMaterialByTypeAndDishesIds(dishesIds);
        return dishesLabelDtos.stream().collect(Collectors.groupingBy((x) -> {
            Long var10000 = x.getDishesId();
            return "" + var10000 + "_" + x.getMaterialType();
        }, Collectors.mapping(DishesLabelDto::getName, Collectors.toList())));
    }

}
