package com.artfess.job.job;

import javax.annotation.Resource;

import com.artfess.base.feign.WorkflowFeignService;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.artfess.base.constants.SystemConstants;
import com.artfess.base.exception.BaseException;
import com.artfess.base.util.AppUtil;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.StringUtil;
import com.artfess.job.model.BaseJob;
import com.artfess.uc.api.impl.util.ContextUtil;

/**
 * 定时启动流程
 *
 * @company 阿特菲斯信息技术有限公司
 * @author heyifan
 * @email heyf@jee-soft.cn
 * @date 2019年5月28日
 */
public class FlowAutoStartJob extends BaseJob {
	@Resource
	WorkflowFeignService workflowFeignService;

	@Override
	public void executeJob(JobExecutionContext context) throws Exception {
		String defaultAccount = SystemConstants.SYSTEM_ACCOUNT;
		JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
		String startAccount = jobDataMap.getString("startAccount");
		if (StringUtil.isNotEmpty(startAccount)) {
			defaultAccount = startAccount;
		}
		// 定时任务中没有当前登录用户，所以需要设置到当前用户上下文中
		ContextUtil.setCurrentUserByAccount(defaultAccount);

		if (workflowFeignService == null) {
			workflowFeignService = AppUtil.getBean(WorkflowFeignService.class);
		}
		// 调用接口启动流程
		ObjectNode startFlowResult = workflowFeignService.defAutoStart();
		if (BeanUtils.isNotEmpty(startFlowResult) && !startFlowResult.get("state").asBoolean()) {
			String message = "流程启动失败";
			if (BeanUtils.isNotEmpty(startFlowResult) && BeanUtils.isNotEmpty(startFlowResult.get("message"))) {
				message += ":" + startFlowResult.get("message").asText();
			}
			throw new BaseException(message);
		}
	}

}
