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

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.bonus.canteen.core.menu.domain.MapBean;
import com.bonus.canteen.core.menu.domain.MenuDishesRelation;
import com.bonus.canteen.core.menu.dto.MenuDishesAddMaterialDTO;
import com.bonus.canteen.core.menu.dto.MenuDishesDTO;
import com.bonus.canteen.core.menu.service.IMenuDishesService;
import com.bonus.canteen.core.utils.Arith;
import com.bonus.canteen.core.utils.NutritionEntity;
import com.bonus.canteen.core.utils.NutritionEntityUtil;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.houqin.utils.id.Id;
import com.bonus.common.security.utils.SecurityUtils;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bonus.canteen.core.menu.mapper.MenuDishesMapper;
import com.bonus.canteen.core.menu.domain.MenuDishes;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import javax.validation.constraints.Size;

/**
 * 菜品信息Service业务层处理
 *
 * @author xsheng
 * @date 2025-04-03
 */
@Service
public class MenuDishesServiceImpl implements IMenuDishesService {
    @Autowired
    private MenuDishesMapper menuDishesMapper;

    /**
     * 查询菜品信息
     *
     * @param id 菜品信息主键
     * @return 菜品信息
     */
    @Override
    public MenuDishes selectMenuDishesById(Long id) {
        return menuDishesMapper.selectMenuDishesById(id);
    }

    /**
     * 查询菜品信息列表
     *
     * @param menuDishes 菜品信息
     * @return 菜品信息
     */
    @Override
    public List<MenuDishes> selectMenuDishesList(MenuDishes menuDishes) {
        return menuDishesMapper.selectMenuDishesList(menuDishes);
    }

    /**
     * 新增菜品信息
     *
     * @param menuDishes 菜品信息
     * @return 结果
     */
    @Override
    public int insertMenuDishes(MenuDishes menuDishes) {
        menuDishes.setCreateTime(DateUtils.getNowDate());
        try {
            return menuDishesMapper.insertMenuDishes(menuDishes);
        } catch (Exception e) {
            throw new ServiceException("错误信息描述");
        }
    }

    /**
     * 修改菜品信息
     *
     * @param menuDishes 菜品信息
     * @return 结果
     */
    @Override
    public int updateMenuDishes(MenuDishes menuDishes) {
        menuDishes.setUpdateTime(DateUtils.getNowDate());
        try {
            return menuDishesMapper.updateMenuDishes(menuDishes);
        } catch (Exception e) {
            throw new ServiceException("错误信息描述");
        }
    }

    /**
     * 批量删除菜品信息
     *
     * @param ids 需要删除的菜品信息主键
     * @return 结果
     */
    @Override
    public int deleteMenuDishesByIds(Long[] ids) {
        return menuDishesMapper.deleteMenuDishesByIds(ids);
    }

    /**
     * 删除菜品信息信息
     *
     * @param id 菜品信息主键
     * @return 结果
     */
    @Override
    public int deleteMenuDishesById(Long id) {
        return menuDishesMapper.deleteMenuDishesById(id);
    }

