package com.neusoft.smart.pos.strategy.repository;

import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.order.request.PostCreateOrderRequest;
import com.neusoft.smart.pos.dto.order.request.PostOrderDetailRequest;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.strategy.constants.StrategyErrorCode;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;


/**
 * 日餐税计算策略
 * 堂食： 返回值 = 菜品总金额 * 10%
 * 外卖： 返回值 = 菜品总金额 * 8%
 */
@Component("JapanCateringTaxStrategyBean")
public class JapanCateringTaxStrategyBean implements IStrategy{
    @Override
    public long doCalculate(PostCreateOrderRequest postCreateOrderRequest, String parameter) {
        if(parameter == null || parameter.isEmpty()) {
            throw new BusinessCommonException(StrategyErrorCode.PATAM_INFO_NOT_EXIST);
        }
        BigDecimal amount = new BigDecimal(0);
        if(null == postCreateOrderRequest.getOrderDetails()) {
            return 0;
        }

        for(PostOrderDetailRequest postOrderDetailRequest : postCreateOrderRequest.getOrderDetails()) {
            amount = amount.add(postOrderDetailRequest.getFinalPrice()); //金额单位：元
        }

        BigDecimal tax;
        // 解析parameter
        try {
            JSONObject param = JSONObject.fromObject(parameter);
            BigDecimal x = new BigDecimal(param.getString("x"));
            BigDecimal y = new BigDecimal(param.getString("y"));
            if(postCreateOrderRequest.getOrderSubType().equals(DictionaryConstant.ORDER_SUB_TYPE_REQ_DELIVERY_ORDER.getCode())) { // 外卖
                tax = amount.multiply(y);
            } else { // 堂食
                tax = amount.multiply(x);
            }
        } catch (Exception e) {
            throw new BusinessCommonException(StrategyErrorCode.PATAM_INFO_FORMAT);
        }
        return tax.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).longValue(); //元转为分
    }
}
