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

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
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.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.modules.workfullmanage.entity.WorkFullRecord;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
import com.jeeplus.modules.workfullmanage.service.WorkFullRecordService;
import com.jeeplus.modules.workreimbursement.utils.VarStr;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 全过程管理项目归档Controller
 * @author mapengbo
 * @version 2017-11-01
 */
@Controller
@RequestMapping(value = "${adminPath}/workfullmanage/workFullRecord")
public class WorkFullRecordController extends BaseController {

	@Autowired
	private WorkFullRecordService workFullRecordService;
	@Autowired
	private WorkFullManageService workFullManageService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private SystemService systemService;
	@Autowired
	protected RuntimeService runtimeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	private ActTaskService actTaskService;
	
	@ModelAttribute
	public WorkFullRecord get(@RequestParam(required=false) String id) {
		WorkFullRecord entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workFullRecordService.get(id);
		}
		if (entity == null){
			entity = new WorkFullRecord();
		}
		return entity;
	}
	
	/**
	 * 项目归档列表页面
	 */
	@RequiresPermissions("workfullmanage:workFullRecord:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkFullManage workFullManage, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!UserUtils.getSelectRoleInfo()){
			String id = UserUtils.getUser().getId();
			workFullManage.setQueryCon(id);
			workFullManage.setMasterId(UserUtils.getUser().getId());
		}
		//查询项目归档的数据
//		workFullManage.setFullProjectStatus("5");
		//添加只查询当前公司的数据  no
		Page<WorkFullManage> page = workFullManageService.findPage(new Page<WorkFullManage>(request, response), workFullManage);
		List<WorkFullManage> list = page.getList();
		for (WorkFullManage workFull:list){
			if(!Strings.isNullOrEmpty(workFull.getHostMaster())){
				String[] split = workFull.getHostMaster().split(",");
				String hostMasterName = workFullManageService.getPeople(split);
				workFull.setHostMasterName(hostMasterName);
			}

			if(!Strings.isNullOrEmpty(workFull.getFollowMaster())){
				String[] split1 = workFull.getFollowMaster().split(",");
				String followMasterName = workFullManageService.getPeople(split1);
				workFull.setFollowMasterName(followMasterName);
			}
			if(!Strings.isNullOrEmpty(workFull.getHostMember())){
				String[] split2 = workFull.getHostMember().split(",");
				String hostMemberName = workFullManageService.getPeople(split2);
				workFull.setHostMemberName(hostMemberName);
			}
			if(!Strings.isNullOrEmpty(workFull.getFollowMember())){
				String[] split3 = workFull.getFollowMember().split(",");
				String followMemberName = workFullManageService.getPeople(split3);
				workFull.setFollowMemberName(followMemberName);
			}
		}
		page.setList(list);
		model.addAttribute("page", page);
		return "modules/workfullmanage/workFullRecordList";
	}

	/**
	 * 查看，增加，编辑项目归档表单页面
	 */
