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

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
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.ActAuditService;
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.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workreimbur.entity.WorkReimbur;
import com.jeeplus.modules.workreimbur.service.WorkReimburService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
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.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 fgy
 * @version 2018-01-19
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "${adminPath}/workreimbur/workReimbur")
public class WorkReimburController extends BaseController {

	@Autowired
	private WorkReimburService workReimburService;
	@Autowired
	protected RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private ActAuditService actAuditService;
	@ModelAttribute
	public WorkReimbur get(@RequestParam(required=false) String id) {
		WorkReimbur entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workReimburService.get(id);
		}
		if (entity == null){
			entity = new WorkReimbur();
		}
		return entity;
	}
	
	/**
	 * 报销申请列表页面
	 */
	@RequiresPermissions("workreimbur:workReimbur:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkReimbur workReimbur, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()) {
			workReimbur.setCompanyId(user.getComId());
			if (!UserUtils.isManager()) {
				workReimbur.setCreateBy(user);//创建人
				//workReimbur.setOfficeId(UserUtils.getSelectOffice().getId());
			}
		}

		Page<WorkReimbur> page = workReimburService.findPage(new Page<WorkReimbur>(request, response), workReimbur); 
		model.addAttribute("page", page);
		return "modules/workreimbur/workReimburList";
	}

	/**
	 * 查看，增加，编辑报销申请表单页面
	 */
	@RequiresPermissions(value={"workreimbur:workReimbur:view","workreimbur:workReimbur:add","workreimbur:workReimbur:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkReimbur workReimbur, Model model) {
		String view = "workReimburForm";
		// 查看审批申请单
		if (org.apache.commons.lang3.StringUtils.isNotBlank(workReimbur.getId())) {//.getAct().getProcInsId())){
			// 环节编号
			String taskDefKey = workReimbur.getAct().getTaskDefKey();
			if (taskDefKey != null) {
				// 查看工单
				if (workReimbur.getAct().isFinishTask()) {
					view = "workReimburView";
				}
				// 修改环节
				else if ("apply_end".equals(taskDefKey)) {
					view = "workReimburAudit";
				}
				// 审核环节
				else if ("audit1".equals(taskDefKey)) {
					if (org.apache.commons.lang3.StringUtils.isBlank(workReimbur.getAct().getStatus())) {
						model.addAttribute("disabled", "true");
					} else {
						model.addAttribute("disabled", "false");
					}
					view = "workReimburAudit";
				}
				//
				else if ("modifyApply".equals(taskDefKey)) {
					view = "workReimburForm";
				}
			}
			if (org.apache.commons.lang3.StringUtils.isNotBlank(workReimbur.getName())) {
				if (workReimbur.getName().equals("view")) {
					model.addAttribute("disabled", "true");
					workReimbur.getAct().setProcInsId(workReimbur.getProcessInstanceId());
					view = "workReimburAudit";
				}
			}
		}

		model.addAttribute("workReimbur", workReimbur);
		return "modules/workreimbur/"+view;
	}

	/**
	 * 保存报销申请
	 */
	@RequiresPermissions(value={"workreimbur:workReimbur:add","workreimbur:workReimbur:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkReimbur workReimbur, Model model,@RequestParam(value = "this_upload_files",required = false)MultipartFile[] this_upload_files, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workReimbur)) {
			return form(workReimbur, model);
		}
		if (org.apache.commons.lang3.StringUtils.isNotBlank(workReimbur.getId())) {
			WorkReimbur t = workReimburService.get(workReimbur.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workReimbur, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			if (t.getStatus().equals("3") || t.getStatus().equals("4")) {
				addMessage(redirectAttributes, "已结束流程不能修改！");
			} else {
				workReimburService.save(t);
			}
		} else {
			try {
				Map<String, Boolean> resultMap = workReimburService.saveWorkReimbur(workReimbur,this_upload_files);
				boolean flag = resultMap.get("flag");
				if (!flag) {
					addMessage(redirectAttributes, "不能选择自己为审批人!");
				} else {
					boolean b = resultMap.get("b");
					if (b) {
						addMessage(redirectAttributes, "报销申请已经提交");
					} else {
						addMessage(redirectAttributes, "系统内部错误！");
					}
				}
			} catch (Exception e) {
				logger.info("save e.getMessage()=" + e.getMessage());
				addMessage(redirectAttributes, "系统内部错误！");
			}
		}
		return "redirect:"+Global.getAdminPath()+"/workreimbur/workReimbur/?repage";
	}
	
	/**
	 * 删除报销申请
	 */
	@RequiresPermissions("workreimbur:workReimbur:del")
	@RequestMapping(value = "delete")
	public String delete(WorkReimbur workReimbur, RedirectAttributes redirectAttributes) {
		workReimburService.delete(workReimbur);
		addMessage(redirectAttributes, "删除报销申请成功");
		return "redirect:"+Global.getAdminPath()+"/workreimbur/workReimbur/?repage";
	}
	
	/**
	 * 批量删除报销申请
	 */
	@RequiresPermissions("workreimbur:workReimbur:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workReimburService.delete(workReimburService.get(id));
		}
		addMessage(redirectAttributes, "删除报销申请成功");
		return "redirect:"+Global.getAdminPath()+"/workreimbur/workReimbur/?repage";
	}
	/**
	 * 执行审批任务
	 * @param
	 * @param vars
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkReimbur workReimbur, Map<String, Object> vars, Model model) {
		//workReimburService.auditSave(workReimbur);
		Act act = workReimbur.getAct();
		actAuditService.saveAudit(act, act.getProcInsId(), "reimbur", workReimbur.getAct().getComment(), workReimbur.getId(), "2");
		if (workReimbur!=null && org.apache.commons.lang3.StringUtils.isNotBlank(workReimbur.getHome()) && workReimbur.getHome().equals("home")){
			return "redirect:" + adminPath + "/home";
		}
		return "redirect:" + adminPath + "/workreimbur/workReimbur";
	}

	/**
	 * 待办任务
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"workReimburTodoList"})
	public String workPaymentTodoList(Act act, HttpServletRequest request, HttpServletResponse response, Model model) {
		act.setProcDefKey("reimbur");
		List<Act> list = actTaskService.todoList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<WorkReimbur> lists = new ArrayList<WorkReimbur>();
		for (Act a : list) {
			WorkReimbur workReimbur = workReimburService.getByProcessInstanceId(a.getProcInsId());
			if (workReimbur != null && workReimbur.getCompanyId().equals(companyId)) {
				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());
					}
				}
				workReimbur.setAct(a);
				if (com.jeeplus.common.utils.StringUtils.isNotBlank(workReimbur.getId())){
					workReimbur.setName(officeService.get(companyId).getName());
				}
				lists.add(workReimbur);
			}
		}
		model.addAttribute("list", lists);
		return "modules/workreimbur/workReimburTodoList";
	}

	/**
	 * 已办任务
	 * @param act
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"workReimburHistoricList"})
	public String workPaymentHistoricList (Act act, HttpServletRequest request, HttpServletResponse response, Model model){
		act.setProcDefKey("reimbur");
		Page<Act> page = actTaskService.historicList(new Page<Act>(request, response), act);
		List<Act> list = page.getList();
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<WorkReimbur> lists = new ArrayList<WorkReimbur>();
		for (Act a : list) {
			WorkReimbur workReimbur = workReimburService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
			if (workReimbur != null && workReimbur.getCompanyId().equals(companyId)) {
				if (a.getVars().getMap().get("applyUserId")!=null){
					a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
				}
				workReimbur.setAct(a);
				if (com.jeeplus.common.utils.StringUtils.isNotBlank(workReimbur.getId())){
					workReimbur.setName(officeService.get(companyId).getName());
				}
				lists.add(workReimbur);
			}
		}
		model.addAttribute("list", lists);

		return "modules/workreimbur/workReimburHistoricList";
	}

	/**
	 * 审核报销申请
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnWorkReimbur")
	public String applyOnWorkReimbur(Act act, HttpServletResponse response, Model model) {
		// 获取流程XML上的表单KEY
		String formKey = actTaskService.getFormKey(act.getProcDefId(), act.getTaskDefKey());
		//logger.info("------formKeys:"+formKeys);
		// 获取流程实例对象
		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
	 * @return
	 */
	@RequestMapping(value = "revoke")
	public String revoke(HttpServletRequest request, HttpServletResponse response) {

		HashMap<String, String> requestMap = findRequestMap(request);
		String processInstanceId = requestMap.get("processInstanceId");
		String id = requestMap.get("id");
		String deleteReason = requestMap.get("reason");

		AjaxJson j = new AjaxJson();
		try {
			WorkReimbur workReimbur = workReimburService.getById(id);
			workReimbur.setStatus("5");
			workReimbur.preUpdate();
			workReimburService.update(workReimbur);
			Map map = workReimburService.getReimburById(id,"1");
			j.put("data",map);
			actTaskService.endProcessInstance(processInstanceId, deleteReason);
			j.setMsg("撤销申请成功");

			//撤销后，更改所有发送过的通知的阅读状态
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workReimbur.getId());
			workProjectNotifyService.readByNotifyId(notify);
		}catch (Exception e){
			j.setErrorCode("101");
			logger.info(e.getMessage());
			j.setMsg("撤销申请失败");
			j.setSuccess(false);
		}
		return "redirect:" + adminPath + "/workreimbur/workReimbur";
	}




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

	/**
	 * 导入Excel数据

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

}