package com.tzy.listener.mq;

import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.tzy.app.domain.order.OrderListDTO;
import com.tzy.app.mapper.OrderListMapper;
import com.tzy.common.constant.Constants;
import com.tzy.common.constant.MqConstans;
import com.tzy.common.dto.act.OrderOverParam;
import com.tzy.common.utils.bean.JSONTools;
import com.tzy.sportcard.api.service.MineApiService;
import com.tzy.sportcard.group.domain.CardGroupOrderInfo;
import com.tzy.sportcard.group.mapper.CardGroupOrderInfoMapper;
import com.tzy.sportcard.point.domain.AppUserPointRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;


/**
 * 订单完结消费
 * 消费者参数json格式：
 * type:类型,1:商城订单完结赠送积分 shop_point
 * orderId: 订单id
 */
@Slf4j
@Component
public class OrderOverConsumer {

	@Resource
	private MineApiService mineApiService;
	@Resource
	private OrderListMapper orderListMapper;
	@Resource
	private CardGroupOrderInfoMapper cardGroupOrderInfoMapper;

	@RabbitHandler
	@RabbitListener(queues = {MqConstans.QUEUE_ORDER_OVER})
	public void orderOverConsumer(String param, Channel channel, Message message) throws IOException {
		log.info("订单完结记录:{}", param);
		try {
			OrderOverParam overParam = JSONTools.jsonStr2obj(param, OrderOverParam.class);
			if(Constants.TYPE_SHOP_POINT.equals(overParam.getType())){
				CardGroupOrderInfo order = cardGroupOrderInfoMapper.selectCardGroupOrderInfoById(overParam.getOrderId());
				addOrderActPoint(order); // 加活动积分
				addPointRecord(order, channel, message);// 商城积分、成长值
			}
		} catch (Exception e) {
			log.error("订单完结异常,参数:{}", param, e);
		}
		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
	}

	private void addOrderActPoint(CardGroupOrderInfo order) {
		List<OrderListDTO> actOrderLists = orderListMapper.selectListByOrderId(order.getId(),true);
		if (CollectionUtils.isEmpty(actOrderLists)) {
			return;
		}

		String actType = actOrderLists.get(0).getActType();
		if (!actType.startsWith(Constants.POINT_TYPE_HB_ACT_OVER_PRE)) {
			return;
		}
		Integer totalActPoint = actOrderLists.stream().filter(ol -> ol.getActPoint() != null).mapToInt(OrderListDTO::getActPoint).sum();
		AppUserPointRecord pointRecord = mineApiService.buildOrderActPointRecord(order, totalActPoint, actType);
		mineApiService.addUserPoint(pointRecord);
	}

	private void addPointRecord(CardGroupOrderInfo order, Channel channel, Message message) throws IOException {
		if(13 != order.getMerchantId() || order.getGiveOrderId() != null) {	// 不是YYDS商家 或者是精美卡片不赠送成长值
			return;
		}
		BigDecimal refundFree = order.getRefundFee() == null ? BigDecimal.ZERO : order.getRefundFee();
		BigDecimal amount=order.getActualPayment().subtract(refundFree);
		if (amount.compareTo(BigDecimal.ZERO) != 1) {
			return;
		}
		/*if(Constants.GROUP_SALE_MERCHANT_IDS.contains(orderInfos.getMerchantId())) { // 排除生态购商家
			return;
		}*/
		Integer points = (amount.multiply(new BigDecimal(100))).intValue();
		order.setPoint(points);
		mineApiService.addUserPoint(order, true, Constants.POINT_TYPE_USER_GROWTH);
		mineApiService.addUserPoint(order, true, Constants.POINT_TYPE_GOODS);
		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
	}

}
