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

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.dao.RoleDao;
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.entity.Workattachment;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.service.WorkattachmentService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
import com.jeeplus.modules.workengineeringproject.entity.WorkEngineeringProject;
import com.jeeplus.modules.workengineeringproject.service.WorkEngineeringProjectService;
import com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.modules.workfullmanage.entity.WorkFullRecord;
import com.jeeplus.modules.workfullmanage.service.WorkFullRecordService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workreimbursement.utils.VarStr;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
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.jdbc.core.namedparam.NamedParameterUtils;
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.List;
import java.util.Map;

/**
 * 工程项目信息Controller
 * @author 杨帆
 * @version 2017-10-23
 */
@Controller
@RequestMapping(value = "${adminPath}/engineeringrecord/engineeringrecord")
public class WorkEngineeringRecordController extends BaseController {

	@Autowired
	private WorkEngineeringProjectService workEngineeringProjectService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private WorkContractInfoService workContractInfoService;
	@Autowired
	private WorkClientInfoService workClientInfoService;
	@Autowired
	protected RuntimeService runtimeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;
	@Autowired
	private WorkattachmentService workattachmentService;
	@Autowired
	private WorkFullRecordService workFullRecordService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private SystemService systemService;

	@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("engineeringrecord:engineeringrecord:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkEngineeringProject workEngineeringProject, HttpServletRequest request, HttpServletResponse response, Model model) {
		//只是普通员工
		if(!UserUtils.getSelectRoleInfo()){
			String id = UserUtils.getUser().getId();
			workEngineeringProject.setQueryCon(id);
		}
		Page<WorkEngineeringProject> page = workEngineeringProjectService.findPage(new Page<WorkEngineeringProject>(request, response), workEngineeringProject);
		List<WorkEngineeringProject> list = page.getList();
		for (WorkEngineeringProject entity :list){
			String hostOfficeMaster = entity.getHostOfficeMaster();
			if (StringUtils.isNotBlank(hostOfficeMaster)){
				String[] ids = hostOfficeMaster.split(",");
				String name = "";
				for (String str:ids) {
					User user = UserUtils.get(str);
					name += user.getName()+",";
				}
				if (StringUtils.isNotBlank(name)){
					name = name.substring(0,name.length() - 1);
				}
				entity.setHostOfficeMasterName(name);
			}
		}
		model.addAttribute("page", page);
		model.addAttribute("name", false);
		model.addAttribute("glygd", false);
		return "modules/workengineeringproject/workEngineeringRecordList";
	}

	/**
	 * 查看，增加，编辑项目归档表单页面
	 */
	@RequestMapping(value = "form")
	public String form(WorkFullRecord workFullRecord, Model model, RedirectAttributes redirectAttributes) {
		String view = "workEngineeringRecordForm";
		String tabId = request.getParameter("tabId");
		String engineeringId = request.getParameter("engineeringId");
		WorkEngineeringProject workEngineeringProject = workEngineeringProjectService.get(engineeringId);
		workFullRecord.setWorkEngineeringProject(workEngineeringProject);

		List<Workattachment> workReportList = workattachmentService.findAttachment(workEngineeringProject.getId(),"39");
		List<Workattachment> workBasisInformationList = workattachmentService.findAttachment(workEngineeringProject.getId(),"40");
		List<Workattachment> workRemoteControlList = workattachmentService.findAttachment(workEngineeringProject.getId(),"41");
		List<Workattachment> workSummaryList = workattachmentService.findAttachment(workEngineeringProject.getId(),"42");
		List<Workattachment> workOtherList = workattachmentService.findAttachment(workEngineeringProject.getId(),"43");
		model.addAttribute("workEngineeringProject", workEngineeringProject);
		model.addAttribute("workReportList", workReportList);
		model.addAttribute("workBasisInformationList", workBasisInformationList);
		model.addAttribute("workRemoteControlList", workRemoteControlList);
		model.addAttribute("workSummaryList", workSummaryList);
		model.addAttribute("workOtherList", workOtherList);
		// 环节编号
		String taskDefKey = workFullRecord.getAct().getTaskDefKey();
		Act act = workFullRecord.getAct();
		WorkFullRecord workFullManageId = workFullRecordService.findUniqueByProperty("work_full_manage_id", engineeringId);
		if(workFullManageId!=null){
			workFullRecord = workFullRecordService.getById(workFullManageId.getId());
			workFullRecord.setAct(act);
		}
		workEngineeringProject.setWorkFullRecord(workFullRecord);
		workFullRecord.setRecordName(workEngineeringProject.getProjectId().getName());
		workFullRecord.setRecordNumber(workEngineeringProject.getProjectId().getNumber());
		if(workFullRecord!=null && StringUtils.isNotBlank(workFullRecord.getManageUser())) {
			workFullRecord.setManageId(UserUtils.get(workFullRecord.getManageUser()).getName());
		}
		model.addAttribute("workFullRecord", workFullRecord);
		if("4".equals(tabId) || StringUtils.isNotBlank(taskDefKey) && workFullRecord.getAct().isFinishTask()
				){
			model.addAttribute("workEngineeringProject",workEngineeringProject);
			view = "workEngineeringRecordForm";
		}
		// 修改环节
		else if ("deptLeaderAudit".equals(taskDefKey) ||
				"recordUser".equals(taskDefKey)|| "modifyApply".equals(taskDefKey)){
			Role role = UserUtils.getSelectRole().get(0);
			model.addAttribute("glygd",role.getEnname().contains("glygd")?true:false);
			view = "workEngineeringRecordAudit";
		}
		if("10".equals(tabId)){
			view = "workEngineeringRecordView";
		}
		return "modules/workengineeringproject/" + view;
	}

