/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workreimbursement.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.mapper.JsonMapper;
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.projectrecord.entity.ProjectRecords;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
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.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysmtree.entity.SysMtree;
import com.jeeplus.modules.sysmtree.service.SysMtreeService;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workbidproject.service.WorkBidProjectService;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
import com.jeeplus.modules.projectrecord.dao.WorkProjectUserDao;
import com.jeeplus.modules.workreimbursement.entity.WorkAccount;
import com.jeeplus.modules.workreimbursement.entity.WorkAccountAudit;
import com.jeeplus.modules.workreimbursement.entity.WorkReimbursement;
import com.jeeplus.modules.workreimbursement.service.WorkReimbursementService;
import com.jeeplus.modules.workreimbursement.utils.VarStr;
import com.jeeplus.modules.workreimbursementback.entity.WorkReimbursementBack;
import com.jeeplus.modules.workreimbursementback.service.WorkReimbursementBackService;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.worksupplier.entity.WorkSupplier;
import com.jeeplus.modules.worksupplier.service.WorkSupplierService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.poi.hssf.record.TableRecord;
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.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 财务报销Controller
 * @author 孟祥越
 * @version 2017-05-02
 */
@Controller
@RequestMapping(value = "${adminPath}/workreimbursement/workReimbursement")
public class WorkReimbursementController extends BaseController {

	@Autowired
	private WorkReimbursementService workReimbursementService;
	@Autowired
	private WorkSupplierService workSupplierService;
	@Autowired
	private WorkContractInfoService workContractInfoService;

	@Autowired
	protected RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private WorkClientInfoService workClientInfoService;
	@Autowired
	private WorkFullManageService workFullManageService;

	@Autowired
	private WorkBidProjectService workBidProjectService;

	@Autowired
	private SysMtreeService sysMtreeService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private ProjectRecordsService projectRecordsService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkProjectUserDao workProjectUserDao;
	@Autowired
	private WorkReimbursementBackService workReimbursementBackService;

	@ModelAttribute
	public WorkReimbursement get(@RequestParam(required=false) String id) {

		WorkReimbursement entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workReimbursementService.get(id);
		}
		if (entity == null){
			entity = new WorkReimbursement();
		}
		return entity;
	}

	/**
	 * 报销单列表页面
	 */
	@RequiresPermissions("workreimbursement:workReimbursement:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkReimbursement workReimbursement, HttpServletRequest request, HttpServletResponse response, Model model) {
		//workReimbursement.setOfficeId(UserUtils.getSelectOffice().getId());
		Page<WorkReimbursement> page = workReimbursementService.findPage(new Page<WorkReimbursement>(request, response), workReimbursement);
		model.addAttribute("page", page);
		return "modules/workreimbursement/workReimbursementList";
	}



	/**
	 * 查看，增加，编辑报销单表单页面
	 */
