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

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.mapper.JsonMapper;
import com.jeeplus.common.utils.IdGen;
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.utils.UserUtils;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workinvoice.entity.WorkInvoice;
import com.jeeplus.modules.workinvoice.service.WorkInvoiceService;
import com.jeeplus.modules.workinvoicereturn.service.WorkInvoiceReturnService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.ibatis.annotations.Param;
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 com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.workinvoicedetail.entity.WorkInvoiceDetail;
import com.jeeplus.modules.workinvoicedetail.service.WorkInvoiceDetailService;

/**
 * 发票明细Controller
 * @author lw
 * @version 2018-05-09
 */
@Controller
@RequestMapping(value = "${adminPath}/workinvoicedetail/workInvoiceDetail")
public class WorkInvoiceDetailController extends BaseController {

	@Autowired
	private WorkInvoiceDetailService workInvoiceDetailService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkInvoiceService workInvoiceService;
	@Autowired
	private ProjectRecordsService projectRecordsService;
	@Autowired
	private WorkInvoiceReturnService invoiceReturnService;
	@ModelAttribute
	public WorkInvoiceDetail get(@RequestParam(required=false) String id) {
		WorkInvoiceDetail entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workInvoiceDetailService.get(id);
		}
		if (entity == null){
			entity = new WorkInvoiceDetail();
		}
		return entity;
	}
	
	/**
	 * 发票明细列表页面
	 */
		@RequiresPermissions("workinvoicedetail:workInvoiceDetail:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkInvoiceDetail workInvoiceDetail, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkInvoiceDetail> page = workInvoiceDetailService.findPages(new Page<WorkInvoiceDetail>(request, response), workInvoiceDetail);
		model.addAttribute("page", page);
		return "modules/workinvoicedetail/workInvoiceDetailList";
	}

	/**
	 * 查看，增加，编辑发票明细表单页面
	 */
	@RequestMapping(value = "form")
	public String form(WorkInvoiceDetail workInvoiceDetail, Model model) {
		String view = "workInvoiceDetailFormAdd";
		Office office = UserUtils.getSelectOffice();
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workInvoiceDetailFormDetail";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workInvoiceDetail.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);
				workInvoiceDetail.setAct(act);
				view = "workInvoiceDetailModify";
			}
		}
		// 环节编号
		String taskDefKey = workInvoiceDetail.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && !taskDefKey.equals("modifyApply")){
			view = "workInvoiceDetailAudit";
		}
		if(StringUtils.isBlank(workInvoiceDetail.getReturnNumber())){
			//workInvoiceDetail.setReturnNumber(IdGen.uuid());
			workInvoiceDetail.setReturnUser(UserUtils.getUser().getName());
		}
		if(StringUtils.isBlank(workInvoiceDetail.getReturnUser())){
			workInvoiceDetail.setReturnUser(UserUtils.getUser().getName());
		}
		model.addAttribute("workInvoiceDetail", workInvoiceDetail);
		return "modules/workinvoicedetail/"+view;
	}
	@RequestMapping(value = "store")
	public String store(WorkInvoiceDetail workInvoiceDetail,
						Model model,
						RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workInvoiceDetail)){
			return form(workInvoiceDetail, model);
		}

		User user = workInvoiceDetail.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		String sta = workInvoiceDetail.getStatus();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter) && sta != null){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workinvoicedetail/workInvoiceDetail/?repage";
		}
		workInvoiceDetail.setStatus("1"); //暂存状态
		workInvoiceDetail.setComId(UserUtils.getSelectCompany().getId());
		workInvoiceDetail.setOfficeId(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(workInvoiceDetail.getProcessInstanceId()) && workInvoiceDetail.getProcessInstanceId().equals("NULL")){
			workInvoiceDetail.setProcessInstanceId("");
		}
		if(!workInvoiceDetail.getIsNewRecord()){//编辑表单保存
			WorkInvoiceDetail t = workInvoiceDetailService.get(workInvoiceDetail.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workInvoiceDetail, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			t.setSign("退票");
			workInvoiceDetailService.save(t);//保存
		}else{//新增表单保存
			workInvoiceDetail.setSign("退票");
			workInvoiceDetailService.save(workInvoiceDetail);//保存
		}
		addMessage(redirectAttributes, "退票申请暂存成功");
		return "redirect:"+Global.getAdminPath()+"/workinvoicedetail/workInvoiceDetail/?repage";
	}
	/**
	 * 保存发票明细
	 */
	@RequestMapping(value = "save")
	public String save(WorkInvoiceDetail workInvoiceDetail, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workInvoiceDetail)){
			return form(workInvoiceDetail, model);
		}
		User user = workInvoiceDetail.getCreateBy();
		String sta = workInvoiceDetail.getStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workinvoicedetail/workInvoiceDetail/?repage";
		}
		//状态设置为审核中
		workInvoiceDetail.setStatus("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workInvoiceDetailService.get(workInvoiceDetail.getId()).getProcessInstanceId();
		}
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workInvoiceDetail.setComId(UserUtils.getSelectCompany().getId());
			workInvoiceDetail.setSign("退票");
			String str = workInvoiceDetailService.saves(workInvoiceDetail, variables,processInstanceId);
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "退票申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "退票申请已经提交");
			}

		} catch (Exception e) {
			addMessage(redirectAttributes, "退票申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/workinvoicedetail/workInvoiceDetail/?repage";
	}
	
	/**
	 * 删除发票明细
	 */
	@RequiresPermissions("workinvoicedetail:workInvoiceDetail:del")
	@RequestMapping(value = "delete")
	public String delete(WorkInvoiceDetail workInvoiceDetail, RedirectAttributes redirectAttributes) {
		workInvoiceDetailService.deletes(workInvoiceDetail);
		addMessage(redirectAttributes, "删除退票申请成功");
		return "redirect:"+Global.getAdminPath()+"/workinvoicedetail/workInvoiceDetail/?repage";
	}

	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkInvoiceDetail workInvoiceDetail, Model model,
							RedirectAttributes redirectAttributes) {
		String str = workInvoiceDetailService.auditSave(workInvoiceDetail);
		addMessage(redirectAttributes, str);
		if (StringUtils.isNotBlank(workInvoiceDetail.getHome()) && "home".equals(workInvoiceDetail.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			return "redirect:"+Global.getAdminPath()+"/workinvoicedetail/workInvoiceDetail/?repage";
		}
	}
	/**
	 * 批量删除发票明细
	 */
	@RequiresPermissions("workinvoicedetail:workInvoiceDetail:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workInvoiceDetailService.delete(workInvoiceDetailService.get(id));
		}
		addMessage(redirectAttributes, "删除发票明细成功");
		return "redirect:"+Global.getAdminPath()+"/workinvoicedetail/workInvoiceDetail/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workinvoicedetail:workInvoiceDetail:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkInvoiceDetail workInvoiceDetail, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "发票明细"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkInvoiceDetail> page = workInvoiceDetailService.findPages(new Page<WorkInvoiceDetail>(request, response, -1), workInvoiceDetail);
    		new ExportExcel("发票明细", WorkInvoiceDetail.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出发票明细记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workinvoicedetail/workInvoiceDetail/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workinvoicedetail:workInvoiceDetail: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<WorkInvoiceDetail> list = ei.getDataList(WorkInvoiceDetail.class);
			for (WorkInvoiceDetail workInvoiceDetail : list){
				try{
					workInvoiceDetailService.save(workInvoiceDetail);
					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()+"/workinvoicedetail/workInvoiceDetail/?repage";
    }
	
	/**
	 * 下载导入发票明细数据模板
	 */
	@RequiresPermissions("workinvoicedetail:workInvoiceDetail:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "发票明细数据导入模板.xlsx";
    		List<WorkInvoiceDetail> list = Lists.newArrayList(); 
    		new ExportExcel("发票明细数据", WorkInvoiceDetail.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workinvoicedetail/workInvoiceDetail/?repage";
    }
	/**
	 * 查询待办列表
	 * @return
	 */

	@RequestMapping("/queryToList")
	public String queryToList(Act act,Model model){
		act.setProcDefKey("workinvoicereturn");
		List<Act> list = actTaskService.todoList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<Activity> activities = activityService.groupByActivityMenu("ggh3125f1f194c82bdea9uiopc750906",companyId);//menuid
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			list.addAll(actTaskService.todoList(act));
		}
		Role role = UserUtils.getSelectRole().get(0);
		List<WorkInvoiceDetail> lists = new ArrayList<WorkInvoiceDetail>();
		for (Act a : list) {
			if(a.getTask().getTaskDefinitionKey()!=null && !"modifyApply".equals(a.getTask().getTaskDefinitionKey())) {
				WorkInvoiceDetail workInvoiceDetail = workInvoiceDetailService.getByProcessInstanceId(a.getProcInsId());
				if(workInvoiceDetail != null) {
					workInvoiceDetail = workInvoiceDetailService.get(workInvoiceDetail.getId());
					//if (workInvoiceDetail != null && workInvoiceDetail.getComId().equals(companyId)) {
					workInvoiceDetail.setCreateBy(UserUtils.get(workInvoiceDetail.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());
						}
					}
					workInvoiceDetail.setAct(a);
					lists.add(workInvoiceDetail);
					//}
				}
			}
		}
		model.addAttribute("list", lists);
		return "modules/workinvoicedetail/workInvoiceDetailTodoList";
	}
	/**
	 * 查询已办列表
	 * @return
	 */
	@RequestMapping("/queryCompleteList")
	public String queryCompleteList(Act act,HttpServletRequest request,HttpServletResponse response,Model model){
		act.setProcDefKey("workinvoicereturn");
		List<Act> list = actTaskService.historicList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<Activity> activities = activityService.groupByActivityMenu("ggh3125f1f194c82bdea9uiopc750906",companyId);//menuid
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			list.addAll(actTaskService.historicList(act));
		}
		List<WorkInvoiceDetail> lists = new ArrayList<WorkInvoiceDetail>();
		for (Act a : list) {
			WorkInvoiceDetail workInvoiceDetail = workInvoiceDetailService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
			if(workInvoiceDetail!=null){
			workInvoiceDetail = workInvoiceDetailService.get(workInvoiceDetail.getId());
			//if (workInvoiceDetail != null && workInvoiceDetail.getComId().equals(companyId)) {
				if (a.getVars().getMap().get("applyUserId")!=null){
					a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
				}

					workInvoiceDetail.setAct(a);
					lists.add(workInvoiceDetail);
				}

			//}
		}
		model.addAttribute("list", lists);
		return "modules/workinvoicedetail/workInvoiceDetailHistoricList";
	}
	/**
	 * 审核信息
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnLeave")
	public String applyOnCompany(Act act, HttpServletResponse response, Model model) {
		// 获取流程XML上的表单KEY
		String formKey = "/workinvoicedetail/workInvoiceDetail/form";
		// 获取流程实例对象
		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 = "getProcessOne")
	public String getProcessOne(WorkInvoiceDetail workInvoiceDetail,Model model) {
		model.addAttribute("processInstanceId", workInvoiceDetail.getProcessInstanceId());
		return "modules/workinvoicedetail/workInvoiceDetailTask";
	}
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkInvoiceDetail workInvoiceDetail,RedirectAttributes redirectAttributes){
		workInvoiceDetailService.cancelInvalidate(workInvoiceDetail);
		return "redirect:"+Global.getAdminPath()+"/workinvoicedetail/workInvoiceDetail/?repage";
	}
	/**
	 * 选择发票
	 */
	@RequestMapping(value = "selectinvoice")
	public String selectcontractId(WorkInvoiceDetail invoice, String invoiceIds, String url, String type, String isTotal, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!"1".equals(UserUtils.getSelectCompany().getId())){
			invoice.setComId(UserUtils.getSelectCompany().getId());
		}
		if (StringUtils.isNotBlank(invoiceIds)){
			String[] split = invoiceIds.split(",");
			invoice.setExclusiveIds(split);
		}
		invoice.setState("正常");
		invoice.setBackSign("正常");
		Page<WorkInvoiceDetail> page = workInvoiceDetailService.findPageWithDept(new Page<WorkInvoiceDetail>(request, response),  invoice);
		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("obj", invoice);
		model.addAttribute("page", page);
		return "modules/sys/gridselectdetail";
	}

	/**
	 * 退票选择发票
	 */
	@RequestMapping(value = "selectinvoices")
	public String selectcontractIds(WorkInvoiceDetail invoice, String invoiceIds, String url, String type, String isTotal, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!"1".equals(UserUtils.getSelectCompany().getId())){
			invoice.setComId(UserUtils.getSelectCompany().getId());
		}
		invoice.setState("正常");
		invoice.setBackSign("正常");
		invoice.setCreateBy(UserUtils.getUser());
		Page<WorkInvoiceDetail> page = workInvoiceDetailService.findPageReturn(new Page<WorkInvoiceDetail>(request, response),  invoice);
		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("obj", invoice);
		model.addAttribute("page", page);
		return "modules/sys/gridselectdetail";
	}
	/**
	 * 获取项目信息
	 * @return
	 */
	@RequestMapping(value = "getWorkInvoice")
	@ResponseBody
	public String getWorkClientInfo() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		WorkInvoiceDetail workInvoiceDetail = workInvoiceDetailService.get(obj);
		WorkInvoice workInvoice = workInvoiceDetail.getWorkInvoice();
		if(workInvoice!=null){
			if(workInvoice.getProject()!=null){
				ProjectRecords projectRecords = workInvoice.getProject();
				map.put("cInfoName",workInvoice.getProject().getProjectName());
				map.put("pNumber",workInvoice.getProject().getProjectId());
				if(workInvoice.getProject().getWorkContractInfo()!=null){
					map.put("cName",workInvoice.getProject().getWorkContractInfo().getName());
					if(workInvoice.getProject().getWorkContractInfo().getClient()!=null){
						map.put("clientName",workInvoice.getProject().getWorkContractInfo().getClient().getName());
					}
				}
				//设置项目组成员
				projectRecordsService.queryUserNames(projectRecords);
				map.put("leaderName",projectRecords.getLeaderNameStr());
				/*if(projectRecords.getProjectLeaders()!=null&&projectRecords.getProjectLeaders().size()>1){
					StringBuffer name = new StringBuffer();
					for (User u:
							projectRecords.getProjectLeaders()) {
						name.append(","+u.getName());
					}
					map.put("leaderName",name.toString());
				}else if(projectRecords.getProjectLeaders()!=null&&projectRecords.getProjectLeaders().size()==1){
					StringBuffer name = new StringBuffer();
					for (User u:
							projectRecords.getProjectLeaders()) {
						name.append(u.getName());
					}
					map.put("leaderName",name.toString());
				}*/
			}
		}
		if(workInvoice.getOffice()!=null){
			map.put("officeName",workInvoice.getOffice().getName());
		}
		if("1".equals(workInvoice.getInvoiceType())){
			map.put("invoiceType","专票");
		}else if("2".equals(workInvoice.getInvoiceType())){
			map.put("invoiceType","普票");
		}
		map.put("wid",workInvoice.getId());
		if(workInvoice.getClient()!=null){
			map.put("invoiceCName",workInvoice.getClient().getName());
			map.put("orUnicode",workInvoice.getOrUnicode());
			map.put("address",workInvoice.getAddress());
			map.put("telephone",workInvoice.getTelephone());
		}
		map.put("bank",workInvoice.getBank());
		map.put("bankNumber",workInvoice.getBankNumber());
		map.put("startDate",workInvoice.getInvoiceDate() == null ? "" : sdf.format(workInvoice.getInvoiceDate()));
		map.put("totalMoney",workInvoiceDetail.getTotalMoney());
		map.put("taxMoney",workInvoiceDetail.getTaxMoney());
		map.put("tax",workInvoiceDetail.getTax());
		map.put("taxRate",workInvoiceDetail.getTaxRate());
		map.put("number",workInvoiceDetail.getNumber());
		return JsonMapper.toJsonString(map);
	}

	@RequestMapping(value = "ajaxInvoice")
    @ResponseBody
    public AjaxJson ajaxGet(@Param("id")String id){
	    AjaxJson ajaxJson = new AjaxJson();
        WorkInvoiceDetail workInvoiceDetail = workInvoiceDetailService.get(id);
        ajaxJson.getBody().put("invoice",workInvoiceDetail);
        return ajaxJson;
    }
	@ResponseBody
	@RequestMapping("checkSame")
	public String checkSame(){
		String number =  request.getParameter("number");
		String oldNumber =  request.getParameter("oldNumber");
		if(number!=null&&number.equals(oldNumber)){
			return "true";
		}else if(number!=null){
			int cou=workInvoiceDetailService.countByNumAndComp(number,UserUtils.getSelectCompany().getId());
			if (cou==0){
				cou = invoiceReturnService.countByNumAndComp(number,UserUtils.getSelectCompany().getId());
				if(cou==0){
					return "true";
				}
			}
		}
		return "false";
	}
}