package com.blueland.bpm.manage.log.web;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.blueland.bpm.application.model.ApplicationEntity;
import com.blueland.bpm.application.service.ApplicationManager;
import com.blueland.bpm.common.base.BaseSpringController;
import com.blueland.bpm.common.page.Page;
import com.blueland.bpm.common.util.HttpUtils;
import com.blueland.bpm.engine.core.model.ProcessInputModel;
import com.blueland.bpm.engine.core.service.ProcessExecuteService;
import com.blueland.bpm.engine.util.JsonUtil;
import com.blueland.bpm.engine.util.WorkFlowException;
import com.blueland.bpm.log.model.ProcessErrorLog;
import com.blueland.bpm.log.service.ProcessErrorLogManager;
import com.blueland.bpm.manage.util.BaseUser;
import com.blueland.bpm.manage.util.SmsEmailMsg;

/**
 * @author lw
 * @version 1.0
 * @since
 */

@Controller
@RequestMapping(value = "processErrorLog")
public class ProcessExecuteLogController extends BaseSpringController {
	// 默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;
	
	private static final Logger log = LoggerFactory.getLogger(ProcessExecuteLogController.class);
	
	@Autowired
	private ProcessErrorLogManager processErrorLogManager;
	@Autowired
	private ApplicationManager applicationManager;
	@Autowired
	ProcessExecuteService processExecuteService;
	private final String LIST_ACTION = "redirect:/processErrorLog/list.do";

	public ProcessExecuteLogController() {
	}

	/**
	 * 增加了@ModelAttribute的方法可以在本controller的方法调用前执行,可以存放一些共享变量,如枚举值
	 */
	@ModelAttribute
	public void init(ModelMap model) {
		// model.put("now", new java.sql.Timestamp(System.currentTimeMillis()));
	}