	/**
	 * 保存项目归档
	 */
	@RequestMapping(value = "startposs")
	public String startposs(WorkFullRecord workFullRecord, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workFullRecord)){
			return form(workFullRecord, model,redirectAttributes);
		}
		String engineeringId = request.getParameter("engineeringId");
		Map<String, Object> variables = Maps.newHashMap();
		Role role = UserUtils.getSelectRole().get(0);
		StringBuffer buffer = DateUtils.getByEnnme(role.getEnname());
		StringBuffer gly = DateUtils.getByEnnme(role.getEnname());

		buffer.append("bmzr");
		gly.append("glygd");
		variables.put("bmzr", buffer.toString()); //设置部门负责人
		variables.put("gly", gly.toString()); //设置部门负责人
		if(!workFullRecord.getIsNewRecord()){//编辑表单保存
			addMessage(redirectAttributes, "归档已存在!");
			return "redirect:"+Global.getAdminPath()+"/engineeringrecord/engineeringrecord/?repage";
		}else{//新增表单保存
			WorkFullRecord workFullManageId = workFullRecordService.findUniqueByProperty("work_full_manage_id", engineeringId);
			if(workFullManageId != null){
				addMessage(redirectAttributes, "项目归档已申请，不能重新申请");
				return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullRecord/?repage";
			}else {
				workFullManageId = new WorkFullRecord();
			}
			workFullManageId.preInsert();
			WorkEngineeringProject workEngineeringProject = workEngineeringProjectService.get(engineeringId);
			workFullManageId.setCompanyId(UserUtils.getSelectCompany().getId());
			workFullManageId.setType("1");
			workFullManageId.setWorkFullManage(new WorkFullManage(engineeringId));
			workFullManageId.setBackRecordStatus(VarStr.BACKRECORD_STATUS[1]);
			workFullManageId.setStartTime(workEngineeringProject.getWorkStartDate());
			workFullManageId.setEndTime(workEngineeringProject.getWorkEndDate());
			workFullManageId.setRecordName(workEngineeringProject.getProjectId().getName());
			workFullManageId.setRecordNumber(workEngineeringProject.getProjectId().getNumber());
			Role r = new Role();
			r.setEnname(gly.toString());
			r.setCompany(UserUtils.getSelectCompany());
			r.setOffice(UserUtils.getSelectOffice());
			Role rolegd =  roleDao.getByEnname(r);
			List<User> userList = systemService.findUser(new User(new Role(rolegd.getId())));
			workFullManageId.setManageUser(userList==null||userList.size()==0?"":userList.get(0).getId());
			workFullRecordService.startposs(workFullManageId,variables,false,"4",buffer.toString());//保存
		}
		addMessage(redirectAttributes, "保存项目归档成功");
		return "redirect:"+Global.getAdminPath()+"/engineeringrecord/engineeringrecord/?repage";
	}

	/**
	 * 保存项目归档
	 */
	@RequestMapping(value = "save")
	public String save(WorkFullRecord workFullRecord, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workFullRecord)){
			return form(workFullRecord, model,redirectAttributes);
		}
		if(!workFullRecord.getIsNewRecord()){//编辑表单保存
			WorkFullRecord t = workFullRecordService.get(workFullRecord.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workFullRecord, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workFullRecordService.save(t);//保存
		}else{//新增表单保存
			WorkFullRecord workFullManageId = workFullRecordService.findUniqueByProperty("work_full_manage_id", workFullRecord.getWorkEngineeringProject().getId());
			if(workFullManageId != null){
				addMessage(redirectAttributes, "项目归档已申请，不能重新申请");
				return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullRecord/?repage";
			}
			WorkEngineeringProject workEngineeringProject = workEngineeringProjectService.get(workFullRecord.getWorkEngineeringProject().getId());
			workFullRecord.setCompanyId(UserUtils.getSelectCompany().getId());
			workFullRecord.setType("1");
			workFullRecord.setWorkFullManage(new WorkFullManage(workFullRecord.getWorkEngineeringProject().getId()));
			workFullRecord.setBackRecordStatus(VarStr.BACKRECORD_STATUS[1]);
			workFullRecord.setStartTime(workEngineeringProject.getWorkStartDate());
			workFullRecord.setEndTime(workEngineeringProject.getWorkEndDate());
			workFullRecord.setRecordName(workEngineeringProject.getProjectId().getName());
			workFullRecord.setRecordNumber(workEngineeringProject.getProjectId().getName());
			workFullRecordService.save(workFullRecord);//保存
		}
		addMessage(redirectAttributes, "保存项目归档成功");
		return "redirect:"+Global.getAdminPath()+"/engineeringrecord/engineeringrecord/?repage";
	}

	/**
	 * 删除项目归档
	 */
	@RequestMapping(value = "delete")
	public String delete(WorkFullRecord workFullRecord, RedirectAttributes redirectAttributes) {
		workFullRecordService.delete(workFullRecord);
		addMessage(redirectAttributes, "删除项目归档成功");
		return "redirect:"+Global.getAdminPath()+"/engineeringrecord/engineeringrecord/?repage";
	}

	/**
	 * 批量删除项目归档
	 */
	@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()+"/engineeringrecord/engineeringrecord/?repage";
	}

	/**
	 * 导出excel文件
	 */
	@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()+"/engineeringrecord/engineeringrecord/?repage";
	}

	/**
	 * 导入Excel数据

	 */
	@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()+"/engineeringrecord/engineeringrecord/?repage";
	}

	/**
	 * 下载导入项目归档数据模板
	 */
	@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()+"/engineeringrecord/engineeringrecord/?repage";
	}

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

	@RequestMapping("/queryToList")
	public String queryToList(Act act,Model model){
		act.setProcDefKey("engineeringrecord");
		List<Act> list = actTaskService.todoList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<WorkFullRecord> lists = new ArrayList<WorkFullRecord>();
		for (Act a : list) {
			WorkFullRecord workFullRecord = workFullRecordService.getByProcessInstanceId(a.getProcInsId());
			if (workFullRecord!=null && StringUtils.isNotBlank(workFullRecord.getManageUser())) {
				workFullRecord.setManageId(UserUtils.get(workFullRecord.getManageUser()).getName());
			}
			if (workFullRecord != null && workFullRecord.getCompanyId().equals(companyId) && workFullRecord.getBackRecordStatus() !=null && !workFullRecord.getBackRecordStatus().equals("3")) {
				workFullRecord.setCreateBy(UserUtils.get(workFullRecord.getCreateBy().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);
			}
		}
		model.addAttribute("list", lists);
		return "modules/workengineeringproject/recordTodoList";
	}

	/**
	 * 查询已办列表
	 * @return
	 */
	@RequestMapping("/queryCompleteList")
	public String queryCompleteList(Act act,Model model){
		act.setProcDefKey("engineeringrecord");
		List<WorkFullRecord> page = workFullRecordService.historicList(act);
		for (WorkFullRecord workFullRecord : page){
			if (workFullRecord!=null && StringUtils.isNotBlank(workFullRecord.getManageUser())) {
				workFullRecord.setManageId(UserUtils.get(workFullRecord.getManageUser()).getName());
			}
		}
		model.addAttribute("list",page);
		return "modules/workengineeringproject/recordHistoricList";
	}

	/**
	 * 审核信息
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnRecord")
	public String applyOnRecord(Act act, HttpServletResponse response, Model model) {
		String engineeringId = request.getParameter("engineeringId");
		// 获取流程XML上的表单KEY
		String formkey = "/engineeringrecord/engineeringrecord/form?engineeringId="+engineeringId;
//		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,redirectAttributes);
		}*/
		String type = "4";
		workFullRecordService.auditSave(workFullRecord, VarStr.BACKRECORD_STATUS,type);
		Role role = UserUtils.getSelectRole().get(0);
		if(role.getEnname().contains("glygd")) {
			workFullRecordService.save(workFullRecord);
		}
		addMessage(redirectAttributes, "项目归档流程已审批！");
		return "redirect:" + adminPath +"/engineeringrecord/engineeringrecord/?repage";
	}

	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(String engineeringId, Model model) {
		WorkFullRecord workFullManageId = workFullRecordService.findUniqueByProperty("work_full_manage_id", engineeringId);
		String processInstanceId = "";
		if (workFullManageId!=null){
			processInstanceId = workFullManageId.getProcessInstanceId();
		}
		model.addAttribute("processInstanceId", processInstanceId);
		return "modules/workengineeringproject/workRecordTrack";
	}

}