package com.mortals.xhx.module.api.service;

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.module.api.feign.portal.ApiResponse;
import com.mortals.xhx.module.api.feign.portal.PortalUserReq;
import com.mortals.xhx.module.api.feign.portal.UserRsp;
import com.mortals.xhx.module.api.handler.AssetFlowEventHandler;
import com.mortals.xhx.module.api.handler.impl.DefaultAssetFlowEventHandler;
import com.mortals.xhx.module.api.model.AssetEventInfo;
import com.mortals.xhx.module.api.model.AssetEventLog;
import com.mortals.xhx.module.asset.model.AssetEntity;
import com.mortals.xhx.module.asset.model.AssetFlowEventEntity;
import com.mortals.xhx.module.asset.service.AssetFlowEventService;
import com.mortals.xhx.module.asset.service.AssetService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author luoshichao
 * @Description
 * @date 2021/1/8 10:46
 */
@Component("assetFlowStatusService")
public class AssetFlowStatusService {
	protected Log log = LogFactory.getLog(this.getClass());

	@Autowired
	private AssetService assetService;
	@Autowired
	private AssetFlowEventService assetFlowEventService;

	@Autowired
	private UserService userService;

//	@Autowired
//	private IPortalFeign portalFeign;


	private Map<String, AssetFlowEventHandler> handlers;

	@PostConstruct
	private void init() {
		// 初始化各个事件的执行类
		handlers = GlobalSysInfo.getBeansByType(AssetFlowEventHandler.class);
	}

	/**
	 * 上报事件处理
	 * 
	 * @param req
	 */
	public void execute(AssetEventLog req) {
		AssetFlowEventEntity eventEntity = assetFlowEventService.getByEventCode(req.getEventCode());
		if (eventEntity == null) {
			throw new AppException("事件编码有误，事件不存在");
		}
		AssetFlowEventHandler handler = null;
		if (StringUtils.isNotEmpty(eventEntity.getScript())) {
			handler = handlers.get(StringUtils.uncapitalize(eventEntity.getScript()));
		}
		if (handler == null) {
			log.info("该事件没有特殊处理逻辑，采用通用处理类");
			handler = handlers.get(StringUtils.uncapitalize(DefaultAssetFlowEventHandler.class.getSimpleName()));
		}
		for(String assetNum: req.getAssetNumList()){
			AssetEntity assetEntity = assetService.getByAssetNum(assetNum);
			if (assetEntity == null) {
				throw new AppException("资产码有误，资产不存在");
			}
			processUser(req);

			handler.execute(assetEntity, eventEntity, req);
		}

	}

	//同步用户
	private  void processUser(AssetEventLog req){
		if(StringUtils.isNotEmpty(req.getEventUser())){
			syncUser(req.getEventUser());
		}
		if(StringUtils.isNotEmpty(req.getEventAfterUser())){
			Arrays.stream(req.getEventAfterUser().split(",")).forEach(loginName -> syncUser(loginName));
		}
	}
	//根据loginName从公共平台同步用户
	private  void syncUser(String loginName){
		UserQuery userQuery = new UserQuery();
		userQuery.setLoginName(loginName);
		List<UserEntity> userEntityList = userService.find(userQuery, null);
		if(userEntityList.isEmpty()){

			PortalUserReq portalUserReq = PortalUserReq.loginNameReq(loginName);
			log.info("调用公共平台接口：m/api/systemUser/get；  参数：" + JSONObject.toJSONString(portalUserReq));
			//从公共平台同步用户
			//ApiResponse<UserRsp> response = portalFeign.getSystemUser(PortalUserReq.loginNameReq(loginName));
			//log.info("调用公共平台接口：m/api/systemUser/get；  返回结果：" + JSONObject.toJSONString(response));
//			if(response.isSuccess()){
//				UserRsp userRsp = response.getData();
//				if(userRsp != null){
//					UserEntity userEntity = new UserEntity();
//					BeanUtils.copyProperties(userRsp, userEntity);
//					userService.save(userEntity, new Context());
//				}
//			}

		}
	}

	/**
	 * 获取资产可操作后续事件
	 * 
	 * @param assetNum
	 */
	public List<AssetEventInfo> getNextEventList(String assetNum) {
		AssetEntity assetEntity = assetService.getByAssetNum(assetNum);
		if (assetEntity == null) {
			throw new AppException("资产码[" + assetNum +"]有误，资产不存在");
		}
		List<AssetFlowEventEntity> eventEntities = assetFlowEventService
				.getFollowEventList(assetEntity.getFlowStatus() + "");
		return BeanUtil.covertList(eventEntities, AssetEventInfo.class);
	}

}