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

import java.text.ParseException;
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.isignature.dao.ISignatureDocumentDao;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
import com.jeeplus.modules.workofficechange.entity.WorkOfficeChange;
import com.jeeplus.modules.workofficechange.entity.WorkOfficeChangeUser;
import com.jeeplus.modules.workstaffachiveslog.entity.WorkStaffAchivesLog;
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.*;
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.workcontractsignature.entity.WorkContractSignature;
import com.jeeplus.modules.workcontractsignature.service.WorkContractSignatureService;

/**
 * 合同签章Controller
 * @author ssrh
 * @version 2018-10-26
 */
@Controller
@RequestMapping(value = "${adminPath}/workcontractsignature/workContractSignature")
public class WorkContractSignatureController extends BaseController {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private WorkContractInfoService workContractInfoService;
	@Autowired
	private WorkContractSignatureService workContractSignatureService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private ISignatureDocumentDao iSignatureDocumentDao;

	@ModelAttribute
	public WorkContractSignature get(@RequestParam(required=false) String id) {
		WorkContractSignature entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workContractSignatureService.get(id);
		}
		if (entity == null){
			entity = new WorkContractSignature();
		}
		return entity;
	}
	
	/**
	 * 合同签章列表页面
	 */
	//@RequiresPermissions("workcontractsignature:workContractSignature:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkContractSignature workContractSignature, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkContractSignature> page = workContractSignatureService.findPage(new Page<WorkContractSignature>(request, response), workContractSignature); 
		model.addAttribute("page", page);
		return "modules/workcontractsignature/workContractSignatureList";
	}

	/**
	 * 查看，增加，编辑合同签章表单页面
	 */
	//@RequiresPermissions(value={"workcontractsignature:workContractSignature:view","workcontractsignature:workContractSignature:add","workcontractsignature:workContractSignature:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkContractSignature workContractSignature, Model model) {
		String tbal=request.getParameter("tbal");
		if("1".equals(tbal)){
			WorkContractInfo workContractInfo=workContractInfoService.get(workContractSignature.getId());
			workContractSignature.setWorkContractInfo(workContractInfo);
			workContractSignature.setWorkAttachments(workContractInfo.getWorkAttachments());
			workContractSignature.setId(null);
		}
		if("2".equals(tbal)){
			model.addAttribute("workContractSignature", workContractSignature);
			return "modules/workcontractsignature/workContractSignatureView";
		}
		model.addAttribute("workContractSignature", workContractSignature);
		return "modules/workcontractsignature/workContractSignatureForm";
	}

	/**
	 * 保存合同签章
	 */
	//@RequiresPermissions(value={"workcontractsignature:workContractSignature:add","workcontractsignature:workContractSignature:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkContractSignature workContractSignature, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workContractSignature)){
			return form(workContractSignature, model);
		}
		WorkContractInfo workContractInfo=workContractInfoService.get(workContractSignature.getWorkContractInfo().getId());

		workContractSignature.setStatus("2");
		workContractSignature.setCompanyId(workContractInfo.getCompanyId());
		workContractSignature.setOfficeId(workContractInfo.getOfficeId());
		workContractSignature.setCreateBy(workContractInfo.getCreateBy());
		if(!workContractSignature.getIsNewRecord()){//编辑表单保存
			WorkContractSignature t = workContractSignatureService.get(workContractSignature.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workContractSignature, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workContractSignatureService.saveChange(t);//保存
		}else{//新增表单保存
			workContractSignatureService.saveChange(workContractSignature);//保存
		}
		addMessage(redirectAttributes, "保存合同签章成功");
		return "redirect:"+Global.getAdminPath()+"/workcontractsignature/workContractSignature/?repage";
	}
	
	/**
	 * 删除合同签章
	 */
	//@RequiresPermissions("workcontractsignature:workContractSignature:del")
	@RequestMapping(value = "delete")
	public String delete(WorkContractSignature workContractSignature, RedirectAttributes redirectAttributes) {
		workContractSignatureService.delete(workContractSignature);
		addMessage(redirectAttributes, "删除合同签章成功");
		return "redirect:"+Global.getAdminPath()+"/workcontractsignature/workContractSignature/?repage";
	}
	
	/**
	 * 批量删除合同签章
	 */
	//@RequiresPermissions("workcontractsignature:workContractSignature:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workContractSignatureService.delete(workContractSignatureService.get(id));
		}
		addMessage(redirectAttributes, "删除合同签章成功");
		return "redirect:"+Global.getAdminPath()+"/workcontractsignature/workContractSignature/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	//@RequiresPermissions("workcontractsignature:workContractSignature:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkContractSignature workContractSignature, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "合同签章"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkContractSignature> page = workContractSignatureService.findPage(new Page<WorkContractSignature>(request, response, -1), workContractSignature);
    		new ExportExcel("合同签章", WorkContractSignature.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出合同签章记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workcontractsignature/workContractSignature/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	//@RequiresPermissions("workcontractsignature:workContractSignature: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<WorkContractSignature> list = ei.getDataList(WorkContractSignature.class);
			for (WorkContractSignature workContractSignature : list){
				try{
					workContractSignatureService.save(workContractSignature);
					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()+"/workcontractsignature/workContractSignature/?repage";
    }
	
	/**
	 * 下载导入合同签章数据模板
	 */
	//@RequiresPermissions("workcontractsignature:workContractSignature:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "合同签章数据导入模板.xlsx";
    		List<WorkContractSignature> list = Lists.newArrayList(); 
    		new ExportExcel("合同签章数据", WorkContractSignature.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workcontractsignature/workContractSignature/?repage";
    }

	@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 {
			workContractSignatureService.cancelProcess(id);
			addMessage(redirectAttributes, "撤回申请成功");
		}catch (Exception e){
			logger.info(e.getMessage());
			addMessage(redirectAttributes, "撤回申请失败");
		}
		return "redirect:" + Global.getAdminPath() + "/workcontractsignature/workContractSignature/?repage";
	}
	@RequestMapping(value = "getProcess")
	public String getProcess(WorkContractSignature workContractSignature, Model model, HttpServletRequest request){
		model.addAttribute("processInstanceId", workContractSignature.getProcessInstanceId());
		return "modules/workcontractsignature/workContractSignatureTask";
	}
	@RequestMapping(value = "modify")
	public String modify(WorkContractSignature workContractSignature, Model model, RedirectAttributes redirectAttributes) {
		workContractSignature=workContractSignatureService.get(workContractSignature.getId());
		ProcessInstance processInstance = actTaskService.getProcIns(workContractSignature.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);
			workContractSignature.setAct(act);
		}
		model.addAttribute("workContractSignature", workContractSignature);
		return "modules/workcontractsignature/workContractSignatureModifyApply";
	}
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkContractSignature workContractSignature, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workContractSignature.getAct().getTaskDefKey();
			List<User> users = UserUtils.getByProssType(workContractSignature.getProcessInstanceId(),1);
			if (users==null || (users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = workContractSignatureService.auditSave(workContractSignature,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			logger.info("Exception e:"+e);
			addMessage(redirectAttributes, "审批失败");
		}
		if (StringUtils.isNotBlank(workContractSignature.getHome()) && "home".equals(workContractSignature.getHome())) {
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		} else {
			return "redirect:"+Global.getAdminPath()+"/workcontractsignature/workContractSignature/?repage";
		}
	}
	@RequestMapping("signatureStatus")
	@ResponseBody
	public boolean signatureStatus(String id) throws ParseException {
		boolean falt=false;
		int count=iSignatureDocumentDao.getCount(id);
		if(count>0){
			falt=true;//存在未签章文件
		}
		return  falt;
	}
}