	/**
	 * 执行搜索
	 **/
	@RequestMapping(value = "errorList")
	public ModelAndView list(HttpServletRequest request, ProcessErrorLog query,String flag) {
		try {
			if ((!BaseUser.isEbpmAdmin(BaseUser.getInstance().getSessionUser(request))
					|| StringUtils.isEmpty(query.getAppId())) && StringUtils.isEmpty(flag)) {
				String loginUserAppId = BaseUser.getInstance().getLoginUserAppId(request);
				query.setAppId(loginUserAppId);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("==list==", e);
		}
		if (query.getStartPelogTime() == null && StringUtils.isEmpty(flag)) {
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DATE, 1);
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.MILLISECOND, 0);
			query.setEndPelogTime(cal.getTime());
			cal.add(Calendar.DATE, -7);
			query.setStartPelogTime(cal.getTime());
		}
		query.setSortColumns("pelog_create_time desc");
		query.setProcessLogLevel("error");
		if (StringUtils.isEmpty(query.getRetryStatus())) {
			query.setRetryStatus("n");
		}
		Page page = this.processErrorLogManager.findPageNotMsg(query);
		ModelAndView result = new ModelAndView("/processErrorLog/errorList");
		result.addAllObjects(toModelMap(page, query));
		result.addObject("flag", flag);
		// saveQueryParams(request, query);
		return result;
	}

	
		
	/**
	 * 执行搜索
	 **/
	@RequestMapping(value = "infoList")
	public ModelAndView infoList(HttpServletRequest request, ProcessErrorLog query,String flag) {
		try {
			if ((!BaseUser.isEbpmAdmin(BaseUser.getInstance().getSessionUser(request))
					|| StringUtils.isEmpty(query.getAppId())) && StringUtils.isEmpty(flag)) {
				String loginUserAppId = BaseUser.getInstance().getLoginUserAppId(request);
				query.setAppId(loginUserAppId);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("==infoList==", e);
		}
		if (query.getStartPelogTime() == null && StringUtils.isEmpty(flag)) {
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.MILLISECOND, 0);
			query.setStartPelogTime(cal.getTime());
			cal.add(Calendar.DATE, 1);
			query.setEndPelogTime(cal.getTime());
		}
		query.setSortColumns("pelog_create_time desc");
		query.setProcessLogLevel("info");
		Page page = this.processErrorLogManager.findPageNotMsg(query);
		ModelAndView result = new ModelAndView("/processErrorLog/infoList");
		result.addAllObjects(toModelMap(page, query));
		result.addObject("flag", flag);
		this.saveQueryParams(request, query);
		return result;
	}
	
	
	
	
	

	/**
	 * 查看对象
	 **/
	@RequestMapping(value = "showInfo")
	public ModelAndView showInfo(HttpServletRequest request) {
		String id = new String(request.getParameter("pelogId"));
		ProcessErrorLog processErrorLog = (ProcessErrorLog) processErrorLogManager.getById(id);
		return new ModelAndView("/processErrorLog/showInfo", "processErrorLog", processErrorLog);
	}

	/**
	 * 查看对象
	 **/
	@RequestMapping(value = "showError")
	public ModelAndView showError(HttpServletRequest request) {
		String id = new String(request.getParameter("pelogId"));
		ProcessErrorLog processErrorLog = (ProcessErrorLog) processErrorLogManager.getById(id);
		return new ModelAndView("/processErrorLog/showError", "processErrorLog", processErrorLog);
	}

	/**
	 * 保存新增对象
	 **/
	@RequestMapping(value = "save")
	public ModelAndView save(HttpServletRequest request, ProcessErrorLog processErrorLog,
			RedirectAttributes redirectAttributes) {
		processErrorLogManager.save(processErrorLog);
		redirectAttributes.addFlashAttribute(ACTION_MESSAGE, CREATED_SUCCESS);
		return new ModelAndView(LIST_ACTION);
	}

	/**
	 * 进入更新页面
	 **/
	@RequestMapping(value = "retryVeiw")
	public ModelAndView edit(HttpServletRequest request) {
		String id = new String(request.getParameter("pelogId"));
		ProcessErrorLog processErrorLog = (ProcessErrorLog) processErrorLogManager.getById(id);
		return new ModelAndView("/processErrorLog/retry", "processErrorLog", processErrorLog);
	}

	/**
	 * 进入更新页面
	 **/
	@RequestMapping(value = "retry")
	@ResponseBody
	public String retry(String pelogId, String processMsg) {
		if (StringUtils.isEmpty(processMsg)) {
			return "发送的消息内容不能为空!";
		}
		ProcessInputModel processInputModel = null;
		try {
			processInputModel = (ProcessInputModel) JsonUtil.convertToBean(processMsg, ProcessInputModel.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (processInputModel == null || StringUtils.isEmpty(processInputModel.getWf_procTitle())) {
			return "消息内容格式有误,无法转换成processInputModel对象";
		}
		Map<String, Object> result = null;
		try {
			result = processExecuteService.nextExecute(processInputModel);
		} catch (Exception e) {
			log.error("==retry==", e);
		}
		ProcessErrorLog processErrorLog = processErrorLogManager.getById(pelogId);
		processErrorLog.setRetryStatus("y");
		processErrorLogManager.update(processErrorLog);
//		try{
//			ApplicationEntity applicationEntity = applicationManager.getById(processErrorLog.getAppId());
//			SmsEmailMsg.sendSmsEmail(SmsEmailMsg.buildEmailMsgData(applicationEntity, processErrorLog,msg));
//		}catch(Exception e){
//			log.error("==retry==邮件提醒发送失败：", e);
//		}
		return (String) result.get("executeStatus");

	}

	/**
	 * 处理错误消息
	 * 
	 * @param pelogId
	 * @return
	 */
	@RequestMapping(value = "disposeErrorLog")
	@ResponseBody
	public String disposeErrorLog(String pelogId) {
		ProcessErrorLog processErrorLog = processErrorLogManager.getById(pelogId);
		if (processErrorLog == null) {
			return "错误消息为空!";
		}
		processErrorLog.setRetryStatus("y");
		processErrorLogManager.update(processErrorLog);
		return "SUCCESS";
	}

	/**
	 * 保存更新对象
	 **/
	@RequestMapping(value = "update")
	public ModelAndView update(HttpServletRequest request, ProcessErrorLog processErrorLog,
			RedirectAttributes redirectAttributes) {
		//String id = new String(request.getParameter("pelogId"));
		processErrorLogManager.update(processErrorLog);
		redirectAttributes.addFlashAttribute(ACTION_MESSAGE, UPDATE_SUCCESS);
		return new ModelAndView(LIST_ACTION);
	}

	/**
	 * 删除对象
	 **/
	@RequestMapping(value = "delete")
	public ModelAndView delete(HttpServletRequest request, RedirectAttributes redirectAttributes) {
		String[] items = request.getParameterValues("items");
		for (int i = 0; i < items.length; i++) {
			Hashtable params = HttpUtils.parseQueryString(items[i]);

			String id = new String((String) params.get("pelogId"));

			processErrorLogManager.removeById(id);
		}
		redirectAttributes.addFlashAttribute(ACTION_MESSAGE, DELETE_SUCCESS);
		return new ModelAndView(LIST_ACTION);
	}

}
