package cn.superdesk.uniorder.event.channelTrigger;

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.enums.channel.UnifiedChannelSyncCompanyTypeEnum;
import cn.superdesk.uniorder.common.enums.common.CommonSoftDeleteEnum;
import cn.superdesk.uniorder.common.enums.common.CommonSourceFromEnum;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import cn.superdesk.uniorder.common.queue.delayed.DelayTaskAsync;
import cn.superdesk.uniorder.common.queue.delayed.instance.DelayTaskInstanceRoleExtData;
import cn.superdesk.uniorder.dao.entity.channel.UnifiedChannelSync;
import cn.superdesk.uniorder.dao.entity.sys.SysUser;
import cn.superdesk.uniorder.dao.entity.sys.SysUserExample;
import cn.superdesk.uniorder.dao.entity.sys.role.SysRoleExtData;
import cn.superdesk.uniorder.dao.entity.sys.role.SysRoleExtDataExample;
import cn.superdesk.uniorder.dao.mapper.sys.SysUserMapper;
import cn.superdesk.uniorder.dao.mapper.sys.role.SysRoleExtDataMapper;
import cn.superdesk.uniorder.queue.delayed.DelayQueueHandler;
import lombok.extern.slf4j.Slf4j;
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/1/20 5:30 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 9/1/20 5:30 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Component
public class ChannelSyncCreateSysRoleExtDataListener {

	@Autowired
	private SysUserMapper        sysUserMapper;
	@Autowired
	private SysRoleExtDataMapper sysRoleExtDataMapper;
	@Resource
	private DelayQueueHandler    delayQueueHandler;

	/**
	 * @param unifiedChannelSync
	 * @return
	 */
	private SysRoleExtData checkIsExistAndGetSysRoleExtData(UnifiedChannelSync unifiedChannelSync) {

		SysRoleExtDataExample example = new SysRoleExtDataExample();
		example.createCriteria()
				.andSourceFromEqualTo(CommonSourceFromEnum.服务之窗.getSourceFromCode())
				.andSourceFromQuoteIdEqualTo(unifiedChannelSync.getChannelId());
		List<SysRoleExtData> result = sysRoleExtDataMapper.selectByExample(example);

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

	/**
	 * @param unifiedChannelSync
	 */
	private void mergeSysRoleExtData(UnifiedChannelSync unifiedChannelSync) {

		SysRoleExtData sysRoleExtData = checkIsExistAndGetSysRoleExtData(unifiedChannelSync);

		if (null == sysRoleExtData) {

			sysRoleExtData = new SysRoleExtData();

			convertUnifiedChannelSync2SysRoleExtData(unifiedChannelSync, sysRoleExtData);

			sysRoleExtData.setCreateTime(DateUtil.date());
			sysRoleExtData.setCreateUserId(1L);
			sysRoleExtDataMapper.insertSelective(sysRoleExtData);
		} else {

			convertUnifiedChannelSync2SysRoleExtData(unifiedChannelSync, sysRoleExtData);

			sysRoleExtData.setUpdateTime(DateUtil.date());
			sysRoleExtData.setUpdateUserId(1L);
			sysRoleExtDataMapper.updateByPrimaryKey(sysRoleExtData);
		}

		/****************************************** 反向挂载 数据权限 start ******************************************/
		SysUserExample updateSysUserExample = new SysUserExample();
		updateSysUserExample.createCriteria()
				.andSourceFromQuoteIdEqualTo(sysRoleExtData.getSourceFromQuoteId());

		SysUser sysUser4Update = new SysUser();
		sysUser4Update.setSysRoleExtDataId(sysRoleExtData.getId());

		sysUserMapper.updateByExampleSelective(sysUser4Update, updateSysUserExample);
		/****************************************** 反向挂载 数据权限 start ******************************************/


		// TODO 挂载数据
//		delayQueueHandler.remove(sysRoleExtData.getSourceFromQuoteId() + "");
//		delayQueueHandler.put(new DelayTaskAsync(new DelayTaskInstanceRoleExtData(sysRoleExtData.getSourceFromQuoteId() + ""), 60000));
		delayQueueHandler.put(new DelayTaskAsync(
				DelayTaskInstanceRoleExtData.builder()
						.identifier(sysRoleExtData.getSourceFromQuoteId() + "")
						.build(),
				60000));
	}

	/**
	 * 转换
	 *
	 * @param unifiedChannelSync
	 * @param sysRoleExtData
	 */
	private void convertUnifiedChannelSync2SysRoleExtData(UnifiedChannelSync unifiedChannelSync, SysRoleExtData sysRoleExtData) {

		// 不填 默认为 全部业务流线?
		sysRoleExtData.setServiceNoMult("");
		sysRoleExtData.setServiceNameMult("");

		// 未 判定 数据权限主体
		sysRoleExtData.setSysRoleExtSampleIds("");

		sysRoleExtData.setSourceFrom(CommonSourceFromEnum.服务之窗.getSourceFromCode());
		sysRoleExtData.setSourceFromQuoteId(unifiedChannelSync.getChannelId());

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

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

		sysRoleExtData.setEnabled(unifiedChannelSync.getEnabled() == null ? 1 : unifiedChannelSync.getEnabled());

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


	}

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

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

		mergeSysRoleExtData(event.getUnifiedChannelSync());
	}

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

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

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

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

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