package org.springblade.payment.handle.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import org.springblade.common.cache.PlatformCache;
import org.springblade.common.config.entity.PlatformConfig;
import org.springblade.common.utils.TradeException;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.ldt.shop.entity.Shop;
import org.springblade.ldt.shop.service.IShopService;
import org.springblade.payment.handle.entity.HandleData;
import org.springblade.payment.handle.entity.Order;
import org.springblade.ldt.activity.entity.Activity;
import org.springblade.ldt.activity.entity.JoinRecord;
import org.springblade.ldt.activity.service.IActivityService;
import org.springblade.ldt.activity.service.IJoinRecordService;
import org.springblade.payment.entity.SuccessParams;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * @author: lianghanqiang
 * @description: 处理各种商家折扣
 * @since: 8/27/21 -- 2:43 PM
 */
@Component
@AllArgsConstructor
public class DiscountHandle implements BaseHandle {

	private IShopService shopService;
	private IActivityService activityService;
	private IJoinRecordService joinRecordService;

	@Override
	public HandleData handle(BigDecimal remain, Order order, SuccessParams successParams) throws TradeException {
		PlatformConfig platformConfig = PlatformCache.platFormConfig();

		//获取相关商家、活动、参与情况
		Shop shop = shopService.getById(order.getShopId());
		JoinRecord joinRecord = activityJoin(shop.getId());

		//判断商家是否参与了活动，参与活动计算相应的活动折扣
		if(!Objects.isNull(joinRecord)){
			Activity activity  = activityService.getById(joinRecord.getActivityId());

			//国信服务费
			BigDecimal serviceFee = BigDecimal.valueOf(platformConfig.getServiceFee());
			//商场活动折扣
			BigDecimal mallDiscount =  activity.getDiscount();
			//商家折扣
			BigDecimal shopDiscount = joinRecord.getDiscount();

			remain =  remain.multiply(mallDiscount)
				.multiply(shopDiscount);

			/*国信收取的服务费*/
			BigDecimal chargeFee  = remain.multiply(serviceFee);
			successParams.getBills().setFee(chargeFee);

			/*最终的交易金额*/
			remain = remain.add(serviceFee);

		}

		return HandleData.builder().successParams(successParams).remain(remain).isSuccess(Boolean.TRUE).build();
	}

	/**
	 * 	获取参与活动中，折扣最小的
	 * */
	private JoinRecord activityJoin(Long id) {
		JoinRecord joinRecord = joinRecordService.getOne(new QueryWrapper<JoinRecord>()
			.lambda()
			.eq(JoinRecord::getJoinId, id).orderByAsc(JoinRecord::getDiscount)
			.last("limit 1"));
		return joinRecord;
	}
}
