package com.ym.mec.workfow.controller.flow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.snaker.engine.SnakerEngine;
import org.snaker.engine.access.Page;
import org.snaker.engine.access.QueryFilter;
import org.snaker.engine.core.AccessService;
import org.snaker.engine.entity.HistoryOrder;
import org.snaker.engine.entity.Task;
import org.snaker.engine.entity.WorkItem;
import org.snaker.engine.model.TaskModel.TaskType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.common.controller.BaseController;

/**
 * Snaker流程引擎常用Controller
 * @author yuqs
 * @since 0.1
 */
@RestController
@RequestMapping(value = "/snaker/task")
public class TaskController extends BaseController {

	@Autowired
	private SnakerEngine snakerEngine;

	@Autowired
	private SysUserFeignService SysUserFeignService;

	@GetMapping(value = "home")
	public Object homeTaskList() {

		SysUser user = SysUserFeignService.queryUserInfo();

		List<String> list = new ArrayList<String>();
		list.add(user.getId() + "");

		String[] assignees = new String[list.size()];
		list.toArray(assignees);

		Page<WorkItem> majorPage = new Page<WorkItem>(5);
		Page<WorkItem> aidantPage = new Page<WorkItem>(3);
		Page<HistoryOrder> ccorderPage = new Page<HistoryOrder>(3);
		List<WorkItem> majorWorks = snakerEngine.query().getWorkItems(majorPage,
				new QueryFilter().setOperators(assignees).setTaskType(TaskType.Major.ordinal()));
		List<WorkItem> aidantWorks = snakerEngine.query().getWorkItems(aidantPage,
				new QueryFilter().setOperators(assignees).setTaskType(TaskType.Aidant.ordinal()));
		List<HistoryOrder> ccWorks = snakerEngine.query().getCCWorks(ccorderPage, new QueryFilter().setOperators(assignees).setState(1));

		ModelMap model = new ModelMap();

		model.addAttribute("majorWorks", majorWorks);
		model.addAttribute("majorTotal", majorPage.getTotalCount());
		model.addAttribute("aidantWorks", aidantWorks);
		model.addAttribute("aidantTotal", aidantPage.getTotalCount());
		model.addAttribute("ccorderWorks", ccWorks);
		model.addAttribute("ccorderTotal", ccorderPage.getTotalCount());
		return succeed(model);
	}

	/**
	 * 根据当前用户查询待办任务列表
	 * @param model
	 * @return
	 */
	@GetMapping(value = "queryWaitList")
	public Object queryWaitList(Page<WorkItem> page) {
		SysUser user = SysUserFeignService.queryUserInfo();

		snakerEngine.query().getWorkItems(page, new QueryFilter().setOperator(user.getId() + ""));
		return succeed(page);
	}

	@PostMapping(value = "actor/add")
	public Object addTaskActor(String orderId, String taskName, String operator) {
		List<Task> tasks = snakerEngine.query().getActiveTasks(new QueryFilter().setOrderId(orderId));
		for (Task task : tasks) {
			if (task.getTaskName().equalsIgnoreCase(taskName) && StringUtils.isNotEmpty(operator)) {
				snakerEngine.task().addTaskActor(task.getId(), operator);
			}
		}
		return succeed();
	}

	@GetMapping(value = "tip")
	public Object addTaskActor(String orderId, String taskName) {
		List<Task> tasks = snakerEngine.query().getActiveTasks(new QueryFilter().setOrderId(orderId));
		StringBuilder builder = new StringBuilder();
		String createTime = "";
		for (Task task : tasks) {
			if (task.getTaskName().equalsIgnoreCase(taskName)) {
				String[] actors = snakerEngine.query().getTaskActorsByTaskId(task.getId());
				for (String actor : actors) {
					builder.append(actor).append(",");
				}
				createTime = task.getCreateTime();
			}
		}
		if (builder.length() > 0) {
			builder.deleteCharAt(builder.length() - 1);
		}
		Map<String, String> data = new HashMap<String, String>();
		data.put("actors", builder.toString());
		data.put("createTime", createTime);
		return succeed(data);
	}

	/**
	 * 活动任务查询列表
	 * @param model
	 * @return
	 */
	@GetMapping(value = "active/more")
	public Object activeTaskList(Page<WorkItem> page, Integer taskType) {
		SysUser user = SysUserFeignService.queryUserInfo();

		List<String> list = new ArrayList<String>();
		list.add(user.getId() + "");

		String[] assignees = new String[list.size()];
		list.toArray(assignees);
		snakerEngine.query().getWorkItems(page, new QueryFilter().setOperators(assignees).setTaskType(taskType));
		return succeed(page);
	}

	/**
	 * 活动任务查询列表
	 * @param model
	 * @return
	 */
	@GetMapping(value = "active/ccmore")
	public Object activeCCList(Page<HistoryOrder> page) {
		SysUser user = SysUserFeignService.queryUserInfo();

		List<String> list = new ArrayList<String>();
		list.add(user.getId() + "");

		String[] assignees = new String[list.size()];
		list.toArray(assignees);
		snakerEngine.query().getCCWorks(page, new QueryFilter().setOperators(assignees).setState(AccessService.STATE_ACTIVE));
		return succeed(page);
	}

	/**
	 * 活动任务的驳回
	 * @param model
	 * @param taskId
	 * @return
	 */
	@PostMapping(value = "reject")
	public Object activeTaskReject(String taskId) {

		SysUser user = SysUserFeignService.queryUserInfo();

		snakerEngine.executeAndJumpTask(taskId, user.getId() + "", null, null);
		return succeed();
	}

	/**
	 * 历史完成任务查询列表
	 * @param model
	 * @return
	 */
	@GetMapping(value = "history")
	public Object historyTaskList(Page<WorkItem> page) {
		SysUser user = SysUserFeignService.queryUserInfo();
		snakerEngine.query().getHistoryWorkItems(page, new QueryFilter().setOperator(user.getId() + ""));
		return succeed(page);
	}

	/**
	 * 历史任务撤回
	 * @param orderId
	 * @return
	 */
	@PostMapping(value = "undo")
	public Object historyTaskUndo(String orderId) {
		SysUser user = SysUserFeignService.queryUserInfo();
		snakerEngine.order().withdraw(orderId, user.getId() + "");
		return succeed();
	}
}
