package cn.superdesk.uniorder.event.orderTrigger;

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.enums.common.CommonServiceNoEnum;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderReturn;
import cn.superdesk.uniorder.dao.entity.channel.UnifiedChannelProfitXVirt;
import cn.superdesk.uniorder.dao.entity.channel.UnifiedChannelProfitXVirtExample;
import cn.superdesk.uniorder.dao.entity.unified.UnifiedOrderProfit;
import cn.superdesk.uniorder.dao.mapper.channel.UnifiedChannelProfitXVirtMapper;
import cn.superdesk.uniorder.dao.mapper.unified.UnifiedOrderProfitMapper;
import cn.superdesk.uniorder.dao.mapper.unified.UnifiedOrderProfitMapperEx;
import cn.superdesk.uniorder.service.organisation.SysSupplierService;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

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


/**
 * @Description: 渠道商分润 计算
 * @Author: linjinyu
 * @CreateDate: 5/28/20 7:45 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 5/28/20 7:45 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Component
public class UnifiedOrderProfitCalculationListener {


	@Autowired
	private UnifiedOrderProfitMapper        unifiedOrderProfitMapper;
	@Autowired
	private UnifiedOrderProfitMapperEx      unifiedOrderProfitMapperEx;
	@Autowired
	private UnifiedChannelProfitXVirtMapper unifiedChannelProfitXVirtMapper;

	@Autowired
	private SysSupplierService unifiedSupplierService;


	private List<UnifiedChannelProfitXVirt> matchingUnifiedChannelProfitXVirt(Long virtId, String businessCode) {

		List<UnifiedChannelProfitXVirt> unifiedChannelProfitXVirtList = null;

//		select
//			id, channel_id, virt_id, business_code, proportion, beginDate, endDate
//		from
//			unified_channel_profit_x_virt
//		WHERE ( virt_id = 4136 and business_code = 'FLSC' and beginDate <= 1590676867058 and endDate >= 1590676867058 )

		UnifiedChannelProfitXVirtExample example = new UnifiedChannelProfitXVirtExample();
		example.createCriteria()
				.andVirtIdEqualTo(virtId)
				.andBusinessCodeEqualTo(businessCode)
				.andBegindateLessThanOrEqualTo(System.currentTimeMillis())
				.andEnddateGreaterThanOrEqualTo(System.currentTimeMillis());


		unifiedChannelProfitXVirtList = unifiedChannelProfitXVirtMapper.selectByExample(example);

		return unifiedChannelProfitXVirtList;

	}

	/**
	 * 处理 订单 计算分润
	 * <p>
	 * -- 企业采购
	 * -- 福利内购
	 * -- 楼闪送 大概是排除在外 因为不是走 kafka
	 *
	 * @param event
	 */
	@Async
	@EventListener
	public void handleProfitOrderCalculationEvent(UnifiedOrderProfitCalculationEvent event) {

		UnifiedOrder unifiedOrder = event.getUnifiedOrder();

		List<UnifiedChannelProfitXVirt> unifiedChannelProfitXVirtList = matchingUnifiedChannelProfitXVirt(unifiedOrder.getPurchaseVirtId(), unifiedOrder.getServiceNo());

		if (AnCollectionUtils.isNotEmpty(unifiedChannelProfitXVirtList)) {


			// 处理可能会有多个渠道商都符合这个分润
			unifiedChannelProfitXVirtList.forEach(unifiedChannelProfitXVirt -> {
				// 插入分润表

				UnifiedOrderProfit unifiedOrderProfit = new UnifiedOrderProfit();

				unifiedOrderProfit.setChannelId(unifiedChannelProfitXVirt.getChannelId());
				unifiedOrderProfit.setOrgId(unifiedOrder.getProjectId());
				// TODO 少了个企业 + by linjinyu 20200528
				unifiedOrderProfit.setVirtId(unifiedOrder.getPurchaseVirtId());
				unifiedOrderProfit.setBusinessCode(unifiedChannelProfitXVirt.getBusinessCode());


				// 记录当时的分润比例
				unifiedOrderProfit.setProportion(unifiedChannelProfitXVirt.getProportion());
				// TODO 再冗余多个字段 unifiedChannelProfitXVirt json


				unifiedOrderProfit.setOrderSn(unifiedOrder.getOrderSn());
				unifiedOrderProfit.setProfitAmount(new BigDecimal(unifiedOrder.getAmount().doubleValue() * unifiedChannelProfitXVirt.getProportion().doubleValue() / 100));

				// TODO 加两个快照 + by linjinyu 20200528
				unifiedOrderProfit.setSnapshotOrder(AnJsonUtils.toJson(unifiedOrder));
				unifiedOrderProfit.setSnapshotProfit(AnJsonUtils.toJson(unifiedChannelProfitXVirt));

				UnifiedOrderProfit searchProfit = unifiedOrderProfitMapperEx.selectBySn(unifiedOrder.getOrderSn());

				if (searchProfit != null) {
					unifiedOrderProfit.setId(searchProfit.getId());
					// TODO 加个更新时间 + by linjinyu 20200528
					unifiedOrderProfit.setUpdateTime(DateUtil.date());
					unifiedOrderProfitMapper.updateByPrimaryKeySelective(unifiedOrderProfit);
				} else {
					unifiedOrderProfit.setCreateTime(DateUtil.date());
					unifiedOrderProfitMapper.insert(unifiedOrderProfit);
				}
			});
		}

	}


	/**
	 * 只处理代客
	 *
	 * @param event
	 */
	@Async
	@EventListener
	public void handleProxyClientOrderSupplierCheckUpEvent(ProxyClientOrderSupplierCheckUpEvent event) {

		UnifiedOrder unifiedOrder = event.getUnifiedOrder();


		if (null != unifiedOrder.getSaleId() && StringUtils.isNotBlank(unifiedOrder.getServiceNo())) {
			unifiedSupplierService.mergeUnifiedSupplier(
					unifiedOrder.getSaleId(),
					unifiedOrder.getSaleName(),
					CommonServiceNoEnum.代客下单.getServiceNo()
			);
		}


	}


	/**
	 * TODO 处理 退单 计算分润
	 *
	 * @param event
	 */
	@Async
	@EventListener
	public void handleProfitOrderReturnCalculationEvent(UnifiedOrderReturnProfitCalculationEvent event) {

		UnifiedOrderReturn unifiedOrderReturn = event.getUnifiedOrderReturn();

		// TODO 目前如果有退单,我是补过 重新核算相对映的订单,而 这个退单 导致 分润失效的问题是还没有实现的

//		List<UnifiedChannelProfitXVirt> unifiedChannelProfitXVirtList = matchingUnifiedChannelProfitXVirt(unifiedOrderReturn.getPurchaseVirtId(), unifiedOrderReturn.getServiceNo());
//
//		if (AnCollectionUtils.isNotEmpty(unifiedChannelProfitXVirtList)) {
//
//			// 处理可能会有多个渠道商都符合这个分润
//			unifiedChannelProfitXVirtList.forEach(unifiedChannelProfitXVirt -> {
//
//			});
//
//
//		}

	}


}
