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

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.jeeplus.common.mapper.JsonMapper;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringEscapeUtils;
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.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
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.workcontractrecord.entity.WorkContractRecord;
import com.jeeplus.modules.workcontractrecord.service.WorkContractRecordService;

/**
 * 合同归档Controller
 * @author lw
 * @version 2018-06-08
 */
@Controller
@RequestMapping(value = "${adminPath}/workcontractrecord/workContractRecord")
public class WorkContractRecordController extends BaseController {

	@Autowired
	private WorkContractRecordService workContractRecordService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkContractInfoService workContractInfoService;
	@ModelAttribute
	public WorkContractRecord get(@RequestParam(required=false) String id) {
		WorkContractRecord entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workContractRecordService.get(id);
		}
		if (entity == null){
			entity = new WorkContractRecord();
		}
		return entity;
	}
	
	/**
	 * 合同归档列表页面
	 */
	@RequiresPermissions("workcontractrecord:workContractRecord:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkContractRecord workContractRecord, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkContractRecord> page = workContractRecordService.findPage(new Page<WorkContractRecord>(request, response), workContractRecord); 
		model.addAttribute("page", page);
		return "modules/workcontractrecord/workContractRecordList";
	}

	/**
	 * 查看，增加，编辑合同归档表单页面
	 */
	//@RequiresPermissions(value={"workcontractrecord:workContractRecord:view","workcontractrecord:workContractRecord:add","workcontractrecord:workContractRecord:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkContractRecord workContractRecord, Model model) {
		String view = "workContractRecordForm";
		Office office = UserUtils.getSelectOffice();
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workContractView";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workContractRecord.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);
				workContractRecord.setAct(act);
				view = "workContractRecordModifyApply";
			}
		}if("4".equals(tabId)){
			WorkContractInfo workContractInfo=workContractInfoService.get(workContractRecord.getId());
			workContractRecord.setWorkContractInfo(workContractInfo);
			workContractRecord.setId(null);
			view = "workContractRecordForm";
		}
		// 环节编号
		String taskDefKey = workContractRecord.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && ("htgdgly".equals(taskDefKey))){
			view = "workContractRecordAudit";
		}
		if(StringUtils.isBlank(workContractRecord.getId())){
			workContractRecord.setCreateBy(UserUtils.getUser());
			workContractRecord.setCreateDate(new Date());
		}
		model.addAttribute("workContractRecord", workContractRecord);
		return "modules/workcontractrecord/"+view;
	}
	/**
	 * 暂存
	 */
	@RequestMapping(value = "store")
	public String store(WorkContractRecord workContractRecord,
						Model model,
						RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workContractRecord)){
			return form(workContractRecord, model);
		}
		//归档中状态
		if(workContractRecord.getWorkContractInfo()!=null){
			if(StringUtils.isNotBlank(workContractRecord.getWorkContractInfo().getId())){
				WorkContractInfo workContractInfo = workContractInfoService.get(workContractRecord.getWorkContractInfo().getId());
				workContractInfo.setRecordState("2");
				workContractInfoService.save(workContractInfo);
			}
		}
		User user = workContractRecord.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		String sta = workContractRecord.getStatus();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter) && sta != null){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workcontractrecord/workContractRecord/?repage";
		}
		workContractRecord.setStatus("1"); //暂存状态
		workContractRecord.setCompanyId(UserUtils.getSelectCompany().getId());
		workContractRecord.setOfficeId(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(workContractRecord.getProcessInstanceId()) && workContractRecord.getProcessInstanceId().equals("NULL")){
			workContractRecord.setProcessInstanceId("");
		}
		if(!workContractRecord.getIsNewRecord()){//编辑表单保存
			WorkContractRecord t = workContractRecordService.get(workContractRecord.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workContractRecord, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workContractRecordService.save(t);//保存
		}else{//新增表单保存
			workContractRecordService.save(workContractRecord);//保存
		}
		addMessage(redirectAttributes, "保存合同归档成功");
		return "redirect:"+Global.getAdminPath()+"/workcontractrecord/workContractRecord/?repage";
	}
	/**
	 * 保存合同归档
	 */
	@RequiresPermissions(value={"workcontractrecord:workContractRecord:add","workcontractrecord:workContractRecord:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkContractRecord workContractRecord, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workContractRecord)){
			return form(workContractRecord, model);
		}
		//归档中状态
		if(workContractRecord.getWorkContractInfo()!=null){
			if(StringUtils.isNotBlank(workContractRecord.getWorkContractInfo().getId())){
				WorkContractInfo workContractInfo = workContractInfoService.get(workContractRecord.getWorkContractInfo().getId());
				workContractInfo.setRecordState("2");
				workContractInfoService.save(workContractInfo);
			}
		}
		User user = workContractRecord.getCreateBy();
		String sta = workContractRecord.getStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workcontractrecord/workContractRecord/?repage";
		}
		//状态设置为审核中
		workContractRecord.setStatus("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workContractRecordService.get(workContractRecord.getId()).getProcessInstanceId();
		}
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workContractRecord.setCompanyId(UserUtils.getSelectCompany().getId());
			workContractRecord.setOfficeId(UserUtils.getSelectOffice().getId());
			String str = workContractRecordService.save(workContractRecord, variables,processInstanceId);
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "合同归档申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "合同归档申请已经提交");
			}

		} catch (Exception e) {
			addMessage(redirectAttributes, "合同归档申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/workcontractrecord/workContractRecord/?repage";
	}
	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkContractRecord workContractRecord, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			List<User> users = UserUtils.getByProssType(workContractRecord.getProcessInstanceId(),1);
			String flag = workContractRecord.getAct().getFlag();
			if ("yes".equals(flag) && (users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = workContractRecordService.auditSave(workContractRecord,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			addMessage(redirectAttributes, "审批失败");
		}

		if (StringUtils.isNotBlank(workContractRecord.getHome()) && "home".equals(workContractRecord.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			return "redirect:"+Global.getAdminPath()+"/workcontractrecord/workContractRecord/?repage";
		}
	}
	/**
	 * 删除合同归档
	 */
	@RequiresPermissions("workcontractrecord:workContractRecord:del")
	@RequestMapping(value = "delete")
	public String delete(WorkContractRecord workContractRecord, RedirectAttributes redirectAttributes) {
		workContractRecordService.delete(workContractRecord);
		addMessage(redirectAttributes, "删除合同归档成功");
		return "redirect:"+Global.getAdminPath()+"/workcontractrecord/workContractRecord/?repage";
	}
	
	/**
	 * 批量删除合同归档
	 */
	@RequiresPermissions("workcontractrecord:workContractRecord:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workContractRecordService.delete(workContractRecordService.get(id));
		}
		addMessage(redirectAttributes, "删除合同归档成功");
		return "redirect:"+Global.getAdminPath()+"/workcontractrecord/workContractRecord/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workcontractrecord:workContractRecord:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkContractRecord workContractRecord, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "合同归档"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkContractRecord> page = workContractRecordService.findPage(new Page<WorkContractRecord>(request, response, -1), workContractRecord);
    		new ExportExcel("合同归档", WorkContractRecord.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出合同归档记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workcontractrecord/workContractRecord/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workcontractrecord:workContractRecord: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<WorkContractRecord> list = ei.getDataList(WorkContractRecord.class);
			for (WorkContractRecord workContractRecord : list){
				try{
					workContractRecordService.save(workContractRecord);
					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()+"/workcontractrecord/workContractRecord/?repage";
    }
	
	/**
	 * 下载导入合同归档数据模板
	 */
	@RequiresPermissions("workcontractrecord:workContractRecord:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "合同归档数据导入模板.xlsx";
    		List<WorkContractRecord> list = Lists.newArrayList(); 
    		new ExportExcel("合同归档数据", WorkContractRecord.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workcontractrecord/workContractRecord/?repage";
    }
	
	
	/**
	 * 选择合同
	 */
	@RequestMapping(value = "selectworkContractInfo")
	public String selectworkContractInfo(WorkContractInfo workContractInfo, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		workContractInfo.setCompanyId(UserUtils.getSelectCompany().getId());
		Page<WorkContractInfo> page = workContractRecordService.findPageByworkContractInfo(new Page<WorkContractInfo>(request, response),  workContractInfo);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", workContractInfo);
		model.addAttribute("page", page);
		return "modules/sys/gridselectrecord";
	}

	/**
	 * 强制撤销
	 */
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkContractRecord workContractRecord,RedirectAttributes redirectAttributes){
		workContractRecordService.cancelInvalidate(workContractRecord);
		return "redirect:"+Global.getAdminPath()+"/workcontractrecord/workContractRecord/?repage";
	}
	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkContractRecord workContractRecord,Model model) {
		model.addAttribute("processInstanceId", workContractRecord.getProcessInstanceId());
		return "modules/workcontractrecord/workTrack";
	}
	//获取合同
	@RequestMapping(value = "getPNumberr")
	@ResponseBody
	public String getPNumberr() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		WorkContractInfo workContractInfo = workContractInfoService.get(obj);
		if(StringUtils.isNotBlank(workContractInfo.getContractNum())){
			String recordNum = workContractRecordService.findRecordNum(workContractInfo.getContractNum());
			if(StringUtils.isBlank(recordNum)){
				map.put("recordNum",workContractInfo.getContractNum()+"-1");
			}else{
				map.put("recordNum",recordNum);
			}
		}else{
			map.put("recordNum","-合同HT-2018-00000-1");
		}
		map.put("contractNum",workContractInfo.getContractNum());
		if(workContractInfo.getClient()!=null){
			map.put("cName",workContractInfo.getClient().getName());
		}
		String a= workContractInfo.getContractType();
		map.put("contractType",DictUtils.getMainDictLabel(workContractInfo.getContractType(),"contract_type",""));
		return JsonMapper.toJsonString(map);
	}
}