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

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
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.officeintroduce.dao.OfficeintroduceDao;
import com.jeeplus.modules.officeintroduce.entity.Officeintroduce;
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.entity.Workattachment;
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.workbidingdocument.entity.WorkBidingDocument;
import com.jeeplus.modules.workbidingdocument.service.WorkBidingDocumentService;
import com.jeeplus.modules.workbidproject.entity.WorkBidProject;
import com.jeeplus.modules.workbidproject.service.WorkBidProjectService;
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.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

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

/**
 * 标书编制Controller
 * @author fgy
 * @version 2017-10-16
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "${adminPath}/workbidingdocument/workBidingDocument")
public class WorkBidingDocumentController extends BaseController {

	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkBidingDocumentService workBidingDocumentService;
	@Autowired
	private WorkBidProjectService workBidProjectService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkattachmentService workattachmentService;
	@Autowired
	private OfficeintroduceDao officeintroduceDao;
	@Autowired
	private ActivityService activityService;

	@ModelAttribute
	public WorkBidingDocument get(@RequestParam(value = "workBidProjectId",required=false) String workBidProjectId ,
								  @RequestParam(value = "id" ,required = false) String id) {
		WorkBidingDocument entity = null;
		WorkBidProject workBidProject = null ;
		if (StringUtils.isNotBlank(workBidProjectId) && StringUtils.isBlank(id)){
			workBidProject = workBidProjectService.get(workBidProjectId);
			entity = workBidingDocumentService.getByWorkBidProject(workBidProjectId);
		}else if(StringUtils.isNotBlank(id) && StringUtils.isBlank(workBidProjectId)){
			entity = workBidingDocumentService.getById(id);
			workBidProject = workBidProjectService.get(entity.getWorkBidProject().getId());
		}else if(StringUtils.isNotBlank(id) && StringUtils.isNotBlank(workBidProjectId)){
			workBidProject = workBidProjectService.get(workBidProjectId);
			entity = workBidingDocumentService.getByWorkBidProject(workBidProjectId);
		}
		if (entity == null){
			entity = new WorkBidingDocument();
		}
        entity.setWorkBidProject(workBidProject);
        return entity;
	}
	
	/**
	 * 项目列表页面
	 * （1、资格预审通过状态为0，项目登记通过状态为3，可以进行标书编制的相关操作）
	 * （2、标书状态为：0待编制--标书编制，1暂存4未通过--修改标书，2审核中3已通过--流程追踪，3已通过--只有审核该标书的部门负责人可修改）
	 */
	@RequiresPermissions("workbidingdocument:workBidingDocument:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkBidingDocument workBidingDocument, HttpServletRequest request, HttpServletResponse response, Model model) {
		//只是普通员工
		if(!UserUtils.getSelectRoleInfo()){
			String id = UserUtils.getUser().getId();
			workBidingDocument.setQueryCon(id);
		}
		Page<WorkBidingDocument> page = workBidingDocumentService.findPage(new Page<WorkBidingDocument>(request,response),workBidingDocument);
		model.addAttribute("page", page);

		//审核已通过的标书，允许审核该标书的部门负责人进行修改
		/*if(role != null && role.getEnname().contains("bmzr")){
			model.addAttribute("modifiable","1");
		}*/

		return "modules/workbidingdocument/workBidingDocumentList";
	}

	/**
	 * 中标维护
	 */
	@RequestMapping("maintain")
	public String maintain(WorkBidingDocument workBidingDocument,HttpServletRequest request,HttpServletResponse response,Model model){
		Page<WorkBidingDocument> page = workBidingDocumentService.documentMaintain(new Page<WorkBidingDocument>(request,response),workBidingDocument);
		model.addAttribute("page",page);
		return "modules/workbidingdocument/workBidingDocumentMaintain";
	}

	/**
	 * 选择送标员
	 */
	@ResponseBody
	@RequestMapping("senderSelect")
	public String senderSelect(@RequestParam(value = "senderId",required = false)String senderId,@RequestParam(value = "workBidingDocumentId")String workBidingDocumentId){
		workBidingDocumentService.updateSender(senderId , workBidingDocumentId);
		String senderName = "";
		if(StringUtils.isNotBlank(senderId) && StringUtils.isNotBlank(UserUtils.get(senderId).getName())){
			senderName = UserUtils.get(senderId).getName();
		}
		return senderName;
	}

	/**
	 *  确认定投标列表(只有送标员可操作)
	 */
	@RequestMapping("confirm")
	public String confirm(WorkBidingDocument workBidingDocument,HttpServletRequest request,HttpServletResponse response,Model model){
		Page<WorkBidingDocument> page = workBidingDocumentService.documentConfirm(new Page<WorkBidingDocument>(request,response),workBidingDocument);
		model.addAttribute("page",page);
		return "modules/workbidingdocument/workBidingDocumentConfirm";
	}

	/**
	 * 确认定投标时(bid_status = 1)，可以修改项目信息
	 */
	@RequestMapping("confirmForm")
	public String confirmForm(@RequestParam("workBidProjectId")String workBidProjectId,HttpServletRequest request,HttpServletResponse response,Model model) throws Exception {
		WorkBidProject workBidProject = workBidProjectService.get(workBidProjectId);
		model.addAttribute("workBidProject", workBidProject);
		return "modules/workbidingdocument/workBidingDocumentConfirmForm";
	}
	/**
	 * 最后修改项目信息，更改中标状态为投标进行中
	 */
	@RequestMapping("confirmSave")
	public String confirmSave(WorkBidProject workBidProject,HttpServletRequest request,HttpServletResponse response,Model model) throws Exception {
		WorkBidingDocument workBidingDocument = workBidingDocumentService.getByWorkBidProject(workBidProject.getId());

		workBidingDocumentService.confirmSave(workBidProject,workBidingDocument);

		WorkBidingDocument document = new WorkBidingDocument();
		return confirm(document,request,response,model);
	}
	/**
	 * 查看，增加，编辑标书表单页面
	 */
	@RequiresPermissions(value={"workbidingdocument:workBidingDocument:view","workbidingdocument:workBidingDocument:add","workbidingdocument:workBidingDocument:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkBidingDocument workBidingDocument,Model model,
					   @RequestParam(value = "view",required = false)String view,
					   @RequestParam(value = "again",required = false)String again) {

		if(StringUtils.isBlank(workBidingDocument.getCompanyId())){
			workBidingDocument.setCompanyId(UserUtils.getSelectCompany().getId());
		}

		Officeintroduce officeintroduce = officeintroduceDao.findUniqueByProperty("sysoffice_id",workBidingDocument.getCompanyId());
		List<Workattachment> attachmentList = workBidingDocumentService.findAttachment(workBidingDocument);
		model.addAttribute("officeintroduce",officeintroduce==null?"":officeintroduce.getIntroduce());
		model.addAttribute("workAttachmentList",attachmentList);
		model.addAttribute("workBidingDocument", workBidingDocument);
		model.addAttribute("workBidProject",workBidingDocument.getWorkBidProject());
		model.addAttribute("again",again);

		if(workBidingDocument.getAct()!=null && StringUtils.isNotBlank(workBidingDocument.getAct().getTaskId())){
			String taskId = workBidingDocument.getAct().getTaskId();
			return "modules/workbidingdocument/workBidingDocumentAudit";
		}

		if(StringUtils.isNotBlank(view)){
			return "modules/workbidingdocument/workBidingDocumentView";
		}else{
			return "modules/workbidingdocument/workBidingDocumentForm";
		}
	}

	/**
	 * 保存标书（提交操作，修改status=2,进入审核流程）
	 */
	@RequiresPermissions(value={"workbidingdocument:workBidingDocument:add","workbidingdocument:workBidingDocument:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkBidingDocument workBidingDocument,Model model, RedirectAttributes redirectAttributes,
						HttpServletRequest request) throws Exception{
		if (!beanValidator(model, workBidingDocument)){
			return form(workBidingDocument,model,"","");
		}
		String again = request.getParameter("again");
		//保存标书信息并进入审核流程(0待编制，1暂存，2审核中，3已通过，4未通过，5已撤销)
		workBidingDocumentService.save(workBidingDocument,"2",again);

		addMessage(redirectAttributes, "保存标书成功");
		return "redirect:"+Global.getAdminPath()+"/workbidingdocument/workBidingDocument/?repage";
	}

	/**
	 * 保存标书（暂存操作,修改status=1）
	 */
	@RequiresPermissions(value={"workbidingdocument:workBidingDocument:add","workbidingdocument:workBidingDocument:edit"},logical=Logical.OR)
	@RequestMapping(value = "toStore")
	public String toStore(WorkBidingDocument workBidingDocument,Model model, RedirectAttributes redirectAttributes,
					  HttpServletRequest request) throws Exception{
		if (!beanValidator(model, workBidingDocument)){
			return form(workBidingDocument,model,"","");
		}
		String again = request.getParameter("again");
		//暂存标书信息，不走审核流程
		workBidingDocumentService.save(workBidingDocument,"1",again);

		addMessage(redirectAttributes, "暂存标书成功");
		return "redirect:"+Global.getAdminPath()+"/workbidingdocument/workBidingDocument/?repage";
	}
	/**
	 * 重新申请或撤销
	 */
	@RequiresPermissions(value={"workbidingdocument:workBidingDocument:add","workbidingdocument:workBidingDocument:edit"},logical=Logical.OR)
	@RequestMapping(value = "reapplyORrepeal")
	//submit:重申保存数据，继续走流程；撤销不保存数据，结束流程
	public String reapplyORrepeal(@RequestParam(required=false) String submit,WorkBidingDocument workBidingDocument,Model model, RedirectAttributes redirectAttributes
					   ) throws Exception{
		if (!beanValidator(model, workBidingDocument)){
			return form(workBidingDocument,model,"","");
		}
		//重申保存数据，继续走流程；撤销不保存数据，结束流程
		//String submit = multiRequest.getParameter("submit");
		if(!workBidingDocument.getIsNewRecord()) {//编辑表单保存
			WorkBidingDocument t = workBidingDocumentService.get(workBidingDocument.getId());//从数据库取出记录的值

			//被驳回状态
			if (StringUtils.isNotBlank(t.getStatus()) &&t.getStatus().equals("4")){
				ProcessInstance processInstance = actTaskService.getProcIns(t.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);
					//重新申请保存修改的值，撤销不保存；
					if("reapply".equals(submit)){
						MyBeanUtils.copyBeanNotNull2Bean(workBidingDocument, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
						act.setFlag("yes");
					}//重新申请
					if("repeal".equals(submit)){act.setFlag("no");}//撤销
					t.setAct(act);
				}
			}
			workBidingDocumentService.reapplyORrepeal(t,submit);
		}
		if("reapply".equals(submit)){
			addMessage(redirectAttributes,"已提交重新申请");
		}else if("repeal".equals(submit)){
			addMessage(redirectAttributes,"已撤销");
		}
		return "redirect:"+Global.getAdminPath()+"/workbidingdocument/workBidingDocument/?repage";
	}
	/**
	 * 在标书完成后，部门负责人可以修改，此时只更新数据，不重启流程；
	 */
	@RequiresPermissions(value={"workbidingdocument:workBidingDocument:add","workbidingdocument:workBidingDocument:edit"},logical=Logical.OR)
	@RequestMapping(value = "updateData")
	public String updateData(WorkBidingDocument workBidingDocument,Model model, RedirectAttributes redirectAttributes ,
								  MultipartHttpServletRequest multiRequest) throws Exception{
		if (!beanValidator(model, workBidingDocument)){
			return form(workBidingDocument,model,"","");
		}
		if(!workBidingDocument.getIsNewRecord()) {//编辑表单保存
			WorkBidingDocument t = workBidingDocumentService.get(workBidingDocument.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workBidingDocument, t);//将编辑表单中的非NULL值覆盖数据库记录中的值

			workBidingDocumentService.updateData(t,multiRequest);
			addMessage(redirectAttributes,"保存成功");
		}


		return "redirect:"+Global.getAdminPath()+"/workbidingdocument/workBidingDocument/?repage";
	}
	@ResponseBody
	@RequestMapping("addMastersOrMembers")
	public Map<String,Object> masterAdd(WorkBidingDocument workBidingDocument,MultipartHttpServletRequest request,Model model){
		Map<String,Object> returnMap = new HashMap<>();
		String masterIds = request.getParameter("masterIds");
		String memberIds = request.getParameter("memberIds");
		returnMap = workBidingDocumentService.addMastersOrMembers(workBidingDocument,request,"1");
		return returnMap;

	}

	/**
	 * 流程追踪
	 */
	@RequestMapping("getProcess")
	public String getProcess(WorkBidingDocument workBidingDocument,Model model){

		model.addAttribute("processInstanceId",workBidingDocument.getProcessInstanceId());
		return "modules/workbidingdocument/workBidingDocumentTask";
	}
	/**
	 * 待办任务
	 * @param act
	 * @param model
	 * @return
	 */
	@RequestMapping("workBidingDocumentTodoList")
	public String workBidingDocumentTodoList(Act act , Model model ,RedirectAttributes redirectAttributes){
		act.setProcDefKey("workBidingDocument");
		List<Act> actList = new ArrayList<>();
		actList.addAll(actTaskService.todoList(act));
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();

		List<Activity> activities = activityService.groupByActivityMenu("215ad3f24b1345bc800fa76a57bb45a8",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			actList.addAll(actTaskService.todoList(act));
		}

		List<WorkBidingDocument> documentsList = new ArrayList<>();
		for(Act a : actList){
			//重新申请和撤销不在代办和历史任务列表展示
			if(! "reapply".equals(a.getTask().getTaskDefinitionKey())){
				WorkBidingDocument workBidingDocument = workBidingDocumentService.getByProcessInstanceId(a.getProcInsId());
				if(workBidingDocument != null && workBidingDocument.getCompanyId().equals(companyId)){
					if(a.getVars().getMap().get("applyUserId") != null){
						User user = UserUtils.get(a.getVars().getMap().get("applyUserId").toString());
						if(user != null){
							a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
						}
					}
					workBidingDocument.setAct(a);
					if(workBidingDocument.getWorkBidProject()!=null && workBidingDocument.getWorkBidProject().getId()!=null){
						WorkBidProject workBidProject = workBidProjectService.get(workBidingDocument.getWorkBidProject().getId());
						workBidingDocument.setWorkBidProject(workBidProject);
					}
					if(StringUtils.isNotBlank(workBidingDocument.getId())){
						workBidingDocument.setName(officeService.get(companyId).getName());
					}
					//默认流程中部门负责人audit1，总经理|董事长audit2，和自定义流程中的重新申请audit1冲突
					if(!"4".equals(workBidingDocument.getStatus())){
						documentsList.add(workBidingDocument);
					}
				}
			}
		}

		model.addAttribute("list", documentsList);
		return "modules/workbidingdocument/workBidingDocumentTodoList";
	}

	/**
	 * 已办任务
	 * @param act
	 * @param model
	 * @return
	 */
	@RequestMapping("workBidingDocumentHistoryList")
	public String workBidingDocumentHistoryList(Act act , Model model,HttpServletRequest request,HttpServletResponse response,RedirectAttributes redirectAttributes){
		act.setProcDefKey("workBidingDocument");
		List<Act> list = actTaskService.historicList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();

		List<Activity> activities = activityService.groupByActivityMenu("215ad3f24b1345bc800fa76a57bb45a8",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			list.addAll(actTaskService.historicList(act));
		}

		List<WorkBidingDocument> workBidingDocumentList = new ArrayList<WorkBidingDocument>();
		for (Act a : list) {
			//重新申请和撤销不展示在代办和历史任务列表里
			if(! "reapply".equals(a.getHistTask().getTaskDefinitionKey())){
				WorkBidingDocument workBidingDocument = workBidingDocumentService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
				if (workBidingDocument != null && workBidingDocument.getCompanyId().equals(companyId)) {
					if (a.getVars().getMap().get("applyUserId")!=null){
						if(UserUtils.get(a.getVars().getMap().get("applyUserId").toString()) !=null){
							a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
						}
					}
					workBidingDocument.setAct(a);
					if(workBidingDocument.getWorkBidProject()!=null && workBidingDocument.getWorkBidProject().getId()!=null){
						WorkBidProject workBidProject = workBidProjectService.get(workBidingDocument.getWorkBidProject().getId());
						workBidingDocument.setWorkBidProject(workBidProject);
					}
					if (StringUtils.isNotBlank(workBidingDocument.getId())){
						workBidingDocument.setName(officeService.get(companyId).getName());
					}
					workBidingDocumentList.add(workBidingDocument);
				}
			}
		}

		model.addAttribute("list", workBidingDocumentList);
		return "modules/workbidingdocument/workBidingDocumentHistoryList";


	}

	/**
	 * 打开审核列表
	 * @return
	 */
	@RequestMapping("applyOnWorkBidingDocument")
	public String applyOnWorkBidingDocument(Act act, HttpServletResponse response, Model model){
		// 获取流程XML上的表单KEY
		String formKey = "/workbidingdocument/workBidingDocument/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);
	}

	/**
	 *  部门负责人、总经理或董事长执行审核操作
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkBidingDocument workBidingDocument,Map<String, Object> vars, Model model, RedirectAttributes redirectAttributes) {
		/*if (StringUtils.isBlank(workBidingDocument.getAct().getComment())){
			addMessage(model, "请填写审核意见。");
			return form(workBidingDocument, model,"");
		}*/
		String message = workBidingDocumentService.auditSave(workBidingDocument);
		addMessage(redirectAttributes, message);
		return "redirect:"+Global.getAdminPath()+"/workbidingdocument/workBidingDocument/?repage";
	}


	/**
	 * 上传评价汇总表
	 * @param multiRequest
	 * @return
	 */
	@RequestMapping("/evaluateUpload")
	@ResponseBody
	public Map<String,String> evaluateUpload(MultipartHttpServletRequest multiRequest){
		String title = multiRequest.getParameter("title");
		String userId = multiRequest.getParameter("userId");

		String aliyunUrl = workBidingDocumentService.uploadEvaludate(multiRequest);

		Map<String,String> map = new HashMap<>();
		map.put("url",aliyunUrl);
		map.put("title",title);
		return map;
	}

    /**
     * 单个删除投标项目的负责人
     * @param
     */
	@RequestMapping("/updateMasterOfWorkBidProject")
    public String updateMasterOfWorkBidProject(WorkBidingDocument workBidingDocument,@RequestParam("masterId")String masterId,Model model){
		WorkBidProject workBidProject = workBidingDocument.getWorkBidProject();
	    workBidProject = workBidingDocumentService.deleteMasterOfWorkBidProject(workBidProject,masterId);
	    workBidingDocument.setWorkBidProject(workBidProject);
	    return form(workBidingDocument,model,"","");
    }

	/**
	 * 单个删除负责组成员
	 * @return
	 */
	@RequestMapping("/updateMemberOfWorkBidProject")
    public String updateMemberOfWorkBidProject(WorkBidingDocument workBidingDocument,@RequestParam("memberId")String memberId,Model model){
    	WorkBidProject workBidProject = workBidingDocument.getWorkBidProject();
    	workBidProject = workBidingDocumentService.deleteMemberOfWorkBidProject(workBidProject,memberId);
		workBidingDocument.setWorkBidProject(workBidProject);
		return form(workBidingDocument,model,"","");
	}

	/**
	 *  单个删除阿里云上的文件，同时更新相关对象的附件信息
	 *  阿里云文件地址http://gangwan-app.oss-cn-hangzhou.aliyuncs.com/attachment-file/workBidingDocument/3fcf03e37b3ba0fd5c7821998e392395.doc
	 *  其中阿里云删除接口所需的参数 key 指的是 attachment-file/workBidingDocument/3fcf03e37b3ba0fd5c7821998e392395.doc
	 * @return
	 */
	@RequestMapping("/deleteFileFromAliyun")
	public String deleteFileFromAliyun(@RequestParam("attachmentId") String attachmentId,WorkBidingDocument workBidingDocument,Model model){
    	Workattachment workattachment = workattachmentService.get(attachmentId);
    	if(workBidingDocument != null && workBidingDocument.getId() != null){
    		workBidingDocumentService.deleteFileFromAliyun(workattachment);
		}

    	return form(workBidingDocument,model,"","");
	}

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

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workbidingdocument:workBidingDocument: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<WorkBidingDocument> list = ei.getDataList(WorkBidingDocument.class);
			for (WorkBidingDocument workBidingDocument : list){
				try{
					workBidingDocumentService.save(workBidingDocument);
					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()+"/workbidingdocument/workBidingDocument/?repage";
    }
	
	/**
	 * 下载导入标书数据模板
	 */
	@RequiresPermissions("workbidingdocument:workBidingDocument:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "标书数据导入模板.xlsx";
    		List<WorkBidingDocument> list = Lists.newArrayList(); 
    		new ExportExcel("标书数据", WorkBidingDocument.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workbidingdocument/workBidingDocument/?repage";
    }
	
	
	/**
	 * 选择投标项目id
	 */
	@RequestMapping(value = "selectworkBidProject")
	public String selectworkBidProject(WorkBidProject workBidProject, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkBidProject> page = workBidingDocumentService.findPageByworkBidProject(new Page<WorkBidProject>(request, response),  workBidProject);
		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", workBidProject);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}
	

}