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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.bos.BOSClientUtil;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.ossutil.OssClient;
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.common.web.HttpRequest;
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.casebuildinfo.entity.CaseBuildInfo;
import com.jeeplus.modules.casebuildinfo.service.CaseBuildInfoService;
import com.jeeplus.modules.casecategory.entity.CaseCategory;
import com.jeeplus.modules.casecategory.service.CaseCategoryService;
import com.jeeplus.modules.casedesigninfo.entity.CaseDesignInfo;
import com.jeeplus.modules.casedesigninfo.service.CaseDesignInfoService;
import com.jeeplus.modules.caseexecuteinfo.entity.CaseExecuteInfo;
import com.jeeplus.modules.caseexecuteinfo.service.CaseExecuteInfoService;
import com.jeeplus.modules.caseinfo.dao.CaseInfoDao;
import com.jeeplus.modules.caseinfo.entity.CaseInfo;
import com.jeeplus.modules.caseinfo.service.CaseInfoService;
import com.jeeplus.modules.casematerials.entity.CaseMaterials;
import com.jeeplus.modules.casematerials.service.CaseMaterialsService;
import com.jeeplus.modules.casematerialsnorm.entity.CaseMaterialsNorm;
import com.jeeplus.modules.casematerialsnorm.service.CaseMaterialsNormService;
import com.jeeplus.modules.casemechanicalnorm.entity.CaseMechanicalNorm;
import com.jeeplus.modules.casemechanicalnorm.service.CaseMechanicalNormService;
import com.jeeplus.modules.casenorm.entity.CaseNorm;
import com.jeeplus.modules.casenorm.service.CaseNormService;
import com.jeeplus.modules.casepeoplenorm.entity.CasePeopleNorm;
import com.jeeplus.modules.casepeoplenorm.service.CasePeopleNormService;
import com.jeeplus.modules.caseprojectfeature.entity.CaseProjectFeature;
import com.jeeplus.modules.caseprojectfeature.service.CaseProjectFeatureService;
import com.jeeplus.modules.sys.dao.RoleDao;
import com.jeeplus.modules.sys.entity.*;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.WorkattachmentService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workproject.entity.WorkProject;
import com.jeeplus.modules.workproject.service.WorkProjectService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import net.sf.json.JSONArray;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricProcessInstance;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 案例详情Controller
 * @author liuw
 * @version 2018-01-24
 */
@Controller
@RequestMapping(value = "${adminPath}/caseinfo/caseInfo")
public class CaseInfoController extends BaseController {

	@Autowired
	private CaseInfoService caseInfoService;
	@Autowired
	private WorkProjectService workProjectService;
	@Autowired
	private CaseCategoryService caseCategoryService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private CaseBuildInfoService caseBuildInfoService;
	@Autowired
	private CaseDesignInfoService caseDesignInfoService;
	@Autowired
	private CaseExecuteInfoService caseExecuteInfoService;
	@Autowired
	private OfficeService officeService;

	@Autowired
	private CaseProjectFeatureService caseProjectFeatureService;
	@Autowired
	private CaseNormService caseNormService;
	@Autowired
	private WorkattachmentService workattachmentService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;

	@Autowired
	private CaseMaterialsService caseMaterialsService;
	@Autowired
	private CaseMaterialsNormService caseMaterialsNormService;
	@Autowired
	private CaseMechanicalNormService caseMechanicalNormService;
	@Autowired
	private CasePeopleNormService casePeopleNormService;
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private CaseInfoDao caseInfoDao;


	@ModelAttribute
	public CaseInfo get(@RequestParam(required=false) String id) {
		CaseInfo entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = caseInfoService.get(id);
		}
		if (entity == null){
			entity = new CaseInfo();
		}
		return entity;
	}
	@RequiresPermissions("caseinfo:caseInfo:index")
	@RequestMapping(value = {"index"})
	public String index(User user, Model model,HttpServletRequest request) {
		String sign = request.getParameter("sign");
		request.setAttribute("sign", sign);
		return "modules/caseinfo/caseInfoIndex";
	}
	/**
	 * 案例详情列表页面
	 */
	@RequiresPermissions("caseinfo:caseInfo:index")
	@RequestMapping(value = {"list", ""})
	public String list(CaseInfo caseInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		String sign = request.getParameter("sign");
		//我的案例
		if("me".equals(sign)){
			if (!user.isAdmin()){
				caseInfo.setCreateBy(user);
			}
			Page<CaseInfo> page = new Page<CaseInfo>(request, response);
			caseInfo.setPage(page);
			List<CaseInfo> list1 = caseInfoDao.findListme(caseInfo);
			List<CaseInfo> list2 = new ArrayList<>();
			for(int i=0;i<list1.size();i++){
				CaseInfo ci = list1.get(i);
				boolean state = true;
				if(StringUtils.isNotBlank(ci.getProcessInstanceId())){
					state = actTaskService.isProcessEnd(ci.getProcessInstanceId());
				}else{
					state = false;
				}
				ci.setProcessEnded(state);
				list2.add(ci);
			}
			page.setList(list2);
			model.addAttribute("page", page);
			return "modules/caseinfo/caseInfoListme";
		}else {
			/*if (!user.isAdmin()){
				caseInfo.setOfficeId(user.getOffice().getId());
			}
			Page<CaseInfo> page = new Page<CaseInfo>(request, response);
			caseInfo.setPage(page);
			page.setList(caseInfoDao.findListoffice2(caseInfo));
			*//*if(UserUtils.getSelectRole().getName().contains("部门负责人")){
				page.setList(caseInfoDao.findListoffice(caseInfo));
			}else{
				page.setList(caseInfoDao.findListoffice2(caseInfo));
			}*//*
			model.addAttribute("page", page);
			return "modules/caseinfo/caseInfoList";*/
			Office office = UserUtils.getSelectCompany();
			String companyIds = "";
			if (UserUtils.getUser().isAdmin()){
				companyIds = "0";
			}else {
				String[] parentIds = office.getParentIds().split(",");
				for (String parentId : parentIds) {
					if (!parentId.equals("0")) {
						Office o = officeService.get(parentId);
						if (o.getType().equals("1")) {
							companyIds += o.getId() + ",";
						}
					}
				}
				if (office.getType().equals("1")) {
					companyIds += office.getId() + ",";
				}
				if (StringUtils.isNotBlank(companyIds)) {
					companyIds = companyIds.substring(0, companyIds.length() - 1);
				}
			}
			caseInfo.setCompanyId(companyIds);

			Page<CaseInfo> page = caseInfoService.findCompanyPage(new Page<CaseInfo>(request, response), caseInfo);
			model.addAttribute("page", page);
			return "modules/caseinfo/caseInfoList";
		}

/*
		caseInfo.setCompanyId(UserUtils.getSelectCompany().getId());
		User user = UserUtils.getUser();
        if (!user.isAdmin()){
			caseInfo.setCreateBy(user);
		}
		Page<CaseInfo> page = caseInfoService.findPage(new Page<CaseInfo>(request, response), caseInfo);
		model.addAttribute("page", page);*/
	}

	/**
	 * 公司案例库列表页面
	 */
	@RequestMapping(value = "companyList")
	public String companyList(CaseInfo caseInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		Office office = UserUtils.getSelectCompany();
		String companyIds = "";
		if (UserUtils.getUser().isAdmin()){
			companyIds = "0";
		}else {
			String[] parentIds = office.getParentIds().split(",");
			for (String parentId : parentIds) {
				if (!parentId.equals("0")) {
					Office o = officeService.get(parentId);
					if (o.getType().equals("1")) {
						companyIds += o.getId() + ",";
					}
				}
			}
			if (office.getType().equals("1")) {
				companyIds += office.getId() + ",";
			}
			if (StringUtils.isNotBlank(companyIds)) {
				companyIds = companyIds.substring(0, companyIds.length() - 1);
			}
		}
		caseInfo.setCompanyId(companyIds);

		Page<CaseInfo> page = caseInfoService.findCompanyPage(new Page<CaseInfo>(request, response), caseInfo);
		model.addAttribute("page", page);
		return "modules/caseinfo/caseCompanyList";
	}

	/**
	 * 平台案例库列表页面
	 */
	@RequestMapping(value = "allList")
	public String allList(CaseInfo caseInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<CaseInfo> page = caseInfoService.findByAllPage(new Page<CaseInfo>(request, response), caseInfo);
		model.addAttribute("page", page);
		return "modules/caseinfo/caseAllList";
	}
	/**
	 * 工单执行（完成任务）
	 * @param
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(CaseInfo caseInfo,Map<String, Object> vars, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) {
		/*if (org.apache.commons.lang3.StringUtils.isBlank(workVisa.getAct().getComment())){
			addMessage(model, "请填写审核意见。");
			return form(workVisa, model,request);
		}*/
		try{
			// 对不同环节的业务逻辑进行操作
			String procDefKey = caseInfo.getAct().getProcDefKey();
			List<User> users = null;
			if ("caseInfo".equals(procDefKey)){
				users = UserUtils.getByProssType(caseInfo.getProcessInstanceId(),1);
				if ("yes".equals(caseInfo.getAct().getFlag()) && (users==null || users.size()==0)){
					addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
				}else {
					String str =caseInfoService.auditSave(caseInfo,users);
					addMessage(redirectAttributes, str);
				}
			}else {
				String str =caseInfoService.auditSave(caseInfo,users);
				addMessage(redirectAttributes, str);
			}

		}catch (Exception e){
			addMessage(redirectAttributes, "审批失败:");
		}
		//return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/?repage";
		//return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/index";
		//return "modules/caseinfo/caseInfoTodoList";
		//return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/caseInfoTodoList";
		if (StringUtils.isNotBlank(caseInfo.getHome()) && "home".equals(caseInfo.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/index";
		}
	}
	/**
	 * 页面跳转
	 */
	@RequestMapping(value = "share")
	public String share(CaseInfo caseInfo, Model model) {
		model.addAttribute("caseInfo", caseInfo);
		return "modules/caseinfo/caseInfoShare";
	}
	/**
	 * 设置案例类型
	 * @return
	 */
	@RequestMapping(value = "caseInfoShare")
	public String caseInfoShare(CaseInfo caseInfo, RedirectAttributes redirectAttributes)throws Exception {
		Map<String, Object> variables = new HashMap<String, Object>();
		CaseInfo t = caseInfoService.get(caseInfo.getId());//从数据库取出记录的值
		MyBeanUtils.copyBeanNotNull2Bean(caseInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
		t.preUpdate();
		caseInfoService.update(t);
		caseInfoService.save(t);
		addMessage(redirectAttributes, "案例类型设置成功");
		return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/index";
	}
	/**
	 * 查看，增加，编辑案例详情表单页面
	 */
	@RequiresPermissions(value={"caseinfo:caseInfo:view","caseinfo:caseInfo:add","caseinfo:caseInfo:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(CaseInfo caseInfo, Model model,HttpServletRequest request) {
		String tabId = request.getParameter("tabId");
		String cid = request.getParameter("cid");
		if(StringUtils.isNotBlank(cid)){
			CaseCategory cc = caseCategoryService.get(cid);
			if(cc!=null){
				caseInfo.setCaseCategory(cc);
			}
		}
		model.addAttribute("caseInfo", caseInfo);
		if("0".equals(tabId)){
			return "modules/caseinfo/caseInfoView";
		}
		if (caseInfo.getAct()!=null && StringUtils.isNotBlank(caseInfo.getAct().getTaskId())){
			return "modules/caseinfo/caseInfoAudit";
		}
			if(StringUtils.isNotBlank(caseInfo.getId())){
				return "modules/caseinfo/caseInfoForms";
			}
		return "modules/caseinfo/caseInfoForm";
	}

	/**
	 * 保存案例详情
	 */
	@RequiresPermissions(value={"caseinfo:caseInfo:add","caseinfo:caseInfo:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(CaseInfo caseInfo, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, caseInfo)){
			return form(caseInfo, model,request);
		}
		try {
			if (!caseInfo.getIsNewRecord()) {//编辑表单保存
				CaseInfo t = caseInfoService.get(caseInfo.getId());//从数据库取出记录的值
				MyBeanUtils.copyBeanNotNull2Bean(caseInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
				t.setCompanyId(UserUtils.getSelectCompany().getId());
				String remarks = t.getRemarks();
				if (StringUtils.isNotBlank(remarks) && remarks.equals("重新申请")) {
					//更新流程
					caseInfoService.getCaseAct(t);
					t.setRemarks("");
					caseInfoService.auditSave(t,null);
					String tableMap = request.getParameter("tableMap");
					String decode = "";
					if (StringUtils.isNotBlank(tableMap)) {
						try {
							decode = URLDecoder.decode(tableMap, "UTF-8");
						} catch (Exception e) {
							e.printStackTrace();
						}
						JSONArray jsonArray = JSONArray.fromObject(decode);
						dealAccountData(jsonArray, t);
					}
					caseInfoService.save(t);//保存
					addMessage(redirectAttributes, "案例已重新申请!");
					if (StringUtils.isNotBlank(caseInfo.getHome()) && "home".equals(caseInfo.getHome())){
						return "redirect:" + Global.getAdminPath() + "/home/?repage";
					}
				} else {
					String tableMap = request.getParameter("tableMap");
					String decode = "";
					if (StringUtils.isNotBlank(tableMap)) {
						try {
							decode = URLDecoder.decode(tableMap, "UTF-8");
						} catch (Exception e) {
							e.printStackTrace();
						}
						JSONArray jsonArray = JSONArray.fromObject(decode);
						dealAccountData(jsonArray, t);
					}
					caseInfoService.save(t);//保存
					addMessage(redirectAttributes, "保存案例成功");
				}
			} else {//新增表单保存
				//案例分享公司
				if (!UserUtils.getUser().isAdmin()) {
					caseInfo.setCompanyName(UserUtils.getSelectCompany().getName());
				} else {
					caseInfo.setCompanyName("总公司");
				}
				String tableMap = request.getParameter("tableMap");
				String decode = "";
				if (StringUtils.isNotBlank(tableMap)) {
					try {
						decode = URLDecoder.decode(tableMap, "UTF-8");
					} catch (Exception e) {
						e.printStackTrace();
					}
					JSONArray jsonArray = JSONArray.fromObject(decode);
					dealAccountData(jsonArray, caseInfo);
				}
				caseInfo.setStatus("2");
				caseInfo.setCompanyId(UserUtils.getSelectCompany().getId());
				caseInfo.setOfficeId(UserUtils.getSelectOffice().getId());
				//caseInfo.setUserids(getPeopleMaster());
				caseInfoService.save(caseInfo);//保存
				Map<String, Object> variables = new HashMap<String, Object>();
				String str = caseInfoService.startProcess(caseInfo, variables,null);
				if (StringUtils.isNotBlank(str)) {
					addMessage(redirectAttributes, "案例申请提交失败:" + str);
				} else {
					addMessage(redirectAttributes, "案例申请已经提交");
				}
			}
		}catch (Exception e) {
			logger.info(e.getMessage());
			addMessage(redirectAttributes, "申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/index?sign="+"me";
	}
	//新增定时
	/**
	 * 保存案例详情
	 */
	@RequiresPermissions(value={"caseinfo:caseInfo:add","caseinfo:caseInfo:edit"},logical=Logical.OR)
	@RequestMapping(value = "saveTiming")
	public String saveTiming(CaseInfo caseInfo, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, caseInfo)){
			return form(caseInfo, model,request);
		}
		try {
			//定时任务已启动，送审
			if (!caseInfo.getIsNewRecord()) {//编辑表单保存
				String sta = caseInfo.getStatus();
				String processInstanceId ="";
				CaseInfo t = caseInfoService.get(caseInfo.getId());//从数据库取出记录的值
				MyBeanUtils.copyBeanNotNull2Bean(caseInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
				String tableMap = request.getParameter("tableMap");
				String decode = "";
				if (StringUtils.isNotBlank(tableMap)) {
					try {
						decode = URLDecoder.decode(tableMap, "UTF-8");
					} catch (Exception e) {
						e.printStackTrace();
					}
					JSONArray jsonArray = JSONArray.fromObject(decode);
					dealAccountData(jsonArray, t);
				}
				t.setStatus("2");
				caseInfoService.saveTiming(t);//保存
				Map<String, Object> variables = new HashMap<String, Object>();
				if (StringUtils.isNotBlank(sta) && "3".equals(sta)){
					processInstanceId =caseInfoService.get(caseInfo.getId()).getProcessInstanceId();
				}
				String str = caseInfoService.startProcess(caseInfo, variables,processInstanceId);
				if (StringUtils.isNotBlank(str)) {
					addMessage(redirectAttributes, "案例申请提交失败:" + str);
				} else {
					addMessage(redirectAttributes, "案例申请已经提交");
				}
			} else {
				//新增表单保存(定时任务未启动)
				//案例分享公司
				if (!UserUtils.getUser().isAdmin()) {
					caseInfo.setCompanyName(UserUtils.getSelectCompany().getName());
				} else {
					caseInfo.setCompanyName("总公司");
				}
				String tableMap = request.getParameter("tableMap");
				String decode = "";
				if (StringUtils.isNotBlank(tableMap)) {
					try {
						decode = URLDecoder.decode(tableMap, "UTF-8");
					} catch (Exception e) {
						e.printStackTrace();
					}
					JSONArray jsonArray = JSONArray.fromObject(decode);
					dealAccountData(jsonArray, caseInfo);
				}
				caseInfo.setStatus("2");
				caseInfo.setCompanyId(UserUtils.getSelectCompany().getId());
				caseInfo.setOfficeId(UserUtils.getSelectOffice().getId());
				//caseInfo.setUserids(getPeopleMaster());
				caseInfoService.save(caseInfo);//保存
				Map<String, Object> variables = new HashMap<String, Object>();
				String str = caseInfoService.startProcess(caseInfo, variables,null);
				if (StringUtils.isNotBlank(str)) {
					addMessage(redirectAttributes, "案例申请提交失败:" + str);
				} else {
					addMessage(redirectAttributes, "案例申请已经提交");
				}
			}
		}catch (Exception e) {
			logger.info(e.getMessage());
			addMessage(redirectAttributes, "申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/index?sign="+"me";
	}
	/**
	 * 撤回/暂存重新申请
	 */
	@RequiresPermissions(value={"caseinfo:caseInfo:add","caseinfo:caseInfo:edit"},logical=Logical.OR)
	@RequestMapping(value = "saves")
	public String saves(CaseInfo caseInfo, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, caseInfo)){
			return form(caseInfo, model,request);
		}
		try {
			String sta = caseInfo.getStatus();
			String processInstanceId ="";
				CaseInfo t = caseInfoService.get(caseInfo.getId());//从数据库取出记录的值
				MyBeanUtils.copyBeanNotNull2Bean(caseInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
					String tableMap = request.getParameter("tableMap");
					String decode = "";
					if (StringUtils.isNotBlank(tableMap)) {
						try {
							decode = URLDecoder.decode(tableMap, "UTF-8");
						} catch (Exception e) {
							e.printStackTrace();
						}
						JSONArray jsonArray = JSONArray.fromObject(decode);
						dealAccountData(jsonArray, t);
					}
					t.setStatus("2");
					caseInfoService.save(t);//保存
				Map<String, Object> variables = new HashMap<String, Object>();
			if (StringUtils.isNotBlank(sta) && "3".equals(sta)){
				processInstanceId =caseInfoService.get(caseInfo.getId()).getProcessInstanceId();
			}
				String str = caseInfoService.startProcess(caseInfo, variables,processInstanceId);
				if (StringUtils.isNotBlank(str)) {
					addMessage(redirectAttributes, "案例申请提交失败:" + str);
				} else {
					addMessage(redirectAttributes, "案例申请已经提交");
				}
		}catch (Exception e) {
			logger.info(e.getMessage());
			addMessage(redirectAttributes, "申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/index?sign="+"me";
	}
	/**
	 * 获取涉及人员的部门负责人及本人
	 * @param
	 * @return
	 */
	public String getPeopleMaster(){
		User user = UserUtils.getUser();
		String masterId = "";
		Map<Object,Object> map = new HashMap<>();
		map.put("ename","bmzr");
		map.put("companyId",user.getCompany().getId());
		map.put("officeId",user.getOffice().getId());
		masterId += roleDao.queryMasterByEnameAndOfficeId(map);//部门负责人
		String masterIds = masterId+","+user.getId();
		return masterIds;
	}
	/**
	 * 保存资格预审项目
	 */
	@RequestMapping(value = "store")
	public String store(CaseInfo caseInfo, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, caseInfo)){
			return form(caseInfo, model,request);
		}
		try {
			if (!caseInfo.getIsNewRecord()) {//编辑表单保存
				CaseInfo t = caseInfoService.get(caseInfo.getId());//从数据库取出记录的值
				MyBeanUtils.copyBeanNotNull2Bean(caseInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
				t.setCompanyId(UserUtils.getSelectCompany().getId());

				if (StringUtils.isNotBlank(t.getStatus()) && t.getStatus().equals("4")) {
					//更新流程
					caseInfoService.getCaseAct2(t);
					//任务处理
					//caseInfoService.auditSave(t);
					//数据保存
					caseInfoService.save(t);
					addMessage(redirectAttributes, "案例已撤销!");
				} else {
					String tableMap = request.getParameter("tableMap");
					String decode = "";
					if (StringUtils.isNotBlank(tableMap)) {
						try {
							decode = URLDecoder.decode(tableMap, "UTF-8");
						} catch (Exception e) {
							e.printStackTrace();
						}
						JSONArray jsonArray = JSONArray.fromObject(decode);
						dealAccountData(jsonArray, t);
					}
					caseInfoService.save(t);//保存
					addMessage(redirectAttributes, "保存案例成功");
				}
			} else {//新增表单保存
				//案例分享公司
				if (!UserUtils.getUser().isAdmin()) {
					caseInfo.setCompanyName(UserUtils.getSelectCompany().getName());
				} else {
					caseInfo.setCompanyName("总公司");
				}
				String tableMap = request.getParameter("tableMap");
				String decode = "";
				if (StringUtils.isNotBlank(tableMap)) {
					try {
						decode = URLDecoder.decode(tableMap, "UTF-8");
					} catch (Exception e) {
						e.printStackTrace();
					}
					JSONArray jsonArray = JSONArray.fromObject(decode);
					dealAccountData(jsonArray, caseInfo);
				}
				caseInfo.setStatus("1");
				caseInfo.setCompanyId(UserUtils.getSelectCompany().getId());
				caseInfo.setOfficeId(UserUtils.getSelectOffice().getId());
				//caseInfo.setUserids(getPeopleMaster());
				caseInfoService.save(caseInfo);//保存
				addMessage(redirectAttributes, "暂存案例详情成功");
			}
		}catch (Exception e) {
			addMessage(redirectAttributes, "申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/index?sign="+"me";
	}
	/**
	 * 保存资格预审项目
	 */
	@RequestMapping(value = "storeTiming")
	public String storeTiming(CaseInfo caseInfo, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, caseInfo)){
			return form(caseInfo, model,request);
		}
		try {
			if (!caseInfo.getIsNewRecord()) {
				//编辑表单保存(定时任务启动，暂存)
				CaseInfo t = caseInfoService.get(caseInfo.getId());//从数据库取出记录的值
				MyBeanUtils.copyBeanNotNull2Bean(caseInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
					String tableMap = request.getParameter("tableMap");
					String decode = "";
					if (StringUtils.isNotBlank(tableMap)) {
						try {
							decode = URLDecoder.decode(tableMap, "UTF-8");
						} catch (Exception e) {
							e.printStackTrace();
						}
						JSONArray jsonArray = JSONArray.fromObject(decode);
						dealAccountData(jsonArray, t);
					}
					caseInfoService.saveTiming(t);//保存
					addMessage(redirectAttributes, "保存案例成功");
			} else {
				//新增表单保存(定时任务未启动)
				if (!UserUtils.getUser().isAdmin()) {
					caseInfo.setCompanyName(UserUtils.getSelectCompany().getName());
				} else {
					caseInfo.setCompanyName("总公司");
				}
				String tableMap = request.getParameter("tableMap");
				String decode = "";
				if (StringUtils.isNotBlank(tableMap)) {
					try {
						decode = URLDecoder.decode(tableMap, "UTF-8");
					} catch (Exception e) {
						e.printStackTrace();
					}
					JSONArray jsonArray = JSONArray.fromObject(decode);
					dealAccountData(jsonArray, caseInfo);
				}
				caseInfo.setStatus("1");
				caseInfo.setCompanyId(UserUtils.getSelectCompany().getId());
				caseInfo.setOfficeId(UserUtils.getSelectOffice().getId());
				//caseInfo.setUserids(getPeopleMaster());
				caseInfoService.save(caseInfo);//保存
				addMessage(redirectAttributes, "暂存案例详情成功");
			}
		}catch (Exception e) {
			addMessage(redirectAttributes, "申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/index?sign="+"me";
	}
	/**
	 * 处理材料单价
	 * @param jsonArray
	 * @param caseInfo
	 */
	public void dealAccountData(JSONArray jsonArray,CaseInfo caseInfo){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<CaseMaterials> caseMaterialsList = caseInfo.getCaseMaterialsList();
		for (int i = 0; i < jsonArray.size() ; i++) {
			Map<Object,Object> json = (Map<Object,Object>)jsonArray.get(i);
			CaseMaterials caseMaterials = new CaseMaterials();
			caseMaterials.setName(json.get("name")+"");
			caseMaterials.setSpecification(json.get("specification")+"");
			caseMaterials.setCalculateUnit( json.get("calculateUnit")+"");
			caseMaterials.setTaxPrice( json.get("taxPrice")+"");
			caseMaterials.setPrice( json.get("price")+"");
			Date useDate = null;
			if(StringUtils.isNotBlank(json.get("useDate")+"")){
				try {
					useDate = sdf.parse(json.get("useDate")+"");
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			caseMaterials.setUseDate(useDate);
			caseMaterials.setSource( json.get("source")+"");
			caseMaterials.setTax( json.get("tax")+"");
			caseMaterials.setMaterial( json.get("material")+"");
			caseMaterials.setBrand( json.get("brand")+"");
			caseMaterials.setPp( json.get("pp")+"");
			Area area = new Area();
			area.setId(json.get("areaId")+"");
			caseMaterials.setArea(area);
			caseMaterialsList.add(caseMaterials);
			if(!"flag".equals(json.get("flag"))){
				caseMaterials.setId(json.get("flag")+"");
			}else{
				caseMaterials.setId("");
			}
		}
		caseInfo.setCaseMaterialsList(caseMaterialsList);
	}

	/**
	 * 删除案例详情
	 */
	@RequiresPermissions("caseinfo:caseInfo:del")
	@RequestMapping(value = "delete")
	public String delete(CaseInfo caseInfo, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		caseInfoService.delete(caseInfo);
		String sign = request.getParameter("sign");
		addMessage(redirectAttributes, "删除案例详情成功");
		return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/list?sign="+sign;
	}
	@RequiresPermissions("caseinfo:caseInfo:del")
	@RequestMapping(value = "cdelete")
	public String cdelete(CaseInfo caseInfo, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		caseInfoService.delete(caseInfo);
		String sign = request.getParameter("sign");
		addMessage(redirectAttributes, "删除案例详情成功");
		return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/list";
	}

	/**
	 * 批量删除案例详情
	 */
	@RequiresPermissions("caseinfo:caseInfo:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			caseInfoService.delete(caseInfoService.get(id));
		}
		addMessage(redirectAttributes, "删除案例详情成功");
		return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("caseinfo:caseInfo:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(CaseInfo caseInfo, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "案例详情"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<CaseInfo> page = caseInfoService.findPage(new Page<CaseInfo>(request, response, -1), caseInfo);
    		new ExportExcel("案例详情", CaseInfo.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出案例详情记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("caseinfo:caseInfo: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<CaseInfo> list = ei.getDataList(CaseInfo.class);
			for (CaseInfo caseInfo : list){
				try{
					caseInfoService.save(caseInfo);
					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()+"/caseinfo/caseInfo/?repage";
    }
	
	/**
	 * 下载导入案例详情数据模板
	 */
	@RequiresPermissions("caseinfo:caseInfo:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "案例详情数据导入模板.xlsx";
    		List<CaseInfo> list = Lists.newArrayList(); 
    		new ExportExcel("案例详情数据", CaseInfo.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/?repage";
    }
	
	
	/**
	 * 选择所属项目
	 */
	@RequestMapping(value = "selectproject")
	public String selectproject(WorkProject project, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey,String numberLabel,String numberKey,String sortLabel,String sortKey,String createDateLabel,String createDateKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		//Page<WorkProject> page = caseInfoService.findPageByproject(new Page<WorkProject>(request, response),  project);
		Page<WorkProject> page = workProjectService.findPage(new Page<WorkProject>(request, response), project);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "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("numberLabel", numberLabel);
		model.addAttribute("numberKey", numberKey);
		model.addAttribute("sortLabel", sortLabel);
		model.addAttribute("sortKey", sortKey);
		model.addAttribute("createDateLabel", createDateLabel);
		model.addAttribute("createDateKey", createDateKey);
		model.addAttribute("obj", project);
		model.addAttribute("page", page);
		return "modules/sys/gridselectp";
	}
	/**
	 *  单个删除阿里云上的文件，同时更新相关对象的附件信息
	 *  阿里云文件地址http://gangwan-app.oss-cn-hangzhou.aliyuncs.com/attachment-file/workBidingDocument/3fcf03e37b3ba0fd5c7821998e392395.doc
	 *  其中阿里云删除接口所需的参数 key 指的是 attachment-file/workBidingDocument/3fcf03e37b3ba0fd5c7821998e392395.doc
	 * @return
	 */
	@RequestMapping("/deleteFileFromAliyun")
	@ResponseBody
	public HashMap<Object, Object> deleteFileFromAliyun(String attachmentId, String url, Model model){
		if(StringUtils.isNotBlank(attachmentId)) {
			Workattachment workattachment = workattachmentService.get(attachmentId);
			workattachmentService.deleteFileFromAliyun(workattachment, workattachment == null ? url : workattachment.getUrl());
		}
		HashMap<Object, Object> map = Maps.newHashMap();
		map.put("str","success");
		return map;
	}
	/**
	 * 下载附件
	 */
	@RequestMapping("/downLoadAttach")
	public String downLoadAttach(@RequestParam("file") String file,HttpServletRequest request,HttpServletResponse response) throws IOException {
//		file = file.replace("amp;","");
//		String fileName = file.substring(file.lastIndexOf("/") + 1, file.length());
//		String aliyunUrl = Global.getAliyunUrl();
//		String aliDownloadUrl = Global.getAliDownloadUrl();
//		String cons = "";
//		if (file.contains(aliyunUrl)){
//			cons = aliyunUrl;
//		}else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
//			cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
//		}else {
//			cons = aliDownloadUrl;
//		}
//		String key = file.split(cons+"/")[1];
//		new OSSClientUtil().downByStream(key,fileName,response,request.getHeader("USER-AGENT"));
//		return null;
		OutputStream out = null;
		InputStream in = null;
		try {
			file = URLDecoder.decode(file,"UTF-8");
			String path = file.substring(file.indexOf(".com") + 5, file.length());
			String fileName = URLEncoder.encode(file.substring(file.lastIndexOf("/") + 1, file.length()),"UTF-8");
			OssClient ossClient = new OssClient();
			in = ossClient.getObject(path);
			response.reset();//重置 响应头
			response.setContentType("application/x-download");
			response.setHeader("Content-disposition", "attachment; filename=" + fileName);
			out = response.getOutputStream();
			byte[] b = new byte[1024];
			int len;
			while ((len = in.read(b)) > 0){
				response.getOutputStream().write(b, 0, len);
			}
			in.close();
			out.close();
		}catch (IOException e){
			e.printStackTrace();
		}finally {
			if (out != null) {
				out.close();
			}
			if (in != null) {
				in.close();
			}
		}
		return  null;

	}

	/**
	 * 待办任务列表页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"caseInfoTodoList"})
	public String caseInfoTodoList(Act act, HttpServletRequest request, HttpServletResponse response, Model model) {
		act.setProcDefKey("caseInfo");
		List<Act> list = actTaskService.todoList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<Activity> activities = activityService.groupByActivityMenu("ggh3125f1f194c82b0000abcdc750904",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			list.addAll(actTaskService.todoList(act));
		}
		Role role = UserUtils.getSelectRole().get(0);
		List<CaseInfo> lists = new ArrayList<CaseInfo>();
		for (Act a : list) {
			if(a.getTask().getTaskDefinitionKey()!=null && !"modifyApply".equals(a.getTask().getTaskDefinitionKey())) {
				CaseInfo caseInfo = caseInfoService.getByProcessInstanceId(a.getProcInsId());
				if (caseInfo != null && caseInfo.getCompanyId().equals(companyId)) {
					caseInfo.setCreateBy(UserUtils.get(caseInfo.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());
						}
					}
					caseInfo.setAct(a);
					lists.add(caseInfo);
				}
			}
		}
		model.addAttribute("list", lists);
		return "modules/caseinfo/caseInfoTodoList";
	}

	/**
	 * 已办任务
	 * @param act
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"caseInfoHistoricList"})
	public String caseInfoHistoricList (Act act, HttpServletRequest request, HttpServletResponse response, Model model){
		act.setProcDefKey("caseInfo");
		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<Activity> activities = activityService.groupByActivityMenu("ggh3125f1f194c82b0000abcdc750904",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			list.addAll(actTaskService.historicList(act));
		}
		List<CaseInfo> lists = new ArrayList<CaseInfo>();
		for (Act a : list) {
			CaseInfo caseInfo = caseInfoService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
			if (caseInfo != null && caseInfo.getCompanyId().equals(companyId)) {
				if (a.getVars().getMap().get("applyUserId")!=null){
					a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
				}
				caseInfo.setAct(a);
				/*if (com.jeeplus.common.	utils.StringUtils.isNotBlank(caseInfo.getId())){
					caseInfo.setName(officeService.get(companyId).getName());
				}*/
				lists.add(caseInfo);
			}
		}
		model.addAttribute("list", lists);
		return "modules/caseinfo/caseInfoHistoricList";
	}

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

	/**
	 * 读取所有流程
	 * @return
	 */
	@RequestMapping(value = "getProcess")
	public String getProcess(CaseInfo caseInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		//admin 可以查看所有流程  展示注释
//        User user = UserUtils.getUser();
//        if (!user.isAdmin()){
////            leave.setCompanyId(user.getComId());
//            if (!UserUtils.isManager()){
//                caseInfo.setCreateBy(user);
//            }
//        }
		CaseInfo caseInfo1 = caseInfoService.get(caseInfo.getId());
		model.addAttribute("processInstanceId", caseInfo1.getProcessInstanceId());
		return "modules/caseinfo/caseInfoTask";
	}

	/**
	 * 启动流程
	 * @return
	 */
	@RequestMapping(value = "startposs")
	public String startposs(CaseInfo caseInfo, HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes)throws Exception {
		try {
			Map<String, Object> variables = new HashMap<String, Object>();
			CaseInfo t = caseInfoService.get(caseInfo.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(caseInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			t.setStatus("2");
			t.preUpdate();
			caseInfoService.update(t);
			String str = caseInfoService.startProcess(t, variables,null);
			if (StringUtils.isNotBlank(str)) {
				addMessage(redirectAttributes, "案例申请提交失败:" + str);
			} else {
				addMessage(redirectAttributes, "案例申请已经提交");
			}
		}catch (Exception e) {
				addMessage(redirectAttributes, "申请提交失败!");
				addMessage(redirectAttributes, "系统内部错误");
			}
		return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/list?sign=me";
	}

	@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");
		try {
			CaseInfo caseInfo = caseInfoService.get(id);
			caseInfoService.cancelInvalidate(caseInfo,processInstanceId);
		}catch (Exception e){
			logger.info(e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/caseinfo/caseInfo/list?sign=me";
	}
	@ResponseBody
	@RequestMapping("checkSame")
	public AjaxJson checkSame(CaseInfo caseInfo){
		AjaxJson ajaxJson = new AjaxJson();
		//String id = null;
		logger.info(caseInfo.toString());
		if(StringUtils.isBlank(caseInfo.getName())){
			 ajaxJson.getBody().put("data",caseInfo);
			return ajaxJson;
		}else{
			try {
				if (!caseInfo.getIsNewRecord()) {//编辑表单保存
					CaseInfo t = caseInfoService.get(caseInfo.getId());//从数据库取出记录的值
					MyBeanUtils.copyBeanNotNull2Bean(caseInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
					String tableMap = request.getParameter("tableMap");
					String decode = "";
					if (StringUtils.isNotBlank(tableMap)) {
						try {
							decode = URLDecoder.decode(tableMap, "UTF-8");
						} catch (Exception e) {
							e.printStackTrace();
						}
						JSONArray jsonArray = JSONArray.fromObject(decode);
						dealAccountData(jsonArray, t);
					}
					caseInfoService.saveTiming(t);//保存
					//id = t.getId();
					ajaxJson.getBody().put("data",t);
				} else {//新增表单保存
					//案例分享公司
					if (!UserUtils.getUser().isAdmin()) {
						caseInfo.setCompanyName(UserUtils.getSelectCompany().getName());
					} else {
						caseInfo.setCompanyName("总公司");
					}
					String tableMap = request.getParameter("tableMap");
					String decode = "";
					if (StringUtils.isNotBlank(tableMap)) {
						try {
							decode = URLDecoder.decode(tableMap, "UTF-8");
						} catch (Exception e) {
							e.printStackTrace();
						}
						JSONArray jsonArray = JSONArray.fromObject(decode);
						dealAccountData(jsonArray, caseInfo);
					}
					caseInfo.setStatus("1");
					caseInfo.setCompanyId(UserUtils.getSelectCompany().getId());
					caseInfo.setOfficeId(UserUtils.getSelectOffice().getId());
					//caseInfo.setUserids(getPeopleMaster());
					caseInfoService.saveTiming(caseInfo);//保存
					ajaxJson.getBody().put("data",caseInfo);
					//id = caseInfo.getId();
				}
			}catch (Exception e) {
				logger.info(e.getMessage());
			}
		}
		return ajaxJson;
	}
}