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

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

import org.snaker.engine.SnakerEngine;
import org.snaker.engine.access.QueryFilter;
import org.snaker.engine.entity.Order;
import org.snaker.engine.entity.Task;
import org.springframework.beans.factory.annotation.Autowired;
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;

@RequestMapping("leave")
@RestController
public class LeaveController extends BaseController {

	@Autowired
	private SysUserFeignService SysUserFeignService;

	@Autowired
	private SnakerEngine snakerEngine;

	/**
	 * 请假申请路由方法
	 */
	@PostMapping(value = "apply")
	public Object apply(String processId, int days, String deptManager, String boss) {
		SysUser user = SysUserFeignService.queryUserInfo();

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("applyer", user.getId());
		params.put("days", days);
		//params.put("deptManager", deptManager);
		params.put("boss", boss);
		params.put("operator", user.getUsername());

		// 开启实例
		Order order = snakerEngine.startInstanceById(processId, user.getId()+"", params);

		// 获取当前任务
		List<Task> tasks = snakerEngine.query().getActiveTasks(new QueryFilter().setOrderId(order.getId()).setOperator(user.getId() + ""));
		for (Task task : tasks) {
			snakerEngine.executeTask(task.getId(), user.getId() + "");
		}

		return succeed();
	}

	@PostMapping(value = "approve")
	public Object approve(String taskId, boolean isAgree, String remark) {
		SysUser user = SysUserFeignService.queryUserInfo();

		System.out.println(user.getUsername() + "审批***************");

		Map<String, Object> params = new HashMap<String, Object>();

		params.put("status", isAgree);
		params.put("remark", remark);
		params.put("operator", user.getUsername());

		List<Task> tasks = null;

		// 审批同意
		if (isAgree) {
			tasks = snakerEngine.executeTask(taskId, user.getId() + "", params);
		} else {
			// 审批驳回
			tasks = snakerEngine.executeAndJumpTask(taskId, user.getId() + "", params, null);
		}
		if (tasks.size() == 0) {
			System.out.println("**********流程已结束*********");
		}

		return succeed();
	}
}
