package cn.pluss.platform.postageConfig.impl;

import cn.pluss.platform.entity.PostageConfig;
import cn.pluss.platform.entity.UserAddress;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.PostageConfigMapper;
import cn.pluss.platform.postageConfig.PostageConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * <p>
 * 邮费信息配置表 服务实现类
 * </p>
 *
 * @author crystal
 * @since 2022-03-29
 */
@Service
public class PostageConfigServiceImpl extends ServiceImpl<PostageConfigMapper, PostageConfig> implements PostageConfigService {

    /**
     * 根据地址和总量获取商品邮费
     * @param address
     * @param weight
     * @return
     */
    @Override
    public BigDecimal getGoodPostageInfo(UserAddress address, BigDecimal weight) {
        MsgException.checkNull(weight,"重量信息异常");
        BigDecimal postage = BigDecimal.ZERO;
        //省
        String areaCode = address.getAreaCode().split("-")[0];
        PostageConfig config = baseMapper.getPostageByArea(areaCode,PostageConfig.STATUS_YES);
        if(config == null){
            return postage;
        }
        postage = postage.add(config.getFirstWeight());
        if(weight.compareTo(PostageConfig.WEIGHT_UNIT) <= 0){
            return postage;
        }else{
            weight = weight.subtract(PostageConfig.WEIGHT_UNIT);
            //向上取整
            Integer nextW = weight.setScale( 0, BigDecimal.ROUND_UP).intValue();
            BigDecimal nextPostage = config.getNextWeight().multiply(BigDecimal.valueOf(nextW));
            postage = postage.add(nextPostage).setScale(2,BigDecimal.ROUND_HALF_UP);
        }
        return postage;
    }
}
