package cn.myapps.runtime.rest.workflow.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import cn.myapps.runtime.workflow.service.WorkflowRunTimeService;
import cn.myapps.runtime.workflow.storage.runtime.ejb.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;

import cn.myapps.base.web.WebUser;
import cn.myapps.common.controller.Resource;
import cn.myapps.common.data.DataPackage;
import cn.myapps.runtime.dynaform.document.ejb.WorkVO;
import cn.myapps.runtime.dynaform.work.ejb.WorkProcess;
import cn.myapps.runtime.dynaform.work.ejb.WorkProcessBean;
import cn.myapps.runtime.rest.common.controller.AbstractRESTController;
import cn.myapps.runtime.rest.workflow.service.WorkflowHistoryService;
import cn.myapps.runtime.workflow.storage.runtime.intervention.ejb.FlowInterventionVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 流程历史控制器
 * 
 * @author steven
 *
 */

@Api(tags = "流程历史模块")
@Controller
@RequestMapping(path = "/api/rest/bpm")
public class WorkflowHistoryController extends AbstractRESTController {

	@Autowired
	@Qualifier("workflowHistoryServiceImpl")
	WorkflowHistoryService service;

	@Autowired
	private WorkflowRunTimeService workflowService;
	/**
	 * 获取文档流程历史
	 * @param accessToken
	 * @param applicationId
	 * @param instanceId
	 * @param userCode
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "流程历史", notes = "流程历史")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "accessToken",value = "访问令牌",required = true,paramType = "query",dataType = "string"),
		@ApiImplicitParam(name = "applicationId",value = "应用Id",required = true,paramType = "query",dataType = "string"),
		@ApiImplicitParam(name = "instanceId",value = "流程实例Id",required = true,paramType = "query",dataType = "string"),
		@ApiImplicitParam(name = "userCode",value = "用户编码",required = true,paramType = "query",dataType = "string")

	})
	@GetMapping(value = "/history/flowHistory", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseStatus(HttpStatus.OK)
	public Resource getHistorys(@RequestParam String accessToken,@RequestParam String applicationId,
								@RequestParam String id,@RequestParam String userCode) throws Exception {
		List<FlowHistoryVO> result = service.getHistorys(applicationId, id);
//		JSONArray jsonArray = cn.myapps.util.json.JsonTmpUtil.fromObject(result);
//		JSONArray newJsonArray = new JSONArray();
//		for (int i = 0; i < jsonArray.size(); i++) {
//			JSONObject jsonObject = (JSONObject) jsonArray.get(i);
//			jsonObject = jsonObject.discard("signature");
//			jsonObject = jsonObject.discard("signatureImageDate");
//			newJsonArray.add(jsonObject);
//		}
		return success("success", result);
	}

	/**
	 * 获取文档流程图
	 * @param accessToken
	 * @param applicationId
	 * @param instanceId
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "获取流程图", notes = "获取流程图")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "accessToken",value = "访问令牌",required = true,paramType = "query",dataType = "string"),
		@ApiImplicitParam(name = "applicationId",value = "应用Id",required = true,paramType = "query",dataType = "string"),
		@ApiImplicitParam(name = "instanceId",value = "流程实例Id",required = true,paramType = "query",dataType = "string")
	})
	@GetMapping("/history/flowPhoto")
	@ResponseStatus(HttpStatus.OK)
	public ResponseEntity<byte[]> getFlowPhoto(@RequestParam String accessToken,@RequestParam String applicationId,
											   @RequestParam String instanceId)throws Exception {
		FlowRuntimeService process = new FlowRuntimeServiceImpl(applicationId);
		FlowStateRT flowState = (FlowStateRT)process.findFlowStateRT(instanceId);
		HttpHeaders headers = new HttpHeaders();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(flowState.getAuditdate());
		String dateTime = String.valueOf(calendar.get(Calendar.YEAR)+String.valueOf(calendar.get(Calendar.MONTH)+1));
		File file = service.getFlowPhoto(applicationId, instanceId,dateTime);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", instanceId+".jpg");
		if ((file == null || !file.exists())&&flowState!=null) {
			throw new Exception("该流程为自由流程，没有流程图。");
		}
		if (file == null || !file.exists()) {
			throw new Exception("找不到文件！");
		}

		return new ResponseEntity<byte[]>(File2byte(file), headers, HttpStatus.CREATED);
	}

	public static byte[] File2byte(File file) {
		byte[] buffer = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}
	/**
	 * 前台widget显示-我的待办(包含多个软件)
	 * @param pageNo 页数
	 * @param linesPerPage 每页
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/myPending")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "前台widget显示-我的待办(包含多个软件)", notes = "rest接口获取我的待办(包含多个软件)")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userCode",value = "用户账号",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "accessToken",value = "访问令牌",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "pageNo",value = "现在的页数",required = false,paramType = "query",dataType = "string",defaultValue="1"),
			@ApiImplicitParam(name = "linesPerPage",value = "每页的条数",required = false,paramType = "query",dataType = "string",defaultValue="5")
	})
	public Resource queryPendingByUser(@RequestParam() String userCode,@RequestParam() String accessToken,@RequestParam(required=false,defaultValue="1") int pageNo,@RequestParam(required=false,defaultValue="5") int linesPerPage) throws Exception{
		//得到用户
		WebUser user=getUser();
		List<String> applicationIds = user.getApplicationIds();
		DataPackage<WorkVO> workDataPage= new DataPackage<WorkVO>();
		List<WorkVO> listWork = new ArrayList<WorkVO>();
		int allSum=0;
		boolean isFlowAgent=true;
		if(applicationIds != null){
			for (String applicationId : applicationIds) {
				WorkProcess wp = new WorkProcessBean(applicationId);
				DataPackage<WorkVO> tmp_works = wp.getPendingList("", "", "", isFlowAgent, applicationId, user.getDomainid(),"", pageNo, linesPerPage, user);
				listWork.addAll(tmp_works.getDatas());
				//添加该用户软件下的待办数量
				allSum+=tmp_works.getRowCount();
			}
		}
		if(allSum!=0){
			//为包赋值
			workDataPage.setRowCount(allSum);
			workDataPage.setLinesPerPage(linesPerPage);
			workDataPage.setPageNo(pageNo);

			//分页后的数据
			int beginIndex=(pageNo-1)*linesPerPage;
			int endIndex=pageNo*linesPerPage;
			//如果开始标志大于listWork的数量
			if(beginIndex>=listWork.size()){
				workDataPage.setDatas(null);
				workDataPage.setRowCount(0);
			}else if(endIndex>=listWork.size()){ //如果结束标志大于等于listWork的数量
				endIndex=listWork.size();
			}

			workDataPage.setDatas(listWork.subList(beginIndex, endIndex));

		}

		return success("ok",workDataPage);
	}

	/**
	 * 前台widget显示-我的经办(包含多个软件)
	 * @param pageNo 页数
	 * @param linesPerPage 每页
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/myProcessing")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "前台widget显示-我的经办(包含多个软件)", notes = "rest接口获取我的经办(包含多个软件)")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userCode",value = "用户账号",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "accessToken",value = "访问令牌",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "pageNo",value = "现在的页数",required = false,paramType = "query",dataType = "string",defaultValue="1"),
			@ApiImplicitParam(name = "linesPerPage",value = "每页的条数",required = false,paramType = "query",dataType = "string",defaultValue="5")
	})
	public Resource queryProcessingByUser(@RequestParam String userCode,@RequestParam String accessToken,@RequestParam(required=false,defaultValue="1") int pageNo,@RequestParam(required=false,defaultValue="5") int linesPerPage) throws Exception{
		//得到用户
		WebUser user=getUser();
		List<String> applicationIds = user.getApplicationIds();
		DataPackage<WorkVO> workDataPage= new DataPackage<WorkVO>();
		List<WorkVO> listWork = new ArrayList<WorkVO>();
		int allSum=0;
		if(applicationIds != null){
			for (String applicationId : applicationIds) {
				WorkProcess wp = new WorkProcessBean(applicationId);

				DataPackage<WorkVO> tmp_works = wp.getProcessedRunningList("", "", "", applicationId, user.getDomainid(), false, "", "", pageNo, linesPerPage, user);
				listWork.addAll(tmp_works.getDatas());
				//添加该用户软件下的待办数量
				allSum+=tmp_works.getRowCount();
			}
		}
		if(allSum!=0){
			//为包赋值
			workDataPage.setRowCount(allSum);
			workDataPage.setLinesPerPage(linesPerPage);
			workDataPage.setPageNo(pageNo);

			//分页后的数据
			int beginIndex=(pageNo-1)*linesPerPage;
			int endIndex=pageNo*linesPerPage;
			//如果开始标志大于listWork的数量
			if(beginIndex>=listWork.size()){
				workDataPage.setDatas(null);
				workDataPage.setRowCount(0);
			}else if(endIndex>=listWork.size()){ //如果结束标志大于等于listWork的数量
				endIndex=listWork.size();
			}

			workDataPage.setDatas(listWork.subList(beginIndex, endIndex));

		}

		return success("ok",workDataPage);
	}

	/**
	 * 获取流程催办历史
	 * @param accessToken
	 * @param applicationId
	 * @param instanceId
	 * @param userCode
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "获取流程催办历史", notes = "获取流程催办历史")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "accessToken",value = "访问令牌",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "applicationId",value = "应用Id",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "userCode",value = "用户编码",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "instanceId",value = "流程实例Id",required = true,paramType = "query",dataType = "string")
	})
	@GetMapping("/history/remindhis")
	@ResponseStatus(HttpStatus.OK)
	public Resource remindHis(@RequestParam String accessToken,@RequestParam String applicationId, @RequestParam String instanceId,
							  @RequestParam String userCode) throws Exception {
		WebUser user = getUser();
		FlowRuntimeService flowStateRTProcess = new FlowRuntimeServiceImpl( applicationId);
		FlowStateRT instance = flowStateRTProcess.findFlowStateRT(instanceId);
		List<FlowReminderHistory> result = workflowService.getRemindHistorys(applicationId, instance.getDocid());
		return success("ok", result);
	}
}