//	@RequiresPermissions(value={"workreimbursement:workReimbursement:view","workreimbursement:workReimbursement:add","workreimbursement:workReimbursement:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkReimbursement workReimbursement,Model model) {
		String view = "workReimbursementFormAdd";
		Office office = UserUtils.getSelectOffice();
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workReimbursementFormDetail";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workReimbursement.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);
				workReimbursement.setAct(act);
				view = "workReimbursementModifyApply";
			}
		}
		// 环节编号
		String taskDefKey = workReimbursement.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && ("bmzr".equals(taskDefKey) ||
				"fgld".equals(taskDefKey)
				 || "zjl".equals(taskDefKey)
				|| taskDefKey.contains("cwzj")|| taskDefKey.contains("cn") || taskDefKey.contains("task"))){
			view = "workReimbursementAudit";
		}else  if (StringUtils.isNotBlank(taskDefKey) && "cw".equals(taskDefKey)){
			view = "workReimbursementCWAudit";
		}else if (StringUtils.isNotBlank(taskDefKey) && !taskDefKey.equals("modifyApply")){
			view = "workReimbursementAudit";
		}
		String param=UserUtils.getSysParam("check_subjects",UserUtils.getUser());
		if("是".equals(param)){
			model.addAttribute("isShow", '1');
		}else{
			model.addAttribute("isShow", '0');
		}
		if (workReimbursement!=null && StringUtils.isBlank(workReimbursement.getSubmitterId())){
			workReimbursement.setSubmitterId(UserUtils.getUser().getId());
			workReimbursement.setSubmitterName(UserUtils.getUser().getName());
			if(UserUtils.getBasicInfo()!=null){
				workReimbursement.setBankCard(UserUtils.getBasicInfo().getBankCard());
			}
		}
		if (workReimbursement!=null && workReimbursement.getCreateBy()==null){
			workReimbursement.setCreateBy(UserUtils.getUser());
			workReimbursement.setUserName(UserUtils.getUser().getName());
		}
		if (workReimbursement!=null && StringUtils.isBlank(workReimbursement.getOfficeId())){
			workReimbursement.setOfficeId(office.getId());
			workReimbursement.setOfficeName(office.getTopCompany());
		}
		if ("workReimbursementFormAdd".equals(view)&&"0".equals(tabId)){
			if(UserUtils.getBasicInfo()!=null && StringUtils.isNotBlank(UserUtils.getBasicInfo().getId())) {
				List<WorkReimbursementBack> backList = workReimbursementBackService.findLoanList(UserUtils.getBasicInfo().getId());
				workReimbursement.setReimbursementBackList(backList);
				workReimbursement.setAchivesId(UserUtils.getBasicInfo().getId());
			}
		}
		model.addAttribute("workReimbursement", workReimbursement);
		return "modules/workreimbursement/"+view;
	}

	/**
	 * 暂存报销单
	 */
	@RequestMapping(value = "store")
	public String store(WorkReimbursement workReimbursement,
						Model model,
//						@RequestParam(value = "upload_files",required = false) MultipartFile[] upload_files,
						RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workReimbursement)){
			return form(workReimbursement, model);
		}

		workReimbursement.setStatus("1"); //暂存状态
		workReimbursement.setCompanyId(UserUtils.getSelectCompany().getId());
		workReimbursement.setCreateOffice(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(workReimbursement.getProcessInstanceId()) && workReimbursement.getProcessInstanceId().equals("NULL")){
			workReimbursement.setProcessInstanceId("");
		}
		if(!workReimbursement.getIsNewRecord()){//编辑表单保存
			WorkReimbursement t = workReimbursementService.get(workReimbursement.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workReimbursement, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workReimbursementService.save(t);//保存
		}else{//新增表单保存
			workReimbursementService.save(workReimbursement);//保存
		}
		addMessage(redirectAttributes, "保存报销单成功");
		return "redirect:" + adminPath +"/workreimbursement/workReimbursement/?repage";
	}

	/**
	 * 保存提交报销单
	 * 启动流程
	 */
	@RequestMapping(value = "save")
	public String save(WorkReimbursement workReimbursement,
					   Model model,
//					   @RequestParam(value = "upload_files",required = false) MultipartFile[] upload_files,
					   RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workReimbursement)){
			return form(workReimbursement, model);
		}
		User user = workReimbursement.getCreateBy();
		String sta = workReimbursement.getStatus();
		//状态设置为审核中
		workReimbursement.setStatus("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workReimbursementService.get(workReimbursement.getId()).getProcessInstanceId();
		}
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workReimbursement.setCompanyId(UserUtils.getSelectCompany().getId());
			workReimbursement.setCreateOffice(UserUtils.getSelectOffice().getId());
			String str = workReimbursementService.save(workReimbursement, variables,processInstanceId);
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "报销申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "报销申请已经提交");
			}

		} catch (Exception e) {
			logger.info("Exception e:"+e);
			addMessage(redirectAttributes, "报销申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:" + adminPath +"/workreimbursement/workReimbursement/?repage";
//		return "modules/workreimbursement/reimbursementTodoList";
	}

	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkReimbursement workReimbursement, Model model,
							RedirectAttributes redirectAttributes) {
//		try {
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workReimbursement.getAct().getTaskDefKey();
			List<User> users = null;
			if ("bmzr".equals(taskDefKey)){
				users = UserUtils.getByProssType(workReimbursement.getProcessInstanceId(),2);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("fgld",2,workReimbursement.getOfficeId(),"8",workReimbursement.getCreateBy());
			}else  if ("fgld".equals(taskDefKey)){
				users = UserUtils.getByProssType(workReimbursement.getProcessInstanceId(),3);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("cwzg", 3, workReimbursement.getOfficeId(), "8", workReimbursement.getCreateBy());
			}else  if ("cw".equals(taskDefKey)){
				users = UserUtils.getByProssType(workReimbursement.getProcessInstanceId(),4);
				if (users==null )
				users = UserUtils.getByRoleActivityEnname("zjl",3,workReimbursement.getOfficeId(),"8",workReimbursement.getCreateBy());
			}else  if ("zjl".equals(taskDefKey)){
				users = UserUtils.getByProssType(workReimbursement.getProcessInstanceId(),5);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("cwfgld",3,workReimbursement.getOfficeId(),"8",workReimbursement.getCreateBy());
			}else  if ("cwzj".equals(taskDefKey)){
				users = UserUtils.getByProssType(workReimbursement.getProcessInstanceId(),6);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("cn",3,workReimbursement.getOfficeId(),"8",workReimbursement.getCreateBy());
			}else if ("cn".equals(taskDefKey)){
				users = UserUtils.getByProssType(workReimbursement.getProcessInstanceId(),1);
			}else if ("modifyApply".equals(taskDefKey)){
				users = UserUtils.getByProssType(workReimbursement.getProcessInstanceId(),1);
			}
            String flag = workReimbursement.getAct().getFlag();
            if ("yes".equals(flag) &&(users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = workReimbursementService.auditSave(workReimbursement,users);
				addMessage(redirectAttributes, str);
			}
//		}catch (Exception e){
//			logger.info("Exception e:"+e);
//			addMessage(redirectAttributes, "审批失败");
//		}
		if (StringUtils.isNotBlank(workReimbursement.getHome()) && "home".equals(workReimbursement.getHome())) {
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		} else {
			return "redirect:" + Global.getAdminPath() + "/workreimbursement/workReimbursement/?repage";
		}
	}


	/**
	 * 删除报销单
	 */
	@RequiresPermissions("workreimbursement:workReimbursement:del")
	@RequestMapping(value = "delete")
	public String delete(WorkReimbursement workReimbursement, RedirectAttributes redirectAttributes) {
		String sta = workReimbursement.getStatus();
		if("5".equals(sta) || "2".equals(sta) ){
			if("5".equals(sta)){
				addMessage(redirectAttributes, "报销单已报销，无法删除");
				return "redirect:"+Global.getAdminPath()+"/workreimbursement/workReimbursement/?repage";
			}else{
				addMessage(redirectAttributes, "报销单正在审核中，无法删除");
				return "redirect:"+Global.getAdminPath()+"/workreimbursement/workReimbursement/?repage";
			}
		}
		workReimbursementService.delete(workReimbursement);
		addMessage(redirectAttributes, "删除报销单成功");
		return "redirect:"+Global.getAdminPath()+"/workreimbursement/workReimbursement/?repage";
	}

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

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

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workreimbursement:workReimbursement: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<WorkReimbursement> list = ei.getDataList(WorkReimbursement.class);
			for (WorkReimbursement workReimbursement : list){
				try{
					workReimbursementService.save(workReimbursement);
					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()+"/workreimbursement/workReimbursement/?repage";
	}

	/**
	 * 下载导入报销单数据模板
	 */
	@RequiresPermissions("workreimbursement:workReimbursement:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "报销单数据导入模板.xlsx";
			List<WorkReimbursement> list = Lists.newArrayList();
			String agent = request.getHeader("USER-AGENT");
			new ExportExcel("报销单数据", WorkReimbursement.class, 1).setDataList(list).write(response, fileName,agent).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workreimbursement/workReimbursement/?repage";
	}

	/**
	 * 选择报销项目
	 */
	@RequestMapping(value = "selectproject")
	public String selectproject(ProjectRecords projectId, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		projectId.setCompany(UserUtils.getSelectCompany());
		Page<ProjectRecords> page = projectRecordsService.findPageByStatus(new Page<ProjectRecords>(request, response), projectId);
		try {
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "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", projectId);
		model.addAttribute("allowInput", true);
		model.addAttribute("page", page);
		return "modules/sys/gridselectcallproject";
		//return "modules/sys/gridselect";
	}

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

	@RequestMapping("/queryToList")
	public String queryToList(Act act,Model model){
    	/*之前的写法*/
//        act.setProcDefKey("reimbursement");
//        List<WorkReimbursement> todoTasks = workReimbursementService.findTodoTasks(act,UserUtils.getUser().getId());
//        model.addAttribute("list",todoTasks);
//        return "modules/workreimbursement/reimbursementTodoList";
		/* 新写法 */
		/*act.setProcDefKey("reimbursement");
		List<Act> list = actTaskService.todoList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();*/
		act.setProcDefKey("reimbursement");
		List<Act> list = actTaskService.todoList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<Activity> activities = activityService.groupByActivityMenu("ggh3125f1f194c82bdea93555c750906",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			list.addAll(actTaskService.todoList(act));
		}
		Role role = UserUtils.getSelectRole().get(0);
		List<WorkReimbursement> lists = new ArrayList<WorkReimbursement>();
		for (Act a : list) {
			if(a.getTask().getTaskDefinitionKey()!=null && !"modifyApply".equals(a.getTask().getTaskDefinitionKey()) && !a.getTask().getTaskDefinitionKey().contains("audit")) {
				WorkReimbursement workReimbursement = workReimbursementService.getByProcessInstanceId(a.getProcInsId());
				if (workReimbursement != null && workReimbursement.getCompanyId().equals(companyId)) {
					workReimbursement.setCreateBy(UserUtils.get(workReimbursement.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());
						}
					}
					workReimbursement.setAct(a);
					lists.add(workReimbursement);
				}
			}
		}
		model.addAttribute("list", lists);
		return "modules/workreimbursement/reimbursementTodoList";
	}
	/**
	 * 查询已办列表
	 * @return
	 */
	@RequestMapping("/queryCompleteList")
	public String queryCompleteList(Act act,HttpServletRequest request,HttpServletResponse response,Model model){
		act.setProcDefKey("reimbursement");
		List<WorkReimbursement> list = workReimbursementService.historicList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<Activity> activities = activityService.groupByActivityMenu("ggh3125f1f194c82bdea93555c750906",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			list.addAll(workReimbursementService.historicList(act));
		}
		model.addAttribute("list",list);
		return "modules/workreimbursement/reimbursementHistoricList";
	}

	/**
	 * 审核信息
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnLeave")
	public String applyOnCompany(Act act, HttpServletResponse response, Model model) {
		// 获取流程XML上的表单KEY
		String formKey = "/workreimbursement/workReimbursement/form";
//        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);
	}

	/**
	 * 读取所有流程
	 * @return
	 */
	@RequestMapping(value = "getProcess")
	public String getProcess(WorkReimbursement workReimbursement, HttpServletRequest request, HttpServletResponse response, Model model) {
//        admin 可以查看所有流程  展示注释
//        User user = UserUtils.getUser();
//        if (!user.isAdmin()){
////            leave.setCompanyId(user.getComId());
//            if (!UserUtils.isManager()){
//                workReimbursement.setCreateBy(user);
//            }
//        }
		Page<WorkReimbursement> page = workReimbursementService.find(new Page<WorkReimbursement>(request, response), workReimbursement);
		model.addAttribute("processInstanceId", page.getList().get(0).getProcessInstanceId());
		return "modules/workreimbursement/workReimbursementTrack";
	}

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

	/**
	 * 获取项目信息
	 * @return
	 */
	@RequestMapping(value = "getProjectInfo")
	@ResponseBody
	public String getProjectInfo() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		ProjectRecords projectRecords = projectRecordsService.get(obj);
		if(projectRecords != null){
			List<User> users = workProjectUserDao.queryProjectUsers(projectRecords.getId(), "1");
			String projectMaster = "";
			String projectMasterName = "";
			if(users!=null && users.size()!=0){
				for (int i = 0; i < users.size(); i++) {
					if(i == users.size() -1){
						projectMasterName += UserUtils.get(users.get(i).getId()).getName();
						projectMaster += UserUtils.get(users.get(i).getId());
					}else{
						projectMaster += UserUtils.get(users.get(i).getId())+",";
						projectMasterName += UserUtils.get(users.get(i).getId()).getName()+",";
					}
				}
				map.put("projectMaster",projectMaster);
				map.put("projectMasterName",projectMasterName);
			}else{
				map.put("projectMaster","projectMaster");
				map.put("projectMasterName","projectMasterName");
			}
			map.put("submitterId",projectRecords.getCreateBy().getId());
			map.put("submitterName",UserUtils.get(projectRecords.getCreateBy().getId()).getName());
			if (projectRecords.getOffice()!=null && StringUtils.isNotBlank(projectRecords.getOffice().getId())){
				map.put("officeId",projectRecords.getOffice().getId());
				map.put("officeName",officeService.get(projectRecords.getOffice().getId()).getName());
			}else {
				map.put("officeId",UserUtils.getSelectOffice().getId());
				map.put("officeName",UserUtils.getSelectOffice().getName());
			}

			map.put("projectType",projectRecords.getScaleType()==null?"":projectRecords.getScaleType());
			map.put("projectTypeName",projectRecords.getScaleType()==null?"":projectRecords.getScaleType());
			map.put("projectId",projectRecords.getId());
		}
		return JsonMapper.toJsonString(map);
	}

	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, @RequestParam(required=false) String type,
											  @RequestParam(required=false) Long grade, @RequestParam(required=false) Boolean isAll, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<SysMtree> list = sysMtreeService.findList(new SysMtree());
		for (int i=0; i<list.size(); i++){
			SysMtree e = list.get(i);
			if ((StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1))
					&& (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("pIds", e.getParentIds());
				map.put("name", e.getName());
				if (type != null && "3".equals(type)){
					map.put("isParent", true);
				}
				mapList.add(map);
			}
		}
		return mapList;
	}

	/**
	 * 异步上传文件
	 * @return
	 */
	@RequestMapping("/uploadFile")
	@ResponseBody
	public Map<String,Object> uploadFile(WorkReimbursement workReimbursement,
										 Model model, RedirectAttributes redirectAttributes,
										 HttpServletRequest request,
										 @RequestParam(value = "myFile") CommonsMultipartFile myFile){
		String attchmentId = request.getParameter("attchmentId");
		WorkClientAttachment workClientAttachment = workClientInfoService.uploadFileSingle(request, myFile, workReimbursement.getId(), VarStr.attachmentFlag[1]);
		workClientAttachment.setId(attchmentId);
		String s = workClientInfoService.save(workClientAttachment);
		Map map = new HashMap();
		map.put("msg","success");
		return map;
	}

	/**
	 * 合同作废：强制撤回
	 */
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkReimbursement workReimbursement,RedirectAttributes redirectAttributes){
		try {
			WorkReimbursement reportData = workReimbursementService.get(workReimbursement.getId());
			if(reportData.getStatus().equals("5")){
				addMessage(redirectAttributes, "报销申请已审批通过，无法撤回");
			}else{
				workReimbursementService.cancelInvalidate(workReimbursement);
				addMessage(redirectAttributes, "报销申请撤回成功");
			}
		}catch (Exception e){
			logger.error("Exception e"+e);
			addMessage(redirectAttributes, "报销申请撤回失败");
		}
		return "redirect:"+Global.getAdminPath()+"/workreimbursement/workReimbursement/?repage";
	}
	/**
	 * 合同管理列表页面
	 */
	@RequestMapping(value = {"gridSelectComname"})
	public String list(WorkSupplier workSupplier, HttpServletRequest request, HttpServletResponse response, Model model) {
		if("1".equals(workSupplier.getFalt())){
			workSupplier.setRemoveSign("1");//正常
			Page<WorkSupplier> page = workSupplierService.findPage(new Page<WorkSupplier>(request, response), workSupplier);
			model.addAttribute("page", page);
		}else{
			WorkClientInfo client=new WorkClientInfo();
			Page<WorkSupplier> page = workSupplierService.findPageClientInfo(new Page<WorkSupplier>(request, response), workSupplier);
			model.addAttribute("page", page);
		}
		return  "modules/sys/gridworkSupplier";
	}
	/**
	 * 选择报销项目
	 */
	@RequestMapping(value = "selectReproject")
	public String selectReproject(String userId,ProjectRecords projectId, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		projectId.setCompany(UserUtils.getSelectCompany());
		Page<ProjectRecords> page = projectRecordsService.findPageByRe(new Page<ProjectRecords>(request, response), projectId,userId);
		try {
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "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", projectId);
		model.addAttribute("allowInput", true);
		model.addAttribute("page", page);
		return "modules/sys/gridselectcallproject";
		//return "modules/sys/gridselect";
	}
}