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

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.leanwo.activiti.dto.BaseRangeResponse;
import com.leanwo.activiti.dto.BaseResponse;
import com.leanwo.activiti.dto.base.TaskDto;
import com.leanwo.activiti.service.base.MTaskService;
import com.leanwo.activiti.util.LoginContextUtil;

@Named
public class MTaskServiceImpl implements MTaskService {

	private static Logger logger = LoggerFactory.getLogger(MTaskServiceImpl.class);
	
	@Inject
	private org.activiti.engine.TaskService taskService;
	
	@Override
	public BaseRangeResponse<TaskDto> listByAssigneeIdCategory(String assigneeId, String category) {
		// 根据用户查询任务
		List<String> categorys = new ArrayList<String>();
		categorys.add(category);
		TaskQuery taskQuery = taskService.createTaskQuery().taskAssignee(assigneeId).processCategoryIn(categorys).active();
		Long count = taskQuery.count();
		int start = 0;
		int length = 10;
		List<Task> tasks = taskQuery.orderByTaskCreateTime().desc().listPage(start, length);
		
		BaseRangeResponse<TaskDto> baseRangeResponse = new BaseRangeResponse<TaskDto>();
		baseRangeResponse.setStart(start);
		baseRangeResponse.setLength(length);
		baseRangeResponse.setTotal(count.intValue());
		
		List<TaskDto> datas = new ArrayList<TaskDto>();
		for(Task task : tasks) {
			TaskDto taskDto = new TaskDto();
			taskDto.setId(task.getId());
			taskDto.setTaskDefinitionKey(task.getTaskDefinitionKey());
			taskDto.setName(task.getName());
			taskDto.setFormKey(task.getFormKey());
			datas.add(taskDto);
		}
		baseRangeResponse.setDatas(datas);
		return baseRangeResponse;
	}

	@Override
	public BaseResponse finishTask(String assigneeId, String taskId) {
		BaseResponse baseResponse = new BaseResponse();
		
		Long userId = LoginContextUtil.getLoginContext().getUserId();

		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

		if (task == null) {
			baseResponse.setErrorCode(1);
			baseResponse.setErrorMessage("任务已完成或已删除。");
			return baseResponse;
		}

		if (!task.getAssignee().equals(String.valueOf(userId))) {
			baseResponse.setErrorCode(2);
			baseResponse.setErrorMessage("您没有权限操作进行该操作。");
			return baseResponse;
		}

		if (task.isSuspended()) {
			baseResponse.setErrorCode(3);
			baseResponse.setErrorMessage("任务已经被挂起。");
			return baseResponse;
		}
		
		taskService.complete(taskId);
		
		baseResponse.setErrorCode(0);
		
		return baseResponse;		
	}

}
