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

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.projectrecord.enums.ProjectStatusEnum;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workborrowmangement.entity.WorkBorrowBack;
import com.jeeplus.modules.workborrowmangement.service.WorkBorrowBackService;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workincomingmessage.entity.WorkIncomingMessage;
import com.jeeplus.modules.workitem.entity.WorkItem;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.workborrowmangement.entity.WorkBorrowMangement;
import com.jeeplus.modules.workborrowmangement.service.WorkBorrowMangementService;

/**
 * 借用管理Controller
 * @author chenyuping
 * @version 2018-07-11
 */
@Controller
@RequestMapping(value = "${adminPath}/workborrowmangement/workBorrowMangement")
public class WorkBorrowMangementController extends BaseController {

	@Autowired
	private WorkBorrowMangementService workBorrowMangementService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkBorrowBackService workBorrowBackService;

	@ModelAttribute
	public WorkBorrowMangement get(@RequestParam(required=false) String id) {
		WorkBorrowMangement entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workBorrowMangementService.get(id);
		}
		if (entity == null){
			entity = new WorkBorrowMangement();
		}
		return entity;
	}
	
	/**
	 * 借用列表页面
	 */
	@RequiresPermissions("workborrowmangement:workBorrowMangement:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkBorrowMangement workBorrowMangement, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkBorrowMangement> page = workBorrowMangementService.findPage(new Page<WorkBorrowMangement>(request, response), workBorrowMangement); 
		model.addAttribute("page", page);
		return "modules/workborrowmangement/workBorrowMangementList";
	}

	/**
	 * 查看，增加，编辑借用表单页面
	 */
	@RequiresPermissions(value={"workborrowmangement:workBorrowMangement:view","workborrowmangement:workBorrowMangement:add","workborrowmangement:workBorrowMangement:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkBorrowMangement workBorrowMangement, Model model) {
	String flat=request.getParameter("tabId");
	if("1".equals(flat)){
		workBorrowMangement.setBackState("0");
		workBorrowMangement.setOfficeName(UserUtils.getSelectOffice().getTopCompany());
		workBorrowMangement.setOfficeId(UserUtils.getSelectOffice().getId());
		workBorrowMangement.setCompanyId(UserUtils.getSelectCompany().getId());
		workBorrowMangement.setBorrower(UserUtils.getUser().getId());
		workBorrowMangement.setUserName(UserUtils.getUser().getName());
	}

		model.addAttribute("workBorrowMangement", workBorrowMangement);
		return "modules/workborrowmangement/workBorrowMangementForm";
	}

	/**
	 * 保存借用
	 */
	@RequiresPermissions(value={"workborrowmangement:workBorrowMangement:add","workborrowmangement:workBorrowMangement:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkBorrowMangement workBorrowMangement, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workBorrowMangement)){
			return form(workBorrowMangement, model);
		}
		workBorrowMangement.setState("2");
		if(!workBorrowMangement.getIsNewRecord()){//编辑表单保存
			WorkBorrowMangement t = workBorrowMangementService.get(workBorrowMangement.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workBorrowMangement, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			String str=workBorrowMangementService.saveBorrow(t);//保存
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "借用申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "借用申请已经提交");
			}
		}else{//新增表单保存
			String str=workBorrowMangementService.saveBorrow(workBorrowMangement);//保存
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "借用申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "借用申请已经提交");
			}
		}
		//addMessage(redirectAttributes, "保存借用成功");
		return "redirect:"+Global.getAdminPath()+"/workborrowmangement/workBorrowMangement/?repage";
	}

	/**
	 * 暂存借用
	 */
	@RequiresPermissions(value={"workborrowmangement:workBorrowMangement:add","workborrowmangement:workBorrowMangement:edit"},logical=Logical.OR)
	@RequestMapping(value = "store")
	public String store(WorkBorrowMangement workBorrowMangement, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workBorrowMangement)){
			return form(workBorrowMangement, model);
		}
		workBorrowMangement.setState("1");
		workBorrowMangement.setOfficeId(UserUtils.getSelectOffice().getId());
		workBorrowMangement.setCompanyId(UserUtils.getSelectCompany().getId());
		workBorrowMangement.setBorrower(UserUtils.getUser().getId());
		workBorrowMangement.setBackState("0");
		if(!workBorrowMangement.getIsNewRecord()){//编辑表单保存
			WorkBorrowMangement t = workBorrowMangementService.get(workBorrowMangement.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workBorrowMangement, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workBorrowMangementService.save(t);//保存
		}else{//新增表单保存
			workBorrowMangementService.save(workBorrowMangement);//保存
		}
		addMessage(redirectAttributes, "保存借用成功");
		return "redirect:"+Global.getAdminPath()+"/workborrowmangement/workBorrowMangement/?repage";
	}
	
	/**
	 * 删除借用
	 */
	@RequiresPermissions("workborrowmangement:workBorrowMangement:del")
	@RequestMapping(value = "delete")
	public String delete(WorkBorrowMangement workBorrowMangement, RedirectAttributes redirectAttributes) {
		workBorrowMangementService.delete(workBorrowMangement);
		addMessage(redirectAttributes, "删除借用成功");
		return "redirect:"+Global.getAdminPath()+"/workborrowmangement/workBorrowMangement/?repage";
	}
	
	/**
	 * 批量删除借用
	 */
	@RequiresPermissions("workborrowmangement:workBorrowMangement:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workBorrowMangementService.delete(workBorrowMangementService.get(id));
		}
		addMessage(redirectAttributes, "删除借用成功");
		return "redirect:"+Global.getAdminPath()+"/workborrowmangement/workBorrowMangement/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workborrowmangement:workBorrowMangement:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkBorrowMangement workBorrowMangement, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "借用"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkBorrowMangement> page = workBorrowMangementService.findPage(new Page<WorkBorrowMangement>(request, response, -1), workBorrowMangement);
    		new ExportExcel("借用", WorkBorrowMangement.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出借用记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workborrowmangement/workBorrowMangement/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workborrowmangement:workBorrowMangement:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WorkBorrowMangement> list = ei.getDataList(WorkBorrowMangement.class);
			for (WorkBorrowMangement workBorrowMangement : list){
				try{
					workBorrowMangementService.save(workBorrowMangement);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条借用记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条借用记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入借用失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workborrowmangement/workBorrowMangement/?repage";
    }
	
	/**
	 * 下载导入借用数据模板
	 */
	@RequiresPermissions("workborrowmangement:workBorrowMangement:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "借用数据导入模板.xlsx";
    		List<WorkBorrowMangement> list = Lists.newArrayList(); 
    		new ExportExcel("借用数据", WorkBorrowMangement.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workborrowmangement/workBorrowMangement/?repage";
    }

	@RequiresPermissions(value={"workborrowmangement:workBorrowMangement:edit"},logical=Logical.OR)
	@RequestMapping(value = "modify")
	public String modify(WorkBorrowMangement workBorrowMangement, Model model, RedirectAttributes redirectAttributes) {
		workBorrowMangement=workBorrowMangementService.get(workBorrowMangement.getId());
		ProcessInstance processInstance = actTaskService.getProcIns(workBorrowMangement.getProcessInstanceId());
		if (processInstance!=null) {
			Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
			Act act = new Act();
			act.setTaskId(taskInfok.getId());
			act.setTaskName(taskInfok.getName());
			act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
			act.setProcDefId(taskInfok.getProcessDefinitionId());
			act.setProcInsId(taskInfok.getProcessInstanceId());
			act.setTask(taskInfok);
			workBorrowMangement.setAct(act);
		}

		model.addAttribute("workBorrowMangement", workBorrowMangement);
		return "modules/workborrowmangement/workBorrowMangementModifyApply";
	}
	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkBorrowMangement workBorrowMangement, Model model,
							RedirectAttributes redirectAttributes) {
		String taskDefKey = workBorrowMangement.getAct().getTaskDefKey();
		List<User> users = null;
		if ("ywbzr".equals(taskDefKey)){
			users = UserUtils.getByProssType(workBorrowMangement.getProcessInstanceId(),2);
			if (users==null)
			users = UserUtils.getByRoleActivityEnname("xzzg",3,workBorrowMangement.getOfficeId(),"16",workBorrowMangement.getCreateBy());
		}else if ("xzzg".equals(taskDefKey)){
			users = UserUtils.getByProssType(workBorrowMangement.getProcessInstanceId(),2);
			if (users==null )
				users = UserUtils.getByRoleActivityEnname("xzzg",3,workBorrowMangement.getOfficeId(),"16",workBorrowMangement.getCreateBy());
		}else if ("modifyApply".equals(taskDefKey)){
			users = UserUtils.getByProssType(workBorrowMangement.getProcessInstanceId(),1);
		}
		String flag = workBorrowMangement.getAct().getFlag();
		if ("yes".equals(flag) && (users==null || users.size()==0)){
			addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
		}else {
			String str = workBorrowMangementService.auditSave(workBorrowMangement,users);
			addMessage(redirectAttributes, str);
		}
		if (StringUtils.isNotBlank(workBorrowMangement.getHome()) && "home".equals(workBorrowMangement.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			return "redirect:" + Global.getAdminPath() + "/workborrowmangement/workBorrowMangement/?repage";
		}
	}
	//	审批页面
	@RequestMapping(value = "audit")
	public String workContractInfoAudit(Act act, WorkBorrowMangement workBorrowMangement, Model model) {

		if (act.getProcInsId() != null) {
			if (actTaskService.getProcIns(act.getProcInsId()) != null) {
				act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
			} else {
				act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
			}
		}
		if (act != null && StringUtils.isNotBlank(act.getTaskId())) {
			workBorrowMangement.setAct(act);
			model.addAttribute("processInstanceId", workBorrowMangement.getProcessInstanceId());
		}
		model.addAttribute("workBorrowMangement", workBorrowMangement);
		return "modules/workborrowmangement/workBorrowMangementAudit";
	}

	@RequestMapping(value = "getProcess")
	public String getProcess(WorkBorrowMangement workBorrowMangement, Model model, HttpServletRequest request){
		model.addAttribute("processInstanceId", workBorrowMangement.getProcessInstanceId());
		return "modules/workborrowmangement/workBorrowMangementTask";
	}

	@RequiresPermissions(value={"workborrowmangement:workBorrowMangement:edit"},logical=Logical.OR)
	@RequestMapping(value = "revoke")
	public String revoke(HttpServletRequest request, RedirectAttributes redirectAttributes) {
		HashMap<String, String> requestMap = findRequestMap(request);
		String processInstanceId = requestMap.get("processInstanceId");
		String id = requestMap.get("id");
		try {
			workBorrowMangementService.cancelProcess(id);
			addMessage(redirectAttributes, "撤回借用申请成功");
		}catch (Exception e){
			logger.info(e.getMessage());
			addMessage(redirectAttributes, "撤回借用申请失败");
		}
		return "redirect:" + Global.getAdminPath() + "/workborrowmangement/workBorrowMangement/?repage";
	}

	/**
	 * 查看，增加，编辑收文管理表单页面
	 */
	@RequiresPermissions(value={"workborrowmangement:workBorrowMangement:view"},logical=Logical.OR)
	@RequestMapping(value = "view")
	public String view(WorkBorrowMangement workBorrowMangement, Model model) {
		model.addAttribute("workBorrowMangement", workBorrowMangement);
		return "modules/workborrowmangement/workBorrowMangementView";
	}

	@RequestMapping(value = "selectItem")
	public String selectItem(WorkBorrowMangement workBorrowMangement, Model model) {
		model.addAttribute("workBorrowMangement", workBorrowMangement);
		return "modules/workborrowmangement/workBorrowMangementView";
	}



}