package cn.superdesk.uniorder.event.channelTrigger;


import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import cn.superdesk.uniorder.dao.entity.channel.UnifiedChannelProfitSync;
import cn.superdesk.uniorder.dao.entity.channel.UnifiedChannelProfitXVirt;
import cn.superdesk.uniorder.dao.entity.channel.UnifiedChannelProfitXVirtExample;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterprise;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterpriseExample;
import cn.superdesk.uniorder.dao.mapper.channel.UnifiedChannelProfitXVirtMapper;
import cn.superdesk.uniorder.dao.mapper.organisation.SysEnterpriseMapper;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.numerical.AnStringUtils;
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 org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 渠道分润 规则 转化为 X
 * @Author: linjinyu
 * @CreateDate: 9/10/20 3:56 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 9/10/20 3:56 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Component
public class ChannelProfitSyncCacheMappingListener {


	@Autowired
	private UnifiedChannelProfitXVirtMapper unifiedChannelProfitXVirtMapper;
	@Autowired
	private SysEnterpriseMapper             sysEnterpriseMapper;


	@Async
	@EventListener(condition = "#event.direction == 'insert'")
	public void handleInsertChannelProfitSyncCacheMappingEvent(ChannelProfitSyncCacheMappingEvent event) {

		log.info("handleInsertChannelProfitSyncCacheMappingEvent\n{}", AnJsonUtils.toJson(event));

		UnifiedChannelProfitSync unifiedChannelProfitSync = event.getUnifiedChannelProfitSync();

		searchAndCleanUnifiedChannelProfitXVirtBychannelIdAndbusinessCode(unifiedChannelProfitSync.getChannelId(), unifiedChannelProfitSync.getBusinessCode());

		handleMergeUnifiedChannelProfitXVirt(event);
	}

	@Async
	@EventListener(condition = "#event.direction == 'update'")
	public void handleUpdateChannelProfitSyncCacheMappingEvent(ChannelProfitSyncCacheMappingEvent event) {

		log.info("handleUpdateChannelProfitSyncCacheMappingEvent\n{}", AnJsonUtils.toJson(event));

		UnifiedChannelProfitSync unifiedChannelProfitSync = event.getUnifiedChannelProfitSync();

		searchAndCleanUnifiedChannelProfitXVirtBychannelIdAndbusinessCode(unifiedChannelProfitSync.getChannelId(), unifiedChannelProfitSync.getBusinessCode());

		handleMergeUnifiedChannelProfitXVirt(event);
	}

	/**
	 * 删除的这个算是已经处理完了
	 *
	 * @param event
	 */
	@Async
	@EventListener(condition = "#event.direction == 'delete'")
	public void handleDeleteChannelProfitSyncCacheMappingEvent(ChannelProfitSyncCacheMappingEvent event) {

		log.info("handleDeleteChannelProfitSyncCacheMappingEvent\n{}", AnJsonUtils.toJson(event));

		UnifiedChannelProfitSync unifiedChannelProfitSync = event.getUnifiedChannelProfitSync();

		searchAndCleanUnifiedChannelProfitXVirtBychannelIdAndbusinessCode(unifiedChannelProfitSync.getChannelId(), unifiedChannelProfitSync.getBusinessCode());

	}


	/**
	 * @param event
	 */
	public void handleMergeUnifiedChannelProfitXVirt(ChannelProfitSyncCacheMappingEvent event) {

		List<SysEnterprise> sysEnterpriseList = null;

		UnifiedChannelProfitSync unifiedChannelProfitSync = event.getUnifiedChannelProfitSync();

		// 处理指定为企业
		if (unifiedChannelProfitSync.getIsBindVirt().equals(1)) {

			if (StringUtils.isNoneBlank(unifiedChannelProfitSync.getVirtIds())) {

				// 这个是传过来的东西 为什么 有以下的操作 是因为不信任 它有的东西我这边不一定有
//				String[] virtIdArr = event.getVirtIds().split(";");

				List<Long> searchVirtIds = AnStringUtils.stringArrayConvertToLongList(unifiedChannelProfitSync.getVirtIds(), ";");

				SysEnterpriseExample example = new SysEnterpriseExample();
				example.createCriteria().andEnterpriseIdIn(searchVirtIds);

				sysEnterpriseList = sysEnterpriseMapper.selectByExample(example);
			}

		}
		// 处理指定为项目
		else {
			SysEnterpriseExample example = new SysEnterpriseExample();
			example.createCriteria().andOrganizationIdEqualTo(unifiedChannelProfitSync.getOrganizationId());

			// 唉,这里是怎么回事,怎么没有 selectByExample , 转去 整改这个表 , 好了
			sysEnterpriseList = sysEnterpriseMapper.selectByExample(example);
		}

		if (AnCollectionUtils.isNotEmpty(sysEnterpriseList)) {
			handleReGenerateUnifiedChannelProfitXVirt(sysEnterpriseList, event);
		}
	}


	/**
	 * TODO 目前 一个个插吧 赶时间
	 *
	 * @param sysEnterpriseList
	 * @param event
	 */
	@Transactional(rollbackFor = Exception.class)
	public void handleReGenerateUnifiedChannelProfitXVirt(List<SysEnterprise> sysEnterpriseList, ChannelProfitSyncCacheMappingEvent event) {

		UnifiedChannelProfitSync unifiedChannelProfitSync = event.getUnifiedChannelProfitSync();

		sysEnterpriseList.forEach(item -> {

			UnifiedChannelProfitXVirt temp = new UnifiedChannelProfitXVirt();

			temp.setChannelId(unifiedChannelProfitSync.getChannelId());
			temp.setVirtId(item.getEnterpriseId());
			temp.setBusinessCode(unifiedChannelProfitSync.getBusinessCode());
			temp.setProportion(unifiedChannelProfitSync.getProportion());
			temp.setBegindate(unifiedChannelProfitSync.getBeginDate().getTime());
			temp.setEnddate(unifiedChannelProfitSync.getEndDate().getTime());

			unifiedChannelProfitXVirtMapper.insert(temp);

		});

	}


	/**
	 * 搜索与清除
	 *
	 * @param channelId
	 * @param businessCode
	 */
	private void searchAndCleanUnifiedChannelProfitXVirtBychannelIdAndbusinessCode(Long channelId, String businessCode) {

		UnifiedChannelProfitXVirtExample example = new UnifiedChannelProfitXVirtExample();
		example.createCriteria()
				.andChannelIdEqualTo(channelId)
//				.andBusinessCodeEqualTo(businessCode)
		;

		List<UnifiedChannelProfitXVirt> handleUnifiedChannelProfitXVirtList = null;

		try {

			handleUnifiedChannelProfitXVirtList = unifiedChannelProfitXVirtMapper.selectByExample(example);

			batchDeleteUnifiedChannelProfitXVirt(handleUnifiedChannelProfitXVirtList);

		} catch (Exception e) {
			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}

	}


	@Transactional(rollbackFor = Exception.class)
	public void batchDeleteUnifiedChannelProfitXVirt(List<UnifiedChannelProfitXVirt> handleUnifiedChannelProfitXVirtList) {

		if (AnCollectionUtils.isNotEmpty(handleUnifiedChannelProfitXVirtList)) {
			handleUnifiedChannelProfitXVirtList.forEach(item -> {
				unifiedChannelProfitXVirtMapper.deleteByPrimaryKey(item.getId());
			});
		}
	}
}
