/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workinvoice.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.dao.ProjectRecordsDao;
import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
import com.jeeplus.modules.projectrecord.enums.ProjectStatusEnum;
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.AreaService;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysuseroffice.service.UserofficeService;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workbidproject.entity.WorkBidProject;
import com.jeeplus.modules.workbidproject.service.WorkBidProjectService;
import com.jeeplus.modules.workclientinfo.entity.WorkClientBank;
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.workinvoice.entity.WorkInvoice;
import com.jeeplus.modules.workinvoice.service.WorkInvoiceService;
import com.jeeplus.modules.workinvoicealter.entity.WorkInvoiceAlter;
import com.jeeplus.modules.workinvoicealter.service.WorkInvoiceAlterService;
import com.jeeplus.modules.workinvoicedetail.service.WorkInvoiceDetailService;
import com.jeeplus.modules.workproject.service.WorkProjectService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
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.commons.beanutils.BeanUtils;
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.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.util.*;

/**
 * 开票管理Controller
 * @author
 * @version
 */
@Controller
@RequestMapping(value = "${adminPath}/workinvoice/workInvoice")
public class WorkInvoiceController extends BaseController {

	@Autowired
	private WorkInvoiceService workInvoiceService;
	@Autowired
	private AreaService areaService;

	@Autowired
	private WorkClientInfoService workClientInfoService;
	@Autowired
	protected RuntimeService runtimeService;
	@Autowired
	protected ProjectRecordsService projectRecordsService;
	@Autowired
	protected WorkInvoiceDetailService workInvoiceDetailService;
	@Autowired
	protected WorkInvoiceAlterService workInvoiceAlterService;

	@Autowired
	protected WorkContractInfoService workContractInfoService;
	@Autowired
	private WorkBidProjectService workBidProjectService;
	@Autowired
	private WorkProjectService workProjectService;
	protected UserofficeService userofficeService;
	@Autowired
	protected OfficeService officeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	protected WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private ActivityService activityService;

