package com.blueland.bpm.manage.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.blueland.bpm.common.page.Page;
import com.blueland.bpm.engine.core.model.SearchProcessListDTO;
import com.blueland.bpm.engine.core.service.AutoRunOneProcess;
import com.blueland.bpm.engine.core.service.ProcessExecuteService;
import com.blueland.bpm.engine.core.service.ProcessInstanceService;
import com.blueland.bpm.manage.util.BaseUser;
import com.blueland.bpm.manage.util.MyContants;
@Controller
@RequestMapping(value = "/procUse")
public class ProcessUseController extends BaseProcessController{
	@Autowired
	private ProcessInstanceService processInstanceService;
	@Autowired
	ProcessExecuteService processExecuteService;
	@Autowired
	AutoRunOneProcess autoRunOneProcess;

	@RequestMapping(value="/list")
	public ModelAndView list(SearchProcessListDTO pageRequest,HttpServletRequest request) throws Exception {
		HistoricProcessInstanceQuery query=processInstanceService.getHistoryService().createHistoricProcessInstanceQuery().unfinished();
		pageRequest = (SearchProcessListDTO) bindPageRequest(request,
				pageRequest, "");
		if (StringUtils.isNotEmpty(pageRequest.getProcessDefKey())) {
			query.processDefinitionKey(pageRequest.getProcessDefKey());

		}
		if (StringUtils.isNotEmpty(pageRequest.getProcessDefName())) {
			query.processDefinitionName("%"+pageRequest.getProcessDefName()+"%");

		}
		if (StringUtils.isNotEmpty(pageRequest.getProcessInstanceId())) {
			query.processInstanceId(pageRequest.getProcessInstanceId());
		}
		if (StringUtils.isNotEmpty(pageRequest.getTitle())) {
			query.procTitle(pageRequest.getTitle());
		}
		if (StringUtils.isNotEmpty(pageRequest.getUserId())) {
			query.startedBy(pageRequest.getUserId());
		}
		String appId=BaseUser.getInstance().getLoginUserAppId(request);
		if("true".equalsIgnoreCase(MyContants.IS_OPEN_TENANT)&&(!StringUtils.isEmpty(appId))){
			query.processInstanceTenantId(appId);
		}

		//pageRequest.setPageSize(500);
		Page page = new Page(pageRequest, (int) query.count());
		
		List<HistoricProcessInstance> historicProcessInstances=query.orderByProcessInstanceStartTime().desc().listPage(page.getFirstResult(),page.getPageSize());
		ModelAndView modelAndView = new ModelAndView("/procInstMgr/list");
		
		page.setResult(historicProcessInstances);
		modelAndView.addAllObjects(toModelMap(page, pageRequest));
		modelAndView.addObject("isBpmAdmin",BaseUser.isEbpmAdmin(BaseUser.getInstance().getSessionUser(request)));
		return modelAndView;
	}
	
	
}