//	@RequiresPermissions(value={"workfullmanage:workFullRecord:view","workfullmanage:workFullRecord:add","workfullmanage:workFullRecord:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkFullRecord workFullRecord, Model model) {
		String view = "workFullRecordForm";
		String tabId = request.getParameter("tabId");
		String manage_id = request.getParameter("manage_id");
		// 环节编号
		String taskDefKey = workFullRecord.getAct().getTaskDefKey();
		if("4".equals(tabId) || StringUtils.isNotBlank(taskDefKey) && workFullRecord.getAct().isFinishTask()
				|| "modifyApply".equals(taskDefKey)){
			WorkFullManage workFullManage = workFullManageService.get(manage_id);
			//查询项目实施阶段的文件信息  还需要查询项目成果文件 no
			List<WorkClientAttachment> workClientAttachments = workFullManageService
					.queryEngeerFile(workFullManage.getCompanyId(), workFullManage.getId());
			model.addAttribute("list",workClientAttachments);
			model.addAttribute("workFullManage",workFullManage);
			view = "projectputsark";
		}
		if("5".equals(tabId)){
			WorkFullManage workFullManage = workFullManageService.get(manage_id);
			//查询项目实施阶段的文件信息  还需要查询项目成果文件 no
			List<WorkClientAttachment> workClientAttachments = workFullManageService
					.queryEngeerFile(workFullManage.getCompanyId(), workFullManage.getId());
			model.addAttribute("list",workClientAttachments);
			model.addAttribute("workFullManage",workFullManage);
			view = "projectputsarkDetail";
		}
		// 修改环节
		else if ("deptLeaderAudit".equals(taskDefKey) ||
				"recordUser".equals(taskDefKey)){
			String enname = UserUtils.getSelectRole().get(0).getEnname();
			if(enname.contains("glygd")){
				model.addAttribute("glygd",true);
			}else{
				model.addAttribute("glygd",false);
			}
			WorkFullManage workFullManage = workFullManageService.get(manage_id);
			WorkFullRecord workFullManageId = workFullRecordService.findUniqueByProperty("work_full_manage_id", manage_id);
			workFullManageId.setRecordName(workFullManage.getFullProjectName());
			workFullManageId.setRecordNumber(workFullManage.getFullProjectNumber());
			model.addAttribute("workFullRecord",workFullManageId);
			model.addAttribute("workFullManage",workFullManage);
			view = "workFullRecordAudit";
		}
		HashMap<Object, Object> map = workFullRecordService.queryWjgly(UserUtils.getSelectCompany().getId(), "glygd");
		if(map != null){
			workFullRecord.setManageUser(map.get("login_name")+"");
			workFullRecord.setManageId(map.get("id")+"");
		}
		model.addAttribute("workFullRecord", workFullRecord);
		return "modules/workfullmanage/"+ view;
	}

	/**
	 * 保存项目归档
	 */
//	@RequiresPermissions(value={"workfullmanage:workFullRecord:add","workfullmanage:workFullRecord:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkFullRecord workFullRecord, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workFullRecord)){
			return form(workFullRecord, model);
		}

		workFullRecord.setType("2"); //存入全过程管理的文档
		if(!workFullRecord.getIsNewRecord()){//编辑表单保存
			WorkFullRecord t = workFullRecordService.get(workFullRecord.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workFullRecord, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workFullRecordService.save(t);//保存
			workFullRecordService.auditSave(workFullRecord, VarStr.BACKRECORD_STATUS,"15");
		}else{//新增表单保存
			WorkFullRecord workFullManageId = workFullRecordService.findUniqueByProperty("work_full_manage_id", workFullRecord.getWorkFullManage().getId());
			if(workFullManageId != null){
				addMessage(redirectAttributes, "项目归档已申请，不能重新申请");
				return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullRecord/?repage";
			}
			workFullRecord.setCompanyId(UserUtils.getSelectCompany().getId());
			workFullRecord.setBackRecordStatus(VarStr.BACKRECORD_STATUS[1]);
			workFullRecordService.save(workFullRecord);//保存
		}
		addMessage(redirectAttributes, "保存项目归档成功");
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullRecord/?repage";
	}

	/**
	 * 启动流程
	 */
//	@RequiresPermissions(value={"workfullmanage:workFullRecord:add","workfullmanage:workFullRecord:edit"},logical=Logical.OR)
	@RequestMapping(value = "startProcess")
	public String startProcess(WorkFullRecord workFullRecord, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workFullRecord)){
			return form(workFullRecord, model);
		}
		String engineeringId = request.getParameter("engineeringId");
		Role role = UserUtils.getSelectRole().get(0);
		StringBuffer buffer = DateUtils.getByEnnme(role.getEnname());
		Map<String, Object> variables = Maps.newHashMap();
		variables.put("SSRHbmzr", buffer.toString() + "bmzr"); //设置部门负责人
		variables.put("recordUser",buffer.toString() + "glygd");
		workFullRecord.setType("2"); //存入全过程管理的文档
		if(!workFullRecord.getIsNewRecord()){//编辑表单保存
			addMessage(redirectAttributes, "归档已存在");
			return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullRecord/?repage";
		}else{//新增表单保存
			WorkFullRecord workFullManageId = workFullRecordService.findUniqueByProperty("work_full_manage_id",engineeringId);
			if(workFullManageId != null){
				addMessage(redirectAttributes, "项目归档流程已申请，不能重新申请");
				return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullRecord/?repage";
			}
			workFullRecord.preInsert();
			workFullRecord.setCompanyId(UserUtils.getSelectCompany().getId());
			workFullRecord.setBackRecordStatus(VarStr.BACKRECORD_STATUS[1]);
			workFullRecord.setWorkFullManage(new WorkFullManage(engineeringId));
			workFullRecordService.startposs(workFullRecord,variables,true,"15",buffer.append("bmzr").toString());//保存
		}
		addMessage(redirectAttributes, "启动项目归档流程成功");
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullRecord/?repage";
	}
	
	/**
	 * 删除项目归档
	 */
//	@RequiresPermissions("workfullmanage:workFullRecord:del")
	@RequestMapping(value = "delete")
	public String delete(WorkFullRecord workFullRecord, RedirectAttributes redirectAttributes) {
		workFullRecordService.delete(workFullRecord);
		addMessage(redirectAttributes, "删除项目归档成功");
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullRecord/?repage";
	}
	
	/**
	 * 批量删除项目归档
	 */
//	@RequiresPermissions("workfullmanage:workFullRecord:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workFullRecordService.delete(workFullRecordService.get(id));
		}
		addMessage(redirectAttributes, "删除项目归档成功");
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullRecord/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
//	@RequiresPermissions("workfullmanage:workFullRecord:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkFullRecord workFullRecord, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "项目归档"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkFullRecord> page = workFullRecordService.findPage(new Page<WorkFullRecord>(request, response, -1), workFullRecord);
    		new ExportExcel("项目归档", WorkFullRecord.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出项目归档记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullRecord/?repage";
    }

	/**
	 * 导入Excel数据

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

	/**
	 * 查询待办列表
	 * @return
	 */

	@RequestMapping("/queryToList")
	public String queryToList(Act act,Model model){
		act.setProcDefKey("workfullrecord");
		List<Act> list = actTaskService.todoList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<WorkFullRecord> lists = new ArrayList<WorkFullRecord>();

		Role role = UserUtils.getSelectRole().get(0);
		String officeId = "";
		if ("4".equals(role.getDataScope())){
			User user = UserUtils.getUser();
			officeId = user.getOffice().getId();
		}
		for (Act a : list) {
			WorkFullRecord workFullRecord = workFullRecordService.getByProcessInstanceId(a.getProcInsId());
			if (workFullRecord != null && workFullRecord.getCompanyId().equals(companyId)) {
				workFullRecord.setCreateBy(UserUtils.get(workFullRecord.getCreateBy().getId()));
				User createBy = UserUtils.get(workFullRecord.getCreateBy().getId());
				if (StringUtils.isNotBlank(officeId)) {
					if (officeId.equals(createBy.getOffice().getId())) {
						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());
							}
						}
						workFullRecord.setAct(a);
						lists.add(workFullRecord);
					}
				}else{
					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());
						}
					}
					workFullRecord.setAct(a);
					lists.add(workFullRecord);
				}
			}
		}
		Role role1 = UserUtils.getSelectRole().get(0);
		if(role1.getEnname().endsWith("glygd")){
			model.addAttribute("flag","1");
		}
		model.addAttribute("list", lists);
		return "modules/workfullmanage/recordTodoList";
	}

	/**
	 * 查询已办列表
	 * @return
	 */
	@RequestMapping("/queryCompleteList")
	public String queryCompleteList(Act act,Model model){
		act.setProcDefKey("workfullrecord");
		List<WorkFullRecord> page = workFullRecordService.historicList(act);
		model.addAttribute("list",page);
		return "modules/workfullmanage/recordHistoricList";
	}

	/**
	 * 审核信息
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnLeave")
	public String applyOnCompany(Act act, HttpServletResponse response, Model model) {
		String manage_id = request.getParameter("manage_id");
		// 获取流程XML上的表单KEY
		String formkey = "//workfullmanage/workFullRecord/form?manage_id="+manage_id;
//		String formKey = actTaskService.getFormKey(act.getProcDefId(), act.getTaskDefKey());
		// 获取流程实例对象
		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 model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkFullRecord workFullRecord, Model model, RedirectAttributes redirectAttributes) {
		/*if (StringUtils.isBlank(workFullRecord.getAct().getFlag())
				|| StringUtils.isBlank(workFullRecord.getAct().getComment())){
			addMessage(model, "请填写审核意见。");
			return form(workFullRecord, model);
		}*/
		String type = "15";
		workFullRecordService.auditSave(workFullRecord, VarStr.BACKRECORD_STATUS,type);
		return "redirect:" + adminPath +"/workfullmanage/workFullRecord/?repage";
	}

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