package com.neusoft.smart.pos.trade.service;


import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.framework.utils.DateUtils;
import com.neusoft.smart.pos.framework.utils.ListUtils;
import com.neusoft.smart.pos.order.persistent.domain.OrderMaster;
import com.neusoft.smart.pos.payorder.persistent.domain.PayOrder;
import com.neusoft.smart.pos.payorder.service.PayOrderService;
import com.neusoft.smart.pos.trade.persistent.domain.BillSettlementRuleDetail;
import com.neusoft.smart.pos.trade.persistent.ext.domain.BillProfitExt;
import com.neusoft.smart.pos.trade.persistent.ext.domain.BillProfitExt.BillProfitDetailExt;

import lombok.val;

import com.neusoft.smart.pos.trade.persistent.ext.domain.BillSettlementRuleDetailExt;
import com.neusoft.smart.pos.trade.persistent.ext.domain.BillSettlementRuleExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("commonBillRuleService")
public class CommonBillRuleService implements IBillRuleService {

	private final static Logger logger = LoggerFactory.getLogger(CommonBillRuleService.class);
	
	@Autowired
    private PayOrderService payOrderService;
	
	/**
	 * 规则执行方法
	 * @return
	 */
	public BillProfitExt executeRule(String billNumber,BillSettlementRuleExt billSettlementRuleExt, OrderMaster orderMaster){
		BillProfitExt billProfitExt = null;
		List<BillProfitDetailExt> billProfitDetails = new ArrayList<>();
		//1.判断当前订单是否满足此规则
		if(!StringUtils.isEmpty(billSettlementRuleExt.getRateStartTime())){
			Date startTime = DateUtils.getDayStartTime(DateUtils.parse(billSettlementRuleExt.getRateStartTime(),DateUtils.FORMAT_SHORT));
			Date endTime = DateUtils.getDayEndTime(DateUtils.parse(billSettlementRuleExt.getRateEndTime(),DateUtils.FORMAT_SHORT));
			if(!DateUtils.between(orderMaster.getCreatedAt(),startTime,endTime)){
				return  billProfitExt;
			}
		}
		
		//2.根据orderNumber获得payOrder
        List<PayOrder> payOrderList = payOrderService.queryPayOrderList(orderMaster.getOrderNumber());
        
		//3.整理返回数据
		billProfitExt = new BillProfitExt();
		BigDecimal profitAmount = BigDecimal.ZERO;
		BigDecimal profitRate = BigDecimal.ZERO;
		//迭代支付单列表
		for (val payOrder : payOrderList) {
            if (payOrder != null) {
                if (DictionaryConstant.PAY_STATUS_YFK.getCode().equals(payOrder.getPayStatus())) {
                	//迭代结算分成规则列表
					for(int i=0;i<billSettlementRuleExt.getBillSettlementRuleDetailExtList().size();i++){
						if(profitAmount.doubleValue()==orderMaster.getRealPayAmount().doubleValue()){
							break;
						}
						BillSettlementRuleDetailExt billSettlementRuleDetailExt = billSettlementRuleExt.getBillSettlementRuleDetailExtList().get(i);
						//判断支付方式是否满足，如果支付方式为空表示不限制支付方式			
	                	if(StringUtils.isEmpty(billSettlementRuleDetailExt.getPayType()) || billSettlementRuleDetailExt.getPayType().equals(payOrder.getPayType())){
	        				BillProfitDetailExt billProfitDetailExt = new BillProfitDetailExt();
	        				billProfitDetailExt.setOrgId(orderMaster.getOrgId());
	        				billProfitDetailExt.setShopId(orderMaster.getShopId());
	        				billProfitDetailExt.setBillNumber(billNumber);
	        				billProfitDetailExt.setOrderNumber(orderMaster.getOrderNumber());
	        				billProfitDetailExt.setSubjectType(billSettlementRuleDetailExt.getSubjectType());
	        				billProfitDetailExt.setSubjectId(billSettlementRuleDetailExt.getSubjectId());
	        				billProfitDetailExt.setSubjectName(billSettlementRuleDetailExt.getSubjectName());
	        				billProfitDetailExt.setPayType(payOrder.getPayType());
	        				billProfitDetailExt.setProfitRate(billSettlementRuleDetailExt.getRate());
	        				profitRate = profitRate.add(billSettlementRuleDetailExt.getRate());
	        				//处理精度问题，处理当遇到小数大于2位时分润金额合计不等于总金额问题
	        				if(profitRate.intValue() == 100){
	        					billProfitDetailExt.setProfitAmount(new BigDecimal(payOrder.getPayAmount()).divide(new BigDecimal(100)).subtract(profitAmount));
	        					billProfitDetails.add(billProfitDetailExt);
	        					break;
	        				}else{
	        					billProfitDetailExt.setProfitAmount(calculationBillProfit(billProfitDetailExt.getProfitRate(), new BigDecimal(payOrder.getPayAmount()).divide(new BigDecimal(100))));
	        					profitAmount = profitAmount.add(billProfitDetailExt.getProfitAmount()); //追加分润金额
	        					billProfitDetails.add(billProfitDetailExt);
	        				}
	        			}	               
	                } 
	            }
	        }			
		}
		if(billProfitDetails.size() == 0){
			billProfitExt = null;
		}else{
			billProfitExt.setBillProfitDetails(billProfitDetails);
		}
		return billProfitExt;
	}
	
	/**
	 * 计算账单分润金额
	 */
	private BigDecimal calculationBillProfit(BigDecimal billRate,BigDecimal realPayAmount){
		BigDecimal rate = billRate.divide(BigDecimal.valueOf(100));
		return realPayAmount.multiply(rate).setScale(2,BigDecimal.ROUND_DOWN);
	}

}
