package cn.superdesk.uniorder.event.channelTrigger;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import cn.superdesk.uniorder.common.enums.common.CommonSoftDeleteEnum;
import cn.superdesk.uniorder.common.enums.common.CommonSourceFromEnum;
import cn.superdesk.uniorder.common.queue.delayed.DelayTaskAsync;
import cn.superdesk.uniorder.common.queue.delayed.instance.DelayTaskInstanceRoleExtData;
import cn.superdesk.uniorder.dao.entity.channel.UnifiedChannelProfitSync;
import cn.superdesk.uniorder.dao.entity.sys.role.SysRoleExtDataSample;
import cn.superdesk.uniorder.dao.entity.sys.role.SysRoleExtDataSampleExample;
import cn.superdesk.uniorder.dao.mapper.sys.role.SysRoleExtDataSampleMapper;
import cn.superdesk.uniorder.queue.delayed.DelayQueueHandler;
import cn.superdesk.uniorder.service.organisation.SysEnterpriseService;
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 javax.annotation.Resource;
import java.util.List;

/**
 * @Description: kafka 同步 运营商 渠道商 同时产生 数据权限许可
 * @Author: linjinyu
 * @CreateDate: 9/10/20 3:53 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 9/10/20 3:53 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Component
public class ChannelProfitSyncCreateSysRoleExtDataSampleListener {

	@Autowired
	private SysRoleExtDataSampleMapper sysRoleExtDataSampleMapper;
	@Autowired
	private SysEnterpriseService       sysEnterpriseService;
	@Resource
	private DelayQueueHandler          delayQueueHandler;


	/**
	 * @param unifiedChannelProfitSync
	 * @return
	 */
	private SysRoleExtDataSample checkIsExistAndGetSysRoleExtDataSample(UnifiedChannelProfitSync unifiedChannelProfitSync) {

		SysRoleExtDataSampleExample example = new SysRoleExtDataSampleExample();
		example.createCriteria()
				.andSourceFromEqualTo(CommonSourceFromEnum.服务之窗.getSourceFromCode())
				.andSourceFromQuoteIdEqualTo(unifiedChannelProfitSync.getSyncId());// 对方的自增Id
		List<SysRoleExtDataSample> result = sysRoleExtDataSampleMapper.selectByExample(example);

		if (CollUtil.isEmpty(result)) {
			return null;
		} else {
			return result.get(0);
		}
	}

	/**
	 * @param unifiedChannelSync
	 */
	private void mergeSysRoleExtDataSample(UnifiedChannelProfitSync unifiedChannelSync) {

		SysRoleExtDataSample sysRoleExtDataSample = checkIsExistAndGetSysRoleExtDataSample(unifiedChannelSync);

		if (null == sysRoleExtDataSample) {

			sysRoleExtDataSample = new SysRoleExtDataSample();
			convertUnifiedChannelProfitSync2SysRoleExtDataSample(unifiedChannelSync, sysRoleExtDataSample);

			sysRoleExtDataSample.setCreateTime(DateUtil.date());
			sysRoleExtDataSample.setCreateUserId(1L);
			sysRoleExtDataSampleMapper.insertSelective(sysRoleExtDataSample);

		} else {

			convertUnifiedChannelProfitSync2SysRoleExtDataSample(unifiedChannelSync, sysRoleExtDataSample);
			sysRoleExtDataSample.setUpdateTime(DateUtil.date());
			sysRoleExtDataSample.setUpdateUserId(1L);
			sysRoleExtDataSampleMapper.updateByPrimaryKey(sysRoleExtDataSample);
		}

		// 延时队列 原生实现
		// TODO 挂载数据
//		delayQueueHandler.remove(sysRoleExtDataSample.getSourceFromQuoteParentId() + "");
//		delayQueueHandler.put(new DelayTaskAsync(new DelayTaskInstanceRoleExtData(sysRoleExtDataSample.getSourceFromQuoteParentId() + ""), 60000));
		delayQueueHandler.put(new DelayTaskAsync(
				DelayTaskInstanceRoleExtData.builder()
						.identifier(sysRoleExtDataSample.getSourceFromQuoteId() + "")
						.build(),
				60000));
	}

	/**
	 * 转换
	 *
	 * @param unifiedChannelSync
	 * @param sysRoleExtDataSample
	 */
	private void convertUnifiedChannelProfitSync2SysRoleExtDataSample(UnifiedChannelProfitSync unifiedChannelSync, SysRoleExtDataSample sysRoleExtDataSample) {

		// 不填 默认为 全部业务流线?
		sysRoleExtDataSample.setServiceNo(unifiedChannelSync.getBusinessCode());
		sysRoleExtDataSample.setServiceName("");

		sysRoleExtDataSample.setSourceFrom(CommonSourceFromEnum.服务之窗.getSourceFromCode());

		sysRoleExtDataSample.setSourceFromQuoteId(unifiedChannelSync.getSyncId());
		sysRoleExtDataSample.setSourceFromQuoteParentId(unifiedChannelSync.getChannelId());

//		sysRoleExtData.setPermitStartTime();
//		sysRoleExtData.setPermitEndTime();

//		sysRoleExtDataSample.setName(UnifiedChannelProfitSyncCompanyTypeEnum.getDesc(unifiedChannelSync.getCompanyType()) + "_" + unifiedChannelSync.getChannelName());
//		sysRoleExtDataSample.setRemark(String.format("系统同步,来源于 code %s | name %s", SysRoleExtDataSampleSourceFromEnum.服务之窗.getSourceFromCode(), SysRoleExtDataSampleSourceFromEnum.服务之窗.getSourceFromName()));

		// 如果是 要填充 setOutVirtIds setSysVirtIds
		sysRoleExtDataSample.setIsBindVirt(unifiedChannelSync.getIsBindVirt());

		sysRoleExtDataSample.setOutOrgId(unifiedChannelSync.getOrganizationId());
		sysRoleExtDataSample.setOutVirtIds(unifiedChannelSync.getVirtIds());

//		sysRoleExtDataSample.setSysOrgId();
//		sysRoleExtDataSample.setSysVirtIds();

		// 当不是 绑定企业 也就是 项目时 修正数据
		if (sysRoleExtDataSample.getIsBindVirt().equals(0)) {

			List<Long> outVirtIds = sysEnterpriseService.getOutVirtIdsByOutOrgId(sysRoleExtDataSample.getOutOrgId());
			// List 转 逗号
			sysRoleExtDataSample.setOutVirtIds(StringUtils.join(outVirtIds.toArray(), ","));

		}
		// 当是 绑定企业 也就是 修正数据 ; 改 ,
		if (sysRoleExtDataSample.getIsBindVirt().equals(1)) {
			sysRoleExtDataSample.setOutVirtIds(unifiedChannelSync.getVirtIds().replace(";", ","));
		}


		// 软删除 默认为 0
		sysRoleExtDataSample.setDeleted(CommonSoftDeleteEnum.正常.getKey());


	}

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

		log.info("handleInsertChannelProfitSyncCreateSysRoleExtDataSampleEvent\n{}", JSONUtil.toJsonStr(event));

		mergeSysRoleExtDataSample(event.getUnifiedChannelProfitSync());
	}

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

		log.info("handleUpdateChannelProfitSyncCreateSysRoleExtDataSampleEvent\n{}", JSONUtil.toJsonStr(event));

		// 渠道商 运营商 数据 转换 成 数据权限角色
		mergeSysRoleExtDataSample(event.getUnifiedChannelProfitSync());
	}

	@Async
	@EventListener(condition = "#event.direction == 'delete'")
	public void handleDeleteChannelProfitSyncCreateSysRoleExtDataSampleEvent(ChannelProfitSyncCreateSysRoleExtDataSampleEvent event) {

		log.info("handleDeleteChannelProfitSyncCreateSysRoleExtDataSampleEvent\n{}", JSONUtil.toJsonStr(event));
	}
}
