package com.yc.ship.module.marketing.api.policy;

import com.yc.ship.module.marketing.dal.dataobject.policydetail.PolicyDetailDO;
import com.yc.ship.module.marketing.dal.mysql.policydetail.PolicyDetailMapper;
import org.springframework.stereotype.Service;

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

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yc.ship.module.marketing.enums.ErrorCodeConstants.*;

@Service
public class PolicyApiImpl implements PolicyApi{

    @Resource
    private PolicyDetailMapper policyDetailMapper;
    @Override
    public void updatePolicySurplusNum(Long policyId, Long voyageId, BigDecimal num) {
        PolicyDetailDO policyDetailDO = policyDetailMapper.selectByPolicyIdAndVoyageId(policyId, voyageId);
        if(policyDetailDO == null) {
            throw exception(POLICY_NOT_EXISTS);
        }
        if(policyDetailDO.getSurplusNum().compareTo(num) < 0) {
            throw exception(POLICY_OVER_NUM);
        }
        policyDetailDO.setSurplusNum(policyDetailDO.getSurplusNum().subtract(num));
        policyDetailMapper.updateById(policyDetailDO);
    }

    @Override
    public Boolean checkPolicySurplusNum(Long policyId, Long voyageId, BigDecimal num) {
        PolicyDetailDO policyDetailDO = policyDetailMapper.selectByPolicyIdAndVoyageId(policyId, voyageId);
        if(policyDetailDO == null) {
            return false;
        }
        if(policyDetailDO.getSurplusNum().compareTo(num) < 0) {
            return false;
        }
        return true;
    }
}
