package cn.iocoder.yudao.module.system.service.dishes;

import cn.hutool.core.util.NumberUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.dishes.vo.DishesPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.dishes.vo.DishesSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.dishes.DishesDO;
import cn.iocoder.yudao.module.system.dal.mysql.dishes.DishesMapper;
import cn.iocoder.yudao.module.system.enums.ErrorCodeConstants;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 菜品管理 Service 实现类
 *
 * @author 开发账号
 */
@Service
@Validated
public class DishesServiceImpl implements DishesService {

    @Resource
    private DishesMapper dishesMapper;
    @Override
    @SneakyThrows
    public Long createDishes(DishesSaveReqVO createReqVO) {
        // 插入
        DishesDO dishes = BeanUtils.toBean(createReqVO, DishesDO.class);
        dishes.setDeleted(Boolean.FALSE);
        //计算每g多少钱
        BigDecimal dishesSumPrice = createReqVO.getDishesSumPrice();
        BigDecimal dishesNumber = createReqVO.getDishesNumber();
        BigDecimal div = NumberUtil.div(dishesSumPrice, dishesNumber, 2);
        //避免计算出每克价格约 为0
        if(div.floatValue() <= 0.00f){
            dishes.setDishesBasePrice(new BigDecimal("0.01"));
        }else{
            dishes.setDishesBasePrice(div);
        }
        dishesMapper.insert(dishes);
        // 返回
        return dishes.getId();
    }
    @Override
    @SneakyThrows
    public void updateDishes(DishesSaveReqVO updateReqVO) {
        // 校验存在
        validateDishesExists(updateReqVO.getId());
//        //把图片转换为base64
//        String img = Base64.getEncoder().encodeToString(updateReqVO.getFile().getBytes());
        // 更新
        DishesDO updateObj = BeanUtils.toBean(updateReqVO, DishesDO.class);
//        updateObj.setDishesImageUrl(img);
        dishesMapper.updateById(updateObj);

    }

    @Override
    public void deleteDishes(Long id) {
        // 校验存在
        validateDishesExists(id);
        // 删除
        dishesMapper.deleteById(id);
    }

    private void validateDishesExists(Long id) {
        if (dishesMapper.selectById(id) == null) {
            throw exception(ErrorCodeConstants.DISHES_NOT_EXISTS);
        }
    }

    @Override
    public DishesDO getDishes(Long id) {
        return dishesMapper.selectById(id);
    }

    @Override
    public PageResult<DishesDO> getDishesPage(DishesPageReqVO pageReqVO) {
        return dishesMapper.selectPage(pageReqVO);
    }

}