/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.worksealform.web;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActAuditService;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.entity.Workattachment;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.WorkattachmentService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.worksealform.entity.WorkSealForm;
import com.jeeplus.modules.worksealform.service.WorkSealFormService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用印申请Controller
 * @author 丁旭
 * @version 2017-04-26
 */
@Controller
@RequestMapping(value = "${adminPath}/worksealform/workSealForm")
public class WorkSealFormController extends BaseController {

	@Autowired
	private WorkSealFormService workSealFormService;

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	protected RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private ActAuditService actAuditService;

	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private WorkattachmentService workattachmentService;

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@ModelAttribute
	public WorkSealForm get(@RequestParam(required=false) String id) {
		WorkSealForm entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workSealFormService.get(id);
		}
		if (entity == null){
			entity = new WorkSealForm();
		}
		return entity;
	}

	@RequiresPermissions(value={"worksealform:workSealForm:view","worksealform:workSealForm:add","worksealform:workSealForm:edit"},logical= Logical.OR)
	@RequestMapping(value = {"form"})
	public String form(WorkSealForm workSealForm, Model model) {
		String view = "workSealFormForm";
		// 查看审批申请单
		if (org.apache.commons.lang3.StringUtils.isNotBlank(workSealForm.getId())){//.getAct().getProcInsId())){
			// 环节编号
			String taskDefKey = workSealForm.getAct().getTaskDefKey();
			if (taskDefKey!=null) {
				// 查看工单
				if (workSealForm.getAct().isFinishTask()) {
					view = "workSealFormView";
				}
				// 修改环节
				else if ("apply_end".equals(taskDefKey)) {
					view = "workSealFormAudit";
				}
				// 审核环节
				else if ("audit1".equals(taskDefKey)) {
					if (org.apache.commons.lang3.StringUtils.isBlank(workSealForm.getAct().getStatus())){
						model.addAttribute("disabled","true");
					}else {
						model.addAttribute("disabled","false");
					}
					view = "workSealFormAudit";
				}
				//
				else if ("modifyApply".equals(taskDefKey)) {
					view = "workSealFormForm";
				}
			}
			if (org.apache.commons.lang3.StringUtils.isNotBlank(workSealForm.getName())){
				if (workSealForm.getName().equals("view")){
					model.addAttribute("disabled","true");
					workSealForm.getAct().setProcInsId(workSealForm.getProcessInstanceId());
					view = "workSealFormAudit";
				}
			}
		}


		model.addAttribute("workSealForm", workSealForm);
		return "modules/worksealform/"+view;
	}

	/**
	 * 启动请假流程
	 * @param workSealForm
	 */
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public String save(WorkSealForm workSealForm, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workSealForm)){
			return form(workSealForm, model);
		}
		if (org.apache.commons.lang3.StringUtils.isNotBlank(workSealForm.getId())) {
			WorkSealForm t = workSealFormService.get(workSealForm.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workSealForm, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			if (t.getStatus().equals("3") || t.getStatus().equals("4")){
				addMessage(redirectAttributes, "已结束流程不能修改！");
			}else {
				workSealFormService.save(t);
			}
		} else {
			try {
				boolean b = workSealFormService.saveWorkSealForm(workSealForm);
				if (b){
					addMessage(redirectAttributes, "用印申请已经提交");
				}else {
					addMessage(redirectAttributes, "系统内部错误！");
				}
			}catch (Exception e){
				logger.info("save e.getMessage()="+e.getMessage());
				addMessage(redirectAttributes, "系统内部错误！");
			}
		}
		if (workSealForm.getWorkAttachments()!=null && workSealForm.getWorkAttachments().size()!=0){
			List<Workattachment> list = workSealForm.getWorkAttachments();
			for (Workattachment w:list){
				if (StringUtils.isNotBlank(w.getUrl()) && !w.getUrl().equals("null")) {
					w.setCompanyId(workSealForm.getCompanyId());
					w.setAttachmentUser(UserUtils.getUser().getId());
					w.setAttachmentId(workSealForm.getId());
					w.setId("");
					workattachmentService.save(w);
				}
			}
		}
		return "redirect:"+ Global.getAdminPath()+"/worksealform/workSealForm/?repage";
	}


	/**
	 * 工单执行（完成任务）
	 * @param workSealForm
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkSealForm workSealForm, Map<String, Object> vars, Model model, RedirectAttributes redirectAttributes) {
		/*if (org.apache.commons.lang3.StringUtils.isBlank(workSealForm.getAct().getComment())){
			addMessage(model, "请填写审核意见。");
			return form(workSealForm, model);
		}*/
		//workSealFormService.auditSave(workSealForm);
		Act act = workSealForm.getAct();
		AjaxJson json = actAuditService.saveAudit(act, act.getProcInsId(), "sealform", workSealForm.getAct().getComment(), workSealForm.getId(), "2");
		addMessage(redirectAttributes, json.getMsg());
		if (workSealForm!=null && org.apache.commons.lang3.StringUtils.isNotBlank(workSealForm.getHome()) && workSealForm.getHome().equals("home")){
			return "redirect:" + adminPath + "/home";
		}
		return "redirect:" + adminPath + "/worksealform/workSealForm";
	}

	/**
	 * 读取所有流程
	 * @return
	 */
	@RequiresPermissions("worksealform:workSealForm:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkSealForm workSealForm, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			workSealForm.setCompanyId(user.getComId());
			if (!UserUtils.isManager()){
				workSealForm.setCreateBy(user);
			}
		}
		Page<WorkSealForm> page = workSealFormService.find(new Page<WorkSealForm>(request, response), workSealForm);
		model.addAttribute("page", page);
		return "modules/worksealform/workSealFormList";
	}

	/**
	 * 待办任务列表页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"workSealFormTodoList"})
	public String oaEvectionTodoList(Act act, HttpServletRequest request, HttpServletResponse response, Model model) {
		act.setProcDefKey("sealform");
		List<Act> list = actTaskService.todoList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<WorkSealForm> lists = new ArrayList<WorkSealForm>();
		for (Act a : list) {
			WorkSealForm workSealForm = workSealFormService.getByProcessInstanceId(a.getProcInsId());
			if (workSealForm != null && workSealForm.getCompanyId().equals(companyId)) {
				if (a.getVars().getMap().get("applyUserId")!=null) {
					User user = UserUtils.get(a.getVars().getMap().get("applyUserId").toString());
					if (user != null) {
						a.getVars().getMap().put("applyUserId", UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
					}
				}
				workSealForm.setAct(a);
				if (com.jeeplus.common.utils.StringUtils.isNotBlank(workSealForm.getId())){
					workSealForm.setName(officeService.get(companyId).getName());
				}
				lists.add(workSealForm);
			}
		}
		model.addAttribute("list", lists);
		return "modules/worksealform/workSealFormTodoList";
	}

	/**
	 * 已办任务
	 * @param act
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"workSealFormHistoricList"})
	public String oaEvectionHistoricList (Act act, HttpServletRequest request, HttpServletResponse response, Model model){
		act.setProcDefKey("sealform");
		Page<Act> page = actTaskService.historicList(new Page<Act>(request, response), act);
		List<Act> list = page.getList();
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<WorkSealForm> lists = new ArrayList<WorkSealForm>();
		for (Act a : list) {
			WorkSealForm workSealForm = workSealFormService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
			if (workSealForm != null && workSealForm.getCompanyId().equals(companyId)) {
				if (a.getVars().getMap().get("applyUserId")!=null){
					a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
				}
				workSealForm.setAct(a);
				if (com.jeeplus.common.utils.StringUtils.isNotBlank(workSealForm.getId())){
					workSealForm.setName(officeService.get(companyId).getName());
				}
				lists.add(workSealForm);
			}
		}
		model.addAttribute("list", lists);

		return "modules/worksealform/workSealFormHistoricList";
	}

	/**
	 * 审核企业信息
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnSealForm")
	public String applyOnCompany(Act act, HttpServletResponse response, Model model) {
		// 获取流程XML上的表单KEY
		String formKey = actTaskService.getFormKey(act.getProcDefId(), act.getTaskDefKey());
		//logger.info("------formKeys:"+formKeys);
		// 获取流程实例对象
		if (act.getProcInsId() != null){
			if(actTaskService.getProcIns(act.getProcInsId())!=null){
				act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
			}else{
				act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
			}
		}
		return "redirect:" + ActUtils.getFormUrl(formKey, act);
	}

	/**
	 * 用印申请撤销
	 * @param
	 * @return
	 */
	@RequestMapping(value = "revoke")
	public String revoke(HttpServletRequest request, HttpServletResponse response) {

		HashMap<String, String> requestMap = findRequestMap(request);
		String processInstanceId = requestMap.get("processInstanceId");
		String id = requestMap.get("id");
		String deleteReason = requestMap.get("reason");

		AjaxJson j = new AjaxJson();
		try {
			WorkSealForm workSealForm = workSealFormService.getById(id);
			workSealForm.setStatus("5");
			workSealForm.preUpdate();
			workSealFormService.update(workSealForm);
			Map map = workSealFormService.getUseSealById(id,"1");
			j.put("data",map);
			actTaskService.endProcessInstance(processInstanceId, deleteReason);
			j.setMsg("撤销申请成功");

			//撤销后，更改所有发送过的通知的阅读状态
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workSealForm.getId());
			workProjectNotifyService.readByNotifyId(notify);
		}catch (Exception e){
			j.setErrorCode("101");
			logger.info(e.getMessage());
			j.setMsg("撤销申请失败");
			j.setSuccess(false);
		}
		return "redirect:" + adminPath + "/worksealform/workSealForm";
	}

}