package cn.superdesk.uniorder.event.organizationTrigger;

import cn.superdesk.uniorder.common.enums.common.CommonSoftDeleteEnum;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterprise;
import cn.superdesk.uniorder.dao.entity.organisation.SysOrganization;
import cn.superdesk.uniorder.service.order.base.CommonOrderProcessService;
import cn.superdesk.uniorder.service.organisation.SysEnterpriseService;
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;


/**
 * @Description: 基于 项目信息变更所带来的级联更新问题
 * @Author: linjinyu
 * @CreateDate: 2021/7/5 上午10:11
 * @UpdateUser: linjinyu
 * @UpdateDate: 2021/7/5 上午10:11
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Component
public class OrganizationListener {

	@Autowired
	private CommonOrderProcessService commonOrderProcessService;

	@Autowired
	private SysEnterpriseService sysEnterpriseService;

	@Async
	@EventListener
	public void handleOrganizationEvent(OrganizationEvent event) {

		SysOrganization sysOrganization = event.getSysOrganization();
		SysOrganization snapshot        = event.getSnapshot();

		// 处理项目更名问题 @游客企业 也相对映要修改 级联更新 订单表的企业名称@游客企业
		if (null != snapshot && !sysOrganization.getOrganizationName().equals(snapshot.getOrganizationName())) {

			SysEnterprise visitorVirt = sysEnterpriseService.renameByOutOrgId(sysOrganization);

			if (null != visitorVirt) {
				// 级联更新 订单表的企业名称@游客企业
				commonOrderProcessService.cascadeUpdateTableUnifiedOrderFieldVirtName(visitorVirt.getEnterpriseId(), visitorVirt.getEnterpriseName());
			}
		}

		// TODO SysOrganization 合法性 验证

		// 游客企业逻辑
		sysEnterpriseService.touchByOutOrgId(sysOrganization.getOrganizationId());

		// 级联更新 订单表的项目名称
		commonOrderProcessService.cascadeUpdateTableUnifiedOrderFieldOrgName(sysOrganization.getOrganizationId(), sysOrganization.getOrganizationName());

		if (sysOrganization.getDeleted().equals(CommonSoftDeleteEnum.删除.getKey())) {
			// 触发 级联更新 判定此项目下有订单情况,更新项目表中的是否有订单[isHasOrder]
			commonOrderProcessService.cascadeUpdateTableOrganizationFieldIsHasOrder(sysOrganization.getOrganizationId(), sysOrganization.getOrganizationName());
		}


	}
}