    @Override
    public List<MapBean> getDishesType(MapBean mapBean) {
        return menuDishesMapper.getDishesType(mapBean);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addMenuDishes(MenuDishesDTO menuDishesDTO) {
        //检查菜品是否已存在
        MenuDishes menuDishesOne = menuDishesMapper.getOne(menuDishesDTO);
        if(menuDishesOne !=null){
            throw new ServiceException("菜品已存在");
        }
        Long dishesId = Id.next();
        Long baseDishesId = Id.next();
        menuDishesDTO.setCrby(SecurityUtils.getUserId()+"");
        //添加基础主表信息
        menuDishesDTO.setBaseDishesId(baseDishesId+"");
        menuDishesDTO.setDishesId(dishesId+"");
        menuDishesDTO.setCustomId(-1);
       int baseNum =  menuDishesMapper.addMenuDishesBase(menuDishesDTO);
       //添加主要信息
        int dishesNum =  menuDishesMapper.addMenuDishes(menuDishesDTO);

        //添加菜品关联信息
        //标签
        List<Integer> labelIdList = menuDishesDTO.getLabelIdList();
        for (Integer i: labelIdList) {
            MenuDishesRelation menuDishesRelation = new MenuDishesRelation();
            menuDishesRelation.setKeyWordId(i);
            menuDishesRelation.setCrby(SecurityUtils.getUserId());
            menuDishesRelation.setDishesId(dishesId);
            menuDishesMapper.adddishesLabel(menuDishesRelation);
        }
        //口味
        List<Integer> tasteIdList = menuDishesDTO.getTasteIdList();
        for (Integer i: tasteIdList) {
            MenuDishesRelation menuDishesRelation = new MenuDishesRelation();
            menuDishesRelation.setKeyWordId(i);
            menuDishesRelation.setCrby(SecurityUtils.getUserId());
            menuDishesRelation.setDishesId(dishesId);
            menuDishesMapper.adddishesTaste(menuDishesRelation);
        }
        //季节分类
        List<Integer> seasonList = menuDishesDTO.getSeason();
        for (Integer i: tasteIdList) {
            MenuDishesRelation menuDishesRelation = new MenuDishesRelation();
            menuDishesRelation.setKeyWordId(i);
            menuDishesRelation.setCrby(SecurityUtils.getUserId());
            menuDishesRelation.setDishesId(dishesId);
            menuDishesMapper.adddishesSeason(menuDishesRelation);
        }
        //适宜人群
        List<Integer> suitIdList = menuDishesDTO.getSuitIdList();
        for (Integer i: suitIdList) {
            MenuDishesRelation menuDishesRelation = new MenuDishesRelation();
            menuDishesRelation.setKeyWordId(i);
            menuDishesRelation.setCrby(SecurityUtils.getUserId());
            menuDishesRelation.setDishesId(dishesId);
            menuDishesMapper.adddishesSuit(menuDishesRelation);
        }
        //餐次
        List<Integer> mealList= menuDishesDTO.getMealList();
        for (Integer i: mealList) {
            MenuDishesRelation menuDishesRelation = new MenuDishesRelation();
            menuDishesRelation.setKeyWordId(i);
            menuDishesRelation.setCrby(SecurityUtils.getUserId());
            menuDishesRelation.setDishesId(dishesId);
            menuDishesMapper.adddishesMeal(menuDishesRelation);
        }

        List<MenuDishesAddMaterialDTO> materialList= menuDishesDTO.getMaterialList();
        List<NutritionEntity> nutritionEntityList = new ArrayList<>();
        System.err.println("长度："+materialList.size());
        for (MenuDishesAddMaterialDTO i: materialList) {
            NutritionEntity nutritionEntity = menuDishesMapper.getNutritionEntity(i);
            System.err.println(i.getMaterialId()+",开始值："+nutritionEntity.getCalcium());
            nutritionEntity.setWeight(i.getWeight());
            nutritionEntity.setBaseWeight(100.0);
            nutritionEntityList.add(nutritionEntity);
        }
        NutritionEntityUtil nutritionEntityUtil = new NutritionEntityUtil();
        NutritionEntity nutritionEntity = nutritionEntityUtil.countNutrition(nutritionEntityList);


        System.err.println("最终值："+nutritionEntity.getCalcium());
        return menuDishesMapper.addFinalNutrition(nutritionEntity);
    }


    private NutritionEntity countNum(NutritionEntity nutritionEntity,Double weight) {
        Field[] fields = nutritionEntity.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Double value = (Double) field.get(nutritionEntity);
                if(value !=null){
                    System.err.println("先前值----："+value);
                    double proportion = Arith.div(weight , 100);
                    value = Arith.mul(value, proportion);
                    field.set(nutritionEntity, value);
                    System.err.println("后来值++++："+value);
                }else{
                    field.set(nutritionEntity, 0.00);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return nutritionEntity;
    }



    //首字母转小写
    public static String toLowerCaseFirstOne(String s)
    {
        if(Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }
    //首字母转大写
    public static String toUpperCaseFirstOne(String s) {
        if (Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
    }


}
