package com.leanwo.activiti.service.base.impl;

import java.util.List;

import javax.inject.Inject;

import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.leanwo.activiti.dto.BaseResponse;
import com.leanwo.activiti.dto.base.TaskDefineDto;
import com.leanwo.activiti.dto.base.TaskInstanceSaveRequest;
import com.leanwo.activiti.dto.base.TaskInstanceStatus;
import com.leanwo.activiti.dto.base.TaskInstanceUpdateRequest;
import com.leanwo.activiti.dto.base.TaskType;
import com.leanwo.activiti.service.base.HttpTaskEngine;
import com.leanwo.activiti.service.base.QuartzEngine;
import com.leanwo.activiti.service.base.TaskDefineService;
import com.leanwo.activiti.service.base.TokenService;
import com.leanwo.activiti.util.LoginContext;
import com.leanwo.activiti.util.LoginContextUtil;
import com.leanwo.activiti.util.SpringUtil;
import com.leanwo.activiti.util.TokenUtil;

/**
 * Http任务自动执行引擎.
 *
 * @author YangZhiJie 20190401
 */
public class HttpTaskEngineImpl extends Thread implements HttpTaskEngine {

	/**  */
	private static Logger logger = LoggerFactory.getLogger(HttpTaskEngineImpl.class);

	/**  */
	@Inject
	private QuartzEngine quartzEngine;

	/**  */
	private Long accountId;

	/**  */
	private boolean enable;

	/**  */
	@Inject
	private TokenService tokenService;

	/**  */
	@Inject
	private TaskDefineService taskDefineService;

	/**
	 * 
	 *
	 * @param accountId
	 * @param enable
	 */
	public HttpTaskEngineImpl(Long accountId, Boolean enable) {
		this.accountId = accountId;
		this.enable = enable;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.leanwo.activiti.service.base.HttpTaskEngine#init()
	 */
	@Override
	public void init() {
		if (this.enable == false) {
			logger.info("设置了Http任务自动执行引擎不启动。");
			return;
		}

		try {
			quartzEngine.start();
		} catch (SchedulerException e) {
			logger.error("Http任务引擎启动失败", e);
		}

		this.start();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		LoginContext loginContext = new LoginContext();
		loginContext.setAccountId(accountId);
		String tempToken = tokenService.generateTempToken();
		TokenUtil.setToken(tempToken);
		LoginContextUtil.setLoginContext(loginContext);
		// 获取所有的HTTP任务
		List<TaskDefineDto> taskDefineDtos = taskDefineService.list(TaskType.HTTP);
		if (taskDefineDtos != null) {
			String message = String.format("账套%d共计查询到%d条HTTP定时执行任务。", accountId,
					taskDefineDtos == null ? 0 : taskDefineDtos.size());
			logger.info(message);
			for (int i = 0; i < taskDefineDtos.size(); i++) {
				TaskDefineDto taskDefineDto = taskDefineDtos.get(i);
				try {
					quartzEngine.addHttpJob(accountId, taskDefineDto);
				} catch (SchedulerException e) {
					logger.error("Http任务添加失败。" + taskDefineDto.toString(), e);
				}
			}
		}
	}

	@Override
	public BaseResponse addJob(TaskDefineDto taskDefineDto) throws SchedulerException {
		BaseResponse baseResponse = new BaseResponse();
		try {
			Long accountId = LoginContextUtil.getLoginContext().getAccountId();
			if (enable) {
				quartzEngine.addHttpJob(accountId, taskDefineDto);
				baseResponse.setErrorCode(0);
				baseResponse.setErrorMessage("添加成功");
			} else {
				baseResponse.setErrorCode(1);
				baseResponse.setErrorMessage("未设置HTTP任务自动启动");
			}
		} catch (SchedulerException e) {
			baseResponse.setErrorCode(-1);
			baseResponse.setErrorMessage("添加失败:" + e.getMessage());
		}
		return baseResponse;

	}

	@Override
	public BaseResponse deleteJob(TaskDefineDto taskDefineDto) throws SchedulerException {
		BaseResponse baseResponse = new BaseResponse();
		try {
			Long accountId = LoginContextUtil.getLoginContext().getAccountId();
			if (enable) {
				quartzEngine.deleteHttpJob(accountId, taskDefineDto);
				baseResponse.setErrorCode(0);
				baseResponse.setErrorMessage("删除成功");
			} else {
				baseResponse.setErrorCode(1);
				baseResponse.setErrorMessage("未设置HTTP任务自动启动");
			}
		} catch (SchedulerException e) {
			baseResponse.setErrorCode(-1);
			baseResponse.setErrorMessage("删除失败:" + e.getMessage());
		}
		return baseResponse;
	}

	@Override
	public BaseResponse addTaskInstance(Long timeSerialNumber, TaskDefineDto taskDefineDto) {
		TaskInstanceSaveRequest taskInstanceSaveRequest = new TaskInstanceSaveRequest();
		taskInstanceSaveRequest.setTimeSerialNumber(timeSerialNumber);
		taskInstanceSaveRequest.setTaskDefineId(taskDefineDto.getId());
		taskInstanceSaveRequest.setClientId(taskDefineDto.getClientId());
		taskInstanceSaveRequest.setUserId(taskDefineDto.getUserId());
		return taskDefineService.addTaskInstance(taskInstanceSaveRequest);
	}

	@Override
	public BaseResponse updateTaskInstance(Long timeSerialNumber, String result, TaskInstanceStatus taskInstanceStatus,
			TaskDefineDto taskDefineDto) {
		TaskInstanceUpdateRequest taskInstanceUpdateRequest = new TaskInstanceUpdateRequest();
		taskInstanceUpdateRequest.setTimeSerialNumber(timeSerialNumber);
		taskInstanceUpdateRequest.setTaskDefineId(taskDefineDto.getId());
		taskInstanceUpdateRequest.setOperationResult(result);
		taskInstanceUpdateRequest.setTaskInstanceStatus(taskInstanceStatus);
		taskInstanceUpdateRequest.setClientId(taskDefineDto.getClientId());
		taskInstanceUpdateRequest.setUserId(taskDefineDto.getUserId());
		return taskDefineService.updateTaskInstance(taskInstanceUpdateRequest);
	}

}