	@Autowired
	private HttpServletRequest request;
	@ModelAttribute
	public WorkInvoice get(@RequestParam(required=false) String id) {
		WorkInvoice entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workInvoiceService.get(id);
		}
		if (entity == null){
			entity = new WorkInvoice();
		}
		return entity;
	}
	
	/**
	 * 开票管理列表页面
	 */
	@RequiresPermissions("workinvoice:workInvoice:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkInvoice workInvoice, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkInvoice> page = workInvoiceService.findPage(new Page<WorkInvoice>(request, response), workInvoice);
		model.addAttribute("page", page);
		return "modules/workinvoice/workInvoiceList";
	}
	/**
	 * 工单执行（完成任务）
	 * @param
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkInvoice workInvoice, Model model,
							RedirectAttributes redirectAttributes) {
//		try{
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workInvoice.getAct().getTaskDefKey();
			List<User> users = null;
			//所属部门
			Office office = officeService.get(workInvoice.getOffice().getId());
			if ("bmzr".equals(taskDefKey)){
				if(("1").equals(workInvoice.getExt())) {
					users = UserUtils.getByProssType(workInvoice.getProcessInstanceId(), 2);
					if (users == null)
						users = UserUtils.getByRoleActivityEnname("scfgld", 1, office.getId(), "5", workInvoice.getCreateBy());
				}else{
					users = UserUtils.getByProssType(workInvoice.getProcessInstanceId(),3);
					if (users==null )
						users = UserUtils.getByRoleActivityEnname("fpgly",3,office.getId(),"5",workInvoice.getCreateBy());
				}
			}else  if ("scbzr".equals(taskDefKey)){
				users = UserUtils.getByProssType(workInvoice.getProcessInstanceId(),3);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("fpgly",1,office.getId(),"5",workInvoice.getCreateBy());
			}else  if ("fpgly".equals(taskDefKey)){
				if(("1").equals(workInvoice.getExt())) {
					users = UserUtils.getByProssType(workInvoice.getProcessInstanceId(), 3);
				}else{
					users = UserUtils.getByProssType(workInvoice.getProcessInstanceId(),1);
				}
			}else if ("modifyApply".equals(taskDefKey)){
				users = UserUtils.getByProssType(workInvoice.getProcessInstanceId(), 1);
			}
			String flag = workInvoice.getAct().getFlag();
			if ("yes".equals(flag) && (users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = "";
				if(("1").equals(workInvoice.getExt())){
					str = workInvoiceService.auditSave(workInvoice,users);
				}else if(("0").equals(workInvoice.getExt())){
					str = workInvoiceService.auditSaveBranch(workInvoice,users);
				}
				addMessage(redirectAttributes, str);
			}
//		}catch (Exception e){
//			addMessage(redirectAttributes, "审批失败:");
//		}

		if (StringUtils.isNotBlank(workInvoice.getHome()) && "home".equals(workInvoice.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
		}
	}
	/**
	 * 查看，增加，编辑开票管理表单页面
	 */
	@RequiresPermissions(value={"workinvoice:workInvoice:view","workinvoice:workInvoice:add","workinvoice:workInvoice:edit"},logical= Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkInvoice workInvoice, Model model) {
		String view = "workInvoiceForm";
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workInvoiceView";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workInvoice.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);
				workInvoice.setAct(act);
				view = "workInvoiceModify";
			}
		}
		// 环节编号
		String taskDefKey = workInvoice.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && ("bmzr".equals(taskDefKey) ||
				"scbzr".equals(taskDefKey))){
			view = "workInvoiceAudit";
		}else  if (StringUtils.isNotBlank(taskDefKey) && "fpgly".equals(taskDefKey)){
			workInvoice.setDrawerName(UserUtils.getUser().getName());
			workInvoice.setInvoiceDate(new Date());
			view = "workInvoiceAuditEnd";//发票管理员操作发票明细页面
		}else if (StringUtils.isNotBlank(taskDefKey) && !taskDefKey.equals("modifyApply")){
			view = "workInvoiceAudit";
		}

		if (StringUtils.isBlank(workInvoice.getId())){
			//workInvoice.setNumber(IdGen.uuid());
			//workInvoice.setInvoiceNumber( (int)((Math.random()*9+1)*100000));
			workInvoice.setInvoiceDate(new Date());
		}
		model.addAttribute("workInvoice", workInvoice);
		return "modules/workinvoice/" + view;
	}

	@RequestMapping("form1")
	public String form1(String id,Model model){
		WorkInvoice workInvoice = workInvoiceService.get(id);
		model.addAttribute("workInvoice", workInvoice);
		return "modules/workinvoice/workInvoiceView";
	}

	/**
	 * 保存开票管理
	 */
	@RequestMapping(value = "save")
	public String save(WorkInvoice workInvoice, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workInvoice)){
			return form(workInvoice, model);
		}

		User user = workInvoice.getCreateBy();
		String invoiceState = workInvoice.getInvoiceState();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
		}
		//启动流程
		workInvoice.setInvoiceState("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(invoiceState) && "3".equals(invoiceState)){
			processInstanceId = workInvoiceService.get(workInvoice.getId()).getProcessInstanceId();
		}
//		try {
			Map<String, Object> variables = Maps.newHashMap();
			WorkClientInfo workClientInfo =workClientInfoService.get(workInvoice.getClient().getId());
			ProjectRecords workProject =projectRecordsService.get(workInvoice.getProject().getId());
			workInvoice.setClient(workClientInfo);
			workInvoice.setProject(workProject);
			workInvoice.setCompanyId(UserUtils.getSelectCompany().getId());
			workInvoice.setOfficeId(UserUtils.getSelectOffice().getId());
			workInvoice.setExt("0");
			String str = "";
			//1总公司0分公司
			if("1".equals(workInvoice.getExt())){
				str = workInvoiceService.save(workInvoice, variables,processInstanceId);
			}else if("0".equals(workInvoice.getExt())){
				str = workInvoiceService.saveBranch(workInvoice, variables,processInstanceId);
			}
			if(StringUtils.isNotBlank(workInvoice.getExt())){
				if (StringUtils.isNotBlank(str)){
					addMessage(redirectAttributes, "发票申请提交失败:"+str);
				}else {
					addMessage(redirectAttributes, "发票申请已经提交");
				}
			}else{
				addMessage(redirectAttributes, "因未选择公司类型，发票申请提交失败");
			}
//		} catch (Exception e) {
//			addMessage(redirectAttributes, "发票申请提交失败!");
//			addMessage(redirectAttributes, "系统内部错误");
//		}
		return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
	}

	/**
	 * 保存开票管理
	 */
	@RequestMapping(value = "store")
	public String store(WorkInvoice workInvoice, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workInvoice)){
			return form(workInvoice, model);
		}
		User user = workInvoice.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		String sta = workInvoice.getInvoiceState();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter) && sta != null){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
		}
		if(!workInvoice.getIsNewRecord()){//编辑表单保存
			WorkInvoice t = workInvoiceService.get(workInvoice.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workInvoice, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workInvoiceService.save(t);//保存
		}else{//新增表单保存
			WorkClientInfo workClientInfo =workClientInfoService.get(workInvoice.getClient().getId());
			ProjectRecords workProject =projectRecordsService.get(workInvoice.getProject().getId());
			workInvoice.setClient(workClientInfo);
			workInvoice.setProject(workProject);
			workInvoice.setCompanyId(UserUtils.getSelectCompany().getId());
			workInvoice.setOfficeId(UserUtils.getSelectOffice().getId());
			workInvoice.setInvoiceState("1");
			workInvoiceService.save(workInvoice);//保存
		}
		addMessage(redirectAttributes, "保存发票成功");
		return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
	}
	/**
	 * 删除开票管理
	 */
	@RequiresPermissions("workinvoice:workInvoice:del")
	@RequestMapping(value = "delete")
	public String delete(WorkInvoice workInvoice, RedirectAttributes redirectAttributes) {
		workInvoiceService.delete(workInvoice);
		addMessage(redirectAttributes, "删除发票管理成功");
		return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
	}
	
	/**
	 * 批量删除开票管理
	 */
	@RequiresPermissions("workinvoice:workInvoice:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workInvoiceService.delete(workInvoiceService.get(id));
		}
		addMessage(redirectAttributes, "删除发票管理成功");
		return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workinvoice:workInvoice:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkInvoice workInvoice, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "发票管理"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkInvoice> page = workInvoiceService.findPage(new Page<WorkInvoice>(request, response, -1), workInvoice);
    		new ExportExcel("发票管理", WorkInvoice.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出发票管理记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workinvoice:workInvoice: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<WorkInvoice> list = ei.getDataList(WorkInvoice.class);
			for (WorkInvoice workInvoice : list){
				try{
					workInvoiceService.save(workInvoice);
					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()+"/workinvoice/workInvoice/?repage";
    }
	
	/**
	 * 下载导入开票管理数据模板
	 */
	@RequiresPermissions("workinvoice:workInvoice:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "发票管理数据导入模板.xlsx";
    		List<WorkInvoice> list = Lists.newArrayList(); 
    		new ExportExcel("发票管理数据", WorkInvoice.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
    }
	
	
	/**
	 * 选择开票单位
	 */
	@RequestMapping(value = "selectclient")
	public String selectclient(WorkClientInfo client, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkClientInfo> page = workClientInfoService.findPage(new Page<WorkClientInfo>(request, response), client);
		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", client);
		model.addAttribute("page", page);
		return "modules/sys/gridInvoice";
	}
	/**
	 * 选择开票项目
	 */
	@RequestMapping(value = "selectproject")
	public String selectproject(ProjectRecords project, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, String ids, HttpServletRequest request, HttpServletResponse response, Model model) {
		project.setCompany(UserUtils.getSelectCompany());
		project.setProjectStatus(ProjectStatusEnum.SIGNED.getValue());//已签状态
		project.setLeaderNameStr(UserUtils.getUser().getName());
		Page<ProjectRecords> page = projectRecordsService.findPage(new Page<ProjectRecords>(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("obj", project);
		model.addAttribute("page",page);
		return "modules/sys/gridinvoiceproject";
	}
	/**
	 * 选择开票项目
	 */
	@RequestMapping(value = "selectprojectperfce")
	public String selectprojectperce(ProjectRecords project, String url,boolean isAll,String type,boolean isSingle, HttpServletRequest request, HttpServletResponse response, Model model) {
		project.setCompany(UserUtils.getSelectCompany());
		project.setProjectStatus(ProjectStatusEnum.SIGNED.getValue());//已签状态
		project.setLeaderNameStr(UserUtils.getUser().getName());
		Page<ProjectRecords> page = projectRecordsService.findPage(new Page<ProjectRecords>(request, response), project);
		model.addAttribute("obj", project);
		model.addAttribute("isSingle", isSingle);
		model.addAttribute("url", url);
		model.addAttribute("isAll", isAll);
		model.addAttribute("type", type);
		model.addAttribute("page", page);
		return "modules/sys/gridprojectperfce";
	}
	//业绩库用
	@RequestMapping(value = "selectprojectperfces")
	public String selectprojectperces(ProjectRecords project, String url,boolean isAll,String type,boolean isSingle, HttpServletRequest request, HttpServletResponse response, Model model) {
		project.setProjectStatus(ProjectStatusEnum.SIGNED.getValue());//已签状态
		Page<ProjectRecords> page = projectRecordsService.findPage(new Page<ProjectRecords>(request, response), project);
		model.addAttribute("obj", project);
		model.addAttribute("isSingle", isSingle);
		model.addAttribute("url", url);
		model.addAttribute("isAll", isAll);
		model.addAttribute("type", type);
		model.addAttribute("page", page);
		return "modules/sys/gridprojectperfce";
	}
	/**
	 * 选择投标项目
	 */
	@RequestMapping(value = "selectprojectt")
	public String selectprojectt(WorkBidProject project, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, String ids, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!"1".equals(UserUtils.getSelectCompany().getId())){
			project.setCompanyId(UserUtils.getSelectCompany().getId());
		}
		project.setStatus("5");
		project.setIsSubcontract("0");
		Page<WorkBidProject> page = workBidProjectService.findPage(new Page<WorkBidProject>(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("obj", project);
		model.addAttribute("page",page);
		return "modules/sys/gridinvoicebidproject";
	}
	/**
	 * 获取项目信息
	 * @return
	 */
	@RequestMapping(value = "getWorkClientInfo")
	@ResponseBody
	public String getWorkClientInfo() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		WorkClientInfo workClientInfo = workClientInfoService.get(obj);
		List<WorkClientBank> list = workClientInfo.getWorkClientBankList();
		String bank = null;
		String bankNumber = null;
		if(list.size()!=0){
			WorkClientBank w = list.get(0);
			bank=w.getOurBank();
			bankNumber=w.getBankNumber();
		}
		/*暂时弃用*/
		/*String province = "";
		if(workClientInfo.getArea()!=null){
			String id = workClientInfo.getArea().getId();
			Area area = areaService.get(id);
			if(area!=null){
				province = area.getParent().getName();
			}
		}*/

		map.put("bank",bank);
		map.put("bankNumber",bankNumber);
		map.put("telephone",workClientInfo.getTelephone());
		map.put("orUnicode",workClientInfo.getUscCode());
		map.put("adress",workClientInfo.getAddress());
		map.put("ids",workClientInfo.getId());
		return JsonMapper.toJsonString(map);
	}
	/**
	 * 获取经办人部门信息
	 * @return
	 */
	@RequestMapping(value = "getUserDp")
	@ResponseBody
	public String getUserDp() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		User u = UserUtils.get(obj);
		map.put("dp",u.getCompany().getName()+"/"+u.getOffice().getName());
		return JsonMapper.toJsonString(map);
	}
	/**
	 * 开票自定义不可撤回
	 * @return
	 */
	@RequestMapping(value = "getReturnBack")
	@ResponseBody
	public String getReturnBack() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		if("ggh3125f1f194c82bdea93555c750905".equals(obj)){
			map.put("dp","no");
		}else {
			map.put("dp","yes");
		}
		return JsonMapper.toJsonString(map);
	}
	/**
	 * 获取项目编号
	 * @return
	 */
	@RequestMapping(value = "getPNumber")
	@ResponseBody
	public String getPNumber() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		ProjectRecords projectRecords = projectRecordsService.getInfo(obj);
		Office company = projectRecordsService.getCompanyById(projectRecords.getCompany().getId());
		map.put("companyName",company.getName());
		map.put("reportName",projectRecords.getReportData().getName());
		map.put("reportId",projectRecords.getReportData().getId());
		map.put("pNumber",projectRecords.getProjectId());//项目编号
		map.put("projectId",projectRecords.getId());//项目id
		map.put("cName",projectRecords.getWorkContractInfo().getClient().getName());//委托方
		map.put("cInfoName",projectRecords.getWorkContractInfo().getName());//合同名称
		map.put("cMoney",projectRecords.getWorkContractInfo().getContractPrice());//合同名称
		String id = projectRecords.getWorkContractInfo().getId();
		WorkContractInfo workContractInfo = workContractInfoService.get(id);
		if(workContractInfo!=null){
			String oid = workContractInfo.getChargeCompany();
			Office office = officeService.get(oid);
			if(office!=null){
				map.put("officeName",office.getTopCompany());//部门
				map.put("officeId",office.getId());//部门
			}
		}
		return JsonMapper.toJsonString(map);
	}
	/**
	 * 获取投标项目编号
	 * @return
	 */
	@RequestMapping(value = "getPNumberr")
	@ResponseBody
	public String getPNumberr() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		WorkBidProject workProject = workBidProjectService.getWB(obj);
		map.put("pNumber",workProject.getProjectNumber());
		return JsonMapper.toJsonString(map);
	}

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

	/**
	 * 已办任务
	 * @param act
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"workInvoiceHistoricList"})
	public String workInvoiceHistoricList (Act act, HttpServletRequest request, HttpServletResponse response, Model model){
		act.setProcDefKey("workinvoice");
		List<Act> list = actTaskService.historicList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<Activity> activities = activityService.groupByActivityMenu("ggh3125f1f194c82bdea93555c750905",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			list.addAll(actTaskService.historicList(act));
		}
		List<WorkInvoice> lists = new ArrayList<WorkInvoice>();
		for (Act a : list) {
			WorkInvoice workInvoice = workInvoiceService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
			if (workInvoice != null && workInvoice.getCompanyId().equals(companyId)) {
				if (a.getVars().getMap().get("applyUserId")!=null){
					a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
				}
				workInvoice.setAct(a);
				lists.add(workInvoice);
			}
		}
		model.addAttribute("list", lists);
		return "modules/workinvoice/workInvoiceHistoricList";
	}

	/**
	 * 审核信息
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnWorkInvoice")
	public String applyOnWorkInvoice(Act act, HttpServletResponse response, Model model) {
		// 获取流程XML上的表单KEY
			String formKey = "/workinvoice/workInvoice/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(WorkInvoice workInvoice, HttpServletRequest request, HttpServletResponse response, Model model) {
		//admin 可以查看所有流程  展示注释
//        User user = UserUtils.getUser();
//        if (!user.isAdmin()){
////            leave.setCompanyId(user.getComId());
//            if (!UserUtils.isManager()){
//                workInvoice.setCreateBy(user);
//            }
//        }
		Page<WorkInvoice> page = workInvoiceService.find(new Page<WorkInvoice>(request, response), workInvoice);
		model.addAttribute("processInstanceId", page.getList().get(0).getProcessInstanceId());
		return "modules/workinvoice/workInvoiceTask";
	}
	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(String id,Model model) {
		WorkInvoice workInvoice = workInvoiceService.get(id);
		model.addAttribute("processInstanceId", workInvoice.getProcessInstanceId());
		return "modules/workinvoice/workInvoiceTask";
	}

	/**
	 * 撤销
	 */
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkInvoice workInvoice,RedirectAttributes redirectAttributes){
		workInvoiceService.cancelInvalidate(workInvoice);
		return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
	}
	@RequiresPermissions(value={"workinvoice:workInvoice:alteredit"},logical= Logical.OR)
	@RequestMapping(value = "alterForm")
	public String alterForm(WorkInvoice workInvoice, Model model) {
		String id = workInvoice.getId();
		WorkInvoiceAlter workInvoiceAlter = new WorkInvoiceAlter();
		workInvoiceAlter.setWorkInvoice(workInvoice);
		try {
			BeanUtils.copyProperties(workInvoiceAlter,workInvoice);
			workInvoiceAlter.setId(null);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		workInvoiceAlter.setCreateBy(UserUtils.getUser());
		workInvoiceAlter.setCreateDate(new Date());
	/*	if(workInvoice!=null){
		 	workInvoiceAlter.setProject(workInvoice.getProject());
		 	workInvoiceAlter.setNumber(workInvoice.getNumber());
		 	workInvoiceAlter.setOffice(workInvoice.getOffice());
			workInvoiceAlter.setExt(workInvoice.getExt());
			workInvoiceAlter.setInvoiceType(workInvoice.getInvoiceType());
			workInvoiceAlter.setClient(workInvoice.getClient());
			workInvoiceAlter.setBank(workInvoice.getBank());
			workInvoiceAlter.setBankNumber(workInvoice.getBankNumber());
			workInvoiceAlter.setMoney(workInvoice.getMoney());
			workInvoiceAlter.setContent(workInvoice.getContent());
			workInvoiceAlter.setDrawerName(workInvoice.getDrawerName());
			workInvoiceAlter.setInvoiceDate(workInvoice.getInvoiceDate());
			workInvoiceAlter.setTakeDate(workInvoice.getTakeDate());
			workInvoiceAlter.setWorkAccountList(workInvoice.getWorkAccountList());
		}*/

		model.addAttribute("workInvoiceAlter", workInvoiceAlter);
		return "modules/workinvoicealter/workInvoiceFormas";
	}
	/*————————————————————————————————————————————*/
	/**
	 * 启动流程(弃用)
	 * @return
	 */
	@RequestMapping(value = "startposs")
	public String startposs(WorkInvoice workInvoice, HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes)throws Exception {
		Map<String, Object> variables = new HashMap<String, Object>();
		WorkInvoice t = workInvoiceService.get(workInvoice.getId());//从数据库取出记录的值
		MyBeanUtils.copyBeanNotNull2Bean(workInvoice, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
		t.setInvoiceState("2");
		t.preUpdate();
		workInvoiceService.update(t);
		String processInstanceId = "";
		String str = workInvoiceService.save(workInvoice, variables,processInstanceId);
		addMessage(redirectAttributes, "启动流程成功");
		return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
	}
	/**
	 * 收款
	 * @return
	 */
	@RequestMapping(value = "receipt")
	public String receipt(WorkInvoice workInvoice, HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes)throws Exception {
		Map<String, Object> variables = new HashMap<String, Object>();
		WorkInvoice t = workInvoiceService.get(workInvoice.getId());//从数据库取出记录的值
		MyBeanUtils.copyBeanNotNull2Bean(workInvoice, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
		t.setIsCharge("2");
		t.preUpdate();
		workInvoiceService.update(t);
		workInvoiceService.save(t);
		addMessage(redirectAttributes, "收款成功");
		//加通知
		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setUser(workInvoice.getCreateBy());
		workProjectNotify.setRemarks("待通知");
		workProjectNotify.setTitle("发票管理-已收款!");
		workProjectNotify.setNotifyId(workInvoice.getId());
		workProjectNotify.setCompanyId(workInvoice.getCompanyId());
		workProjectNotify.setContent(workInvoice.getAct().getComment());
		workProjectNotify.setType("21");//开票管理对应type21
		workProjectNotify.setStatus("0");
		workProjectNotifyService.save(workProjectNotify);
		return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
	}
	/**
	 * 取消收款
	 * @return
	 */
	@RequestMapping(value = "canclereceipt")
	public String canclereceipt(WorkInvoice workInvoice, HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes)throws Exception {
		Map<String, Object> variables = new HashMap<String, Object>();
		WorkInvoice t = workInvoiceService.get(workInvoice.getId());//从数据库取出记录的值
		MyBeanUtils.copyBeanNotNull2Bean(workInvoice, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
		t.setIsCharge("1");
		t.preUpdate();
		workInvoiceService.update(t);
		workInvoiceService.save(t);
		addMessage(redirectAttributes, "取消收款成功");
		//加通知
		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setUser(workInvoice.getCreateBy());
		workProjectNotify.setRemarks("待通知");
		workProjectNotify.setTitle("发票管理-已取消收款!");
		workProjectNotify.setNotifyId(workInvoice.getId());
		workProjectNotify.setCompanyId(workInvoice.getCompanyId());
		workProjectNotify.setContent(workInvoice.getAct().getComment());
		workProjectNotify.setType("21");//开票管理对应type21
		workProjectNotify.setStatus("0");
		workProjectNotifyService.save(workProjectNotify);
		return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
	}
	/**
	 * 发票作废页面跳转
	 */
	@RequestMapping(value = "cancle")
	public String cancle(WorkInvoice workInvoice, Model model) {
		model.addAttribute("workInvoice", workInvoice);
		return "modules/workinvoice/workInvoiceCancle";
	}
	/**
	 * 发票作废
	 * @return
	 */
	@RequestMapping(value = "cancleinvoice")
	public String cancleinvoice(WorkInvoice workInvoice, HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes)throws Exception {
		Map<String, Object> variables = new HashMap<String, Object>();
		WorkInvoice t = workInvoiceService.get(workInvoice.getId());//从数据库取出记录的值
		MyBeanUtils.copyBeanNotNull2Bean(workInvoice, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
		Role r = UserUtils.getSelectRole().get(0);
		t.preUpdate();
		t.setInvoiceState("4");
		workInvoiceService.update(t);
		workInvoiceService.save(t);
		addMessage(redirectAttributes, "发票已经作废成功");

		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setUser(workInvoice.getCreateBy());
		workProjectNotify.setRemarks("待通知");
		workProjectNotify.setTitle("发票管理-已被财务作废!");
		workProjectNotify.setNotifyId(workInvoice.getId());
		workProjectNotify.setCompanyId(workInvoice.getCompanyId());
		workProjectNotify.setContent(workInvoice.getAct().getComment());
		workProjectNotify.setType("21");//开票管理对应type21
		workProjectNotify.setStatus("0");
		workProjectNotifyService.save(workProjectNotify);
		//作废是否启动流程
//		if(r.getEnname().equals("SSRHaccount")){
//			t.setInvoiceState("4");
//			workInvoiceService.update(t);
//			workInvoiceService.save(t);
//			addMessage(redirectAttributes, "发票已经作废成功");
//		}else{
//			workInvoiceService.update(t);
//			workInvoiceService.saveCancle(workInvoice, variables);
//			addMessage(redirectAttributes, "提交审批'" + workInvoice.getDrawer().getName() + "'成功");
//		}
		return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
	}

	/**
	 * 工单执行（完成任务）
	 * @param
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAuditCancle")
	public String saveAuditCancle(WorkInvoice workInvoice, Model model) {
//		if (StringUtils.isBlank(workInvoice.getAct().getFlag())
//				|| StringUtils.isBlank(workInvoice.getAct().getComment())){
//			addMessage(model, "请填写审核意见。");
//			return form(workInvoice, model);
//		}
		workInvoiceService.cancleSave(workInvoice);
		//return "redirect:" + adminPath + "/act/task";
		return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
	}
/*--------------------------分割线---------------------------------*/

}