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

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.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.projectcontentinfo.entity.ProjectReportData;
import com.jeeplus.modules.projectcontentinfo.entity.Projectcontentinfo;
import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
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.projectcontentinfo.entity.ProjectReportRecord;
import com.jeeplus.modules.projectcontentinfo.service.ProjectReportRecordService;

/**
 * 报告归档Controller
 * @author 杨帆
 * @version 2018-06-22
 */
@Controller
@RequestMapping(value = "${adminPath}/projectcontentinfo/projectReportRecord")
public class ProjectReportRecordController extends BaseController {

	@Autowired
	private ProjectReportRecordService projectReportRecordService;
	@Autowired
	private ActTaskService actTaskService;

	@ModelAttribute
	public ProjectReportRecord get(@RequestParam(required=false) String id) {
		ProjectReportRecord entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = projectReportRecordService.get(id);
		}
		if (entity == null){
			entity = new ProjectReportRecord();
		}
		return entity;
	}
	
	/**
	 * 报告归档列表页面
	 */
	@RequiresPermissions("projectcontentinfo:projectReportRecord:list")
	@RequestMapping(value = {"list", ""})
	public String list(ProjectReportRecord projectReportRecord, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ProjectReportRecord> page = projectReportRecordService.findPage(new Page<ProjectReportRecord>(request, response), projectReportRecord); 
		model.addAttribute("page", page);
		return "modules/projectcontentinfo/projectReportRecordList";
	}

	/**
	 * 查看，增加，编辑报告归档表单页面
	 */
	@RequestMapping(value = "form")
	public String form(ProjectReportRecord projectReportRecord, Model model) {
		if(StringUtils.isBlank(projectReportRecord.getId())){
			projectReportRecord.setCreateDate(new Date());
			projectReportRecord.setCreateBy(UserUtils.getUser());
		}
		model.addAttribute("projectReportRecord", projectReportRecord);
		if (StringUtils.isNotBlank(projectReportRecord.getView()) && projectReportRecord.getView().equals("view")){
			return "modules/projectcontentinfo/projectReportRecordView";
		}else if (StringUtils.isNotBlank(projectReportRecord.getView()) && projectReportRecord.getView().equals("modiftApply")){
			ProcessInstance processInstance = actTaskService.getProcIns(projectReportRecord.getProcessInstanceId());
			if (processInstance!=null) {
				Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
				Act act = new Act();
				act.setTaskId(taskInfok.getId());
				act.setTaskName(taskInfok.getName());
				act.setProcDefId(taskInfok.getProcessDefinitionId());
				act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
				act.setProcInsId(taskInfok.getProcessInstanceId());
				act.setTask(taskInfok);
				projectReportRecord.setAct(act);
			}
			return "modules/projectcontentinfo/projectReportRecordModiftApply";
		}
		return "modules/projectcontentinfo/projectReportRecordForm";
	}

	/**
	 * 保存报告归档
	 */
	@RequestMapping(value = "save")
	public String save(ProjectReportRecord projectReportRecord, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, projectReportRecord)){
			return form(projectReportRecord, model);
		}
		try {
			User user = projectReportRecord.getCreateBy();
			String sta = projectReportRecord.getStatus();
			if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
				addMessage(redirectAttributes, "您不是申请人，无法修改");
				return "redirect:"+Global.getAdminPath()+"/workreimbursement/workReimbursement/?repage";
			}
			//状态设置为审核中
			projectReportRecord.setStatus("2");
			String processInstanceId ="";
			if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
				processInstanceId = projectReportRecordService.get(projectReportRecord.getId()).getProcessInstanceId();
			}
			Map<String, Object> variables = new HashMap<>();
			if(!projectReportRecord.getIsNewRecord()){//编辑表单保存
				ProjectReportRecord t = projectReportRecordService.get(projectReportRecord.getId());//从数据库取出记录的值
				MyBeanUtils.copyBeanNotNull2Bean(projectReportRecord, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
				projectReportRecordService.save(projectReportRecord,variables,processInstanceId);//保存
			}else {//新增表单保存
				projectReportRecordService.save(projectReportRecord,variables,processInstanceId);//保存
			}

			addMessage(redirectAttributes, "保存报告归档成功");
		}catch (Exception e){
			addMessage(redirectAttributes, "保存报告归档失败");
		}
		return "redirect:"+Global.getAdminPath()+"/projectcontentinfo/projectReportRecord/?repage";
	}
	/**
	 * 保存报告归档
	 */
	@RequestMapping(value = "store")
	public String store(ProjectReportRecord projectReportRecord, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, projectReportRecord)){
			return form(projectReportRecord, model);
		}
		if(!projectReportRecord.getIsNewRecord()){//编辑表单保存
			ProjectReportRecord t = projectReportRecordService.get(projectReportRecord.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(projectReportRecord, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			projectReportRecordService.save(t);//保存
		}else{//新增表单保存
			User user = UserUtils.getUser();
			projectReportRecord.setCompanyId(user.getComId());
			projectReportRecord.setOfficeId(user.getOffice().getId());
			projectReportRecord.setStatus("1");
			projectReportRecordService.save(projectReportRecord);//保存
		}
		addMessage(redirectAttributes, "保存报告归档成功");
		return "redirect:"+Global.getAdminPath()+"/projectcontentinfo/projectReportRecord/?repage";
	}
	/**
	 * 保存报告归档
	 */
	@RequestMapping(value = "getNumber")
	@ResponseBody
	public Map<String,Object> getNumber(@RequestParam(required=false) String reportId, Model model, RedirectAttributes redirectAttributes) throws Exception{
		Map<String,Object> map = new HashMap<>();
		try {
			int count = projectReportRecordService.getNumber(reportId);
			map.put("numberCount",count>9?count+"":"0"+count);
		}catch (Exception e){
			logger.error("Exception e"+e);
			map.put("numberCount","01");
		}
		return map;
	}

	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(ProjectReportRecord projectReportRecord,Model model) {
		model.addAttribute("processInstanceId", projectReportRecord.getProcessInstanceId());
		return "modules/workreimbursement/workReimbursementTrack";
	}

	//报告流程审批
	@RequestMapping(value = {"auditSave"})
	public String auditSave(ProjectReportRecord projectReportRecord, HttpServletRequest request, HttpServletResponse response, Model model,
							  RedirectAttributes redirectAttributes) {
		try {
			// 对不同环节的业务逻辑进行操作
			List<User> users = UserUtils.getByProssType(projectReportRecord.getProcessInstanceId(),1);
			String flag = projectReportRecord.getAct().getFlag();
			if ("yes".equals(flag) && (users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = projectReportRecordService.auditSave(projectReportRecord,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			logger.error("Exception e:"+e);
			addMessage(redirectAttributes, "报告归档流程审批失败");
		}
		if (StringUtils.isNotBlank(projectReportRecord.getHome()) && projectReportRecord.getHome().equals("home")){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			//报告变更
			Page<ProjectReportRecord> page = projectReportRecordService.findPage(new Page<ProjectReportRecord>(request, response), projectReportRecord);
			model.addAttribute("page", page);
			return "modules/projectcontentinfo/projectReportRecordList";
		}
	}

	/**
	 * 删除报告归档
	 */
	@RequestMapping(value = "delete")
	public String delete(ProjectReportRecord projectReportRecord, RedirectAttributes redirectAttributes) {
		try {
			String sta = projectReportRecord.getStatus();
			if("5".equals(sta)){
				addMessage(redirectAttributes, "报告归档已归档，无法删除");
				return "redirect:"+Global.getAdminPath()+"/projectcontentinfo/projectReportRecord/?repage";
			}else if("2".equals(sta)){
				addMessage(redirectAttributes, "报告归档正在审核中，无法删除");
				return "redirect:"+Global.getAdminPath()+"/projectcontentinfo/projectReportRecord/?repage";
			}
			projectReportRecordService.delete(projectReportRecord);
			addMessage(redirectAttributes, "删除报告归档成功");
		}catch (Exception e){
				addMessage(redirectAttributes, "删除报告归档失败");
		}
		return "redirect:"+Global.getAdminPath()+"/projectcontentinfo/projectReportRecord/?repage";
	}

	/**
	 * 报告归档：强制撤回
	 */
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(ProjectReportRecord projectReportRecord,RedirectAttributes redirectAttributes){
		try {
			if(projectReportRecord.getStatus().equals("5")){
				addMessage(redirectAttributes, "报告归档已审批通过，无法撤回");
			}else{
				projectReportRecordService.cancelInvalidate(projectReportRecord);
				addMessage(redirectAttributes, "强制撤回报告归档成功");
			}
		}catch (Exception e){
			addMessage(redirectAttributes, "强制撤回报告归档失败");
		}
		return "redirect:"+Global.getAdminPath()+"/projectcontentinfo/projectReportRecord/?repage";
	}

	/**
	 * 批量删除报告归档
	 */
	@RequiresPermissions("projectcontentinfo:projectReportRecord:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			projectReportRecordService.delete(projectReportRecordService.get(id));
		}
		addMessage(redirectAttributes, "删除报告归档成功");
		return "redirect:"+Global.getAdminPath()+"/projectcontentinfo/projectReportRecord/?repage";
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("projectcontentinfo:projectReportRecord:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(ProjectReportRecord projectReportRecord, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "报告归档"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ProjectReportRecord> page = projectReportRecordService.findPage(new Page<ProjectReportRecord>(request, response, -1), projectReportRecord);
    		new ExportExcel("报告归档", ProjectReportRecord.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出报告归档记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/projectcontentinfo/projectReportRecord/?repage";
    }

	/**
	 * 导入Excel数据

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

}