package com.qmth.qrzk.web.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.commons.io.FileUtils;
import org.krysalis.barcode4j.BarcodeGenerator;
import org.krysalis.barcode4j.BarcodeUtil;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.output.eps.EPSCanvasProvider;
import org.krysalis.barcode4j.output.svg.SVGCanvasProvider;
import org.krysalis.barcode4j.tools.MimeTypes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.qmth.qrzk.batch.model.BatchGJCourse;
import com.qmth.qrzk.batch.model.PaperStateView;
import com.qmth.qrzk.dao.repositories.BatchGJCourseRepo;
import com.qmth.qrzk.dao.repositories.PaperRepo;
import com.qmth.qrzk.dao.repositories.PaperStateViewRepo;
import com.qmth.qrzk.dao.repositories.SupplyCourseRepo;
import com.qmth.qrzk.dbf.ReadDBF;
import com.qmth.qrzk.dbf.WriteDBF;
import com.qmth.qrzk.paper.vo.Stock;
import com.qmth.qrzk.repository.common.base.BaseDao;
import com.qmth.qrzk.repository.common.enumeration.PaperStatusEnum;
import com.qmth.qrzk.repository.service.query.PaperBatchParams;
import com.qmth.qrzk.repository.service.query.PaperParams;
import com.qmth.qrzk.repository.service.query.QueryParams;
import com.qmth.qrzk.repository.user.model.CodeBook;
import com.qmth.qrzk.repository.user.model.Paper;
import com.qmth.qrzk.repository.user.model.PaperBatch;
import com.qmth.qrzk.repository.user.model.PaperPaperBatch;
import com.qmth.qrzk.repository.user.model.Suffix;
import com.qmth.qrzk.repository.user.service.ICodeBookService;
import com.qmth.qrzk.repository.user.service.IPaperBatchService;
import com.qmth.qrzk.repository.user.service.IPaperPaperBatchService;
import com.qmth.qrzk.repository.user.service.ISuffixService;
import com.qmth.qrzk.repository.user.service.impl.DbfPaperInfoServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.PaperServiceImpl;
import com.qmth.qrzk.repository.util.zip.ZipUtil;
import com.qmth.qrzk.repository.utils.CompressZIP;
import com.qmth.qrzk.repository.utils.Consts;
import com.qmth.qrzk.repository.utils.FileTool;
import com.qmth.qrzk.repository.utils.General;
import com.qmth.qrzk.repository.utils.ServerConfig;
import com.qmth.qrzk.supplypaper.model.SupplyCourse;
import com.qmth.qrzk.usedbatch.service.UsedBatchService;

@RestController
@RequestMapping("/examPaper")
public class ExamPaperController extends BaseAjaxController {

	private static final String BASE_JSP_PATH = "examPaper/";
	
	/** Parameter name for the message */
    public static final String BARCODE_MSG = "msg";
    /** Parameter name for the barcode type */
    public static final String BARCODE_TYPE = "type";
    /** Parameter name for the barcode height */
    public static final String BARCODE_HEIGHT  = "height";
    /** Parameter name for the module width */
    public static final String BARCODE_MODULE_WIDTH = "mw";
    /** Parameter name for the wide factor */
    public static final String BARCODE_WIDE_FACTOR = "wf";
    /** Parameter name for the quiet zone */
    public static final String BARCODE_QUIET_ZONE = "qz";
    /** Parameter name for the human-readable placement */
    public static final String BARCODE_HUMAN_READABLE_POS = "hrp";
    /** Parameter name for the output format */
    public static final String BARCODE_FORMAT = "fmt";
    /** Parameter name for the image resolution (for bitmaps) */
    public static final String BARCODE_IMAGE_RESOLUTION = "res";
    /** Parameter name for the grayscale or b/w image (for bitmaps) */
    public static final String BARCODE_IMAGE_GRAYSCALE = "gray";
    /** Parameter name for the font size of the human readable display */
    public static final String BARCODE_HUMAN_READABLE_SIZE = "hrsize";
    /** Parameter name for the font name of the human readable display */
    public static final String BARCODE_HUMAN_READABLE_FONT = "hrfont";
    /** Parameter name for the pattern to format the human readable message */
    public static final String BARCODE_HUMAN_READABLE_PATTERN = "hrpattern";

    private transient Logger log = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
	
    @Autowired
    private ISuffixService suffixService;

	@Autowired
	private PaperServiceImpl paperSerivce;

	@Autowired
	@Qualifier("paperBatchServiceImpl")
	private IPaperBatchService paperBatchService;
	
	@Autowired
	@Qualifier("codeBookServiceImpl")
	private ICodeBookService codeBookService;
	
	@Autowired
	@Qualifier("paperPaperBatchServiceImpl")
	private IPaperPaperBatchService paperPaperBatchService;

	@Autowired
	private DbfPaperInfoServiceImpl dbfPaperInfoSerivce;

	@Autowired private PaperStateViewRepo paperStateViewRepo;
	@Autowired private SupplyCourseRepo supplyCourseRepo;
	@Autowired private PaperRepo paperRepo;
	@Autowired private UsedBatchService usedBatchService;
	@Autowired private BatchGJCourseRepo gjRepo;
	@Autowired private BaseDao dao;
	
	@RequestMapping(value = "/backQYList/{id}")
	public ModelAndView backQYList(@PathVariable int id) {
		PaperBatch pb = paperBatchService.findTypeById(id);
		return new ModelAndView("redirect:/examPaper/batchPapers/"+ pb.getCode());
	}

	@RequestMapping(value = "/batch")
	public ModelAndView batch(HttpServletRequest request, HttpSession session) {
		return new ModelAndView(BASE_JSP_PATH + "batch");
	}

	@RequestMapping(value = "/batchPapers/{batchId}")
	public ModelAndView batchPapers(HttpServletRequest request,
			HttpSession session, @PathVariable String batchId) {
		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH
				+ "batchPapers");
		// TODO 需要根据batchId获取batch对象
		//这里有一个bug batchId为string
		PaperBatch pb = paperBatchService.findById(Integer.parseInt(batchId));
		if ("启用".equalsIgnoreCase(pb.getType())) {
			List<Integer> relatedPaperNums = dbfPaperInfoSerivce
					.queryRelatedPaperNumsByBatchId(pb.getId());
			modelAndView.addObject("relatedPaperNums", relatedPaperNums);
		}
		modelAndView.addObject("paperBatch", pb);
		return modelAndView;
	}

	@RequestMapping(value = "/batchPapers/addPapers/{batchId}")
	public ModelAndView addDraftPapers(HttpServletRequest request,
			HttpSession session, @PathVariable int batchId) {
		PaperBatch paperBatch = paperBatchService.findTypeById(batchId);

		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH+ "listPapersAddToBatch");
		modelAndView.addObject("paperBatch", paperBatch);
		return modelAndView;
	}

	@RequestMapping(value = "/batchPapers/addFormalPapers/{batchId}")
	public ModelAndView addFormalPapers(HttpServletRequest request,
			HttpSession session, @PathVariable int batchId) {
		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH
				+ "listFormalPapers");
		modelAndView.addObject("batchType", batchId);
		return modelAndView;
	}

	@RequestMapping("/queryBatch")
	@ResponseBody
	public Map<String, Object> queryBatch(PaperBatchParams params) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (params.getType() != null) {
			if (params.getType().equals("all")) {
				params.setType("");
			}
		}

		List<PaperBatch> ls = paperBatchService.queryBatch(params);
		int total = paperBatchService.getCount(params);
		result.put("rows", ls);
		result.put("total", total);
		return result;
	}

	@RequestMapping("/printCode/{msg}")
	public void printCode(HttpServletRequest request,HttpServletResponse response,@PathVariable String msg){
		try {
            String format = determineFormat(request);
            int orientation = 0;
            Configuration cfg = buildCfg(request);


            BarcodeUtil util = BarcodeUtil.getInstance();
            BarcodeGenerator gen = util.createBarcodeGenerator(cfg);

            ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
            try {
                if (format.equals(MimeTypes.MIME_SVG)) {
                    //Create Barcode and render it to SVG
                    SVGCanvasProvider svg = new SVGCanvasProvider(false, orientation);
                    gen.generateBarcode(svg, msg);
                    org.w3c.dom.DocumentFragment frag = svg.getDOMFragment();

                    //Serialize SVG barcode
                    TransformerFactory factory = TransformerFactory.newInstance();
                    Transformer trans = factory.newTransformer();
                    Source src = new javax.xml.transform.dom.DOMSource(frag);
                    Result res = new javax.xml.transform.stream.StreamResult(bout);
                    trans.transform(src, res);
                } else if (format.equals(MimeTypes.MIME_EPS)) {
                    EPSCanvasProvider eps = new EPSCanvasProvider(bout, orientation);
                    gen.generateBarcode(eps, msg);
                    eps.finish();
                } else {
                    String resText = request.getParameter(BARCODE_IMAGE_RESOLUTION);
                    int resolution = 300; //dpi
                    if (resText != null) {
                        resolution = Integer.parseInt(resText);
                    }
                    if (resolution > 2400) {
                        throw new IllegalArgumentException(
                            "Resolutions above 2400dpi are not allowed");
                    }
                    if (resolution < 10) {
                        throw new IllegalArgumentException(
                            "Minimum resolution must be 10dpi");
                    }
                    String gray = request.getParameter(BARCODE_IMAGE_GRAYSCALE);
                    BitmapCanvasProvider bitmap = ("true".equalsIgnoreCase(gray)? 
                    		new BitmapCanvasProvider(bout, format, resolution,BufferedImage.TYPE_BYTE_GRAY, true, orientation):
                    			new BitmapCanvasProvider(bout, format, resolution,BufferedImage.TYPE_BYTE_BINARY, false, orientation));
                    String[] arr=msg.split("=");
                    msg=arr[1];
                    
//                    String courseName=arr[2];
//                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//                    StringBuilder sb=new StringBuilder();
//                    sb.append(msg).append("\n").append(courseName);
//                    sb.append("\n").append(sdf.format(new Date()));
//                    System.out.println(sb.toString());
                    gen.generateBarcode(bitmap, msg);
                    bitmap.finish();
                }
            } finally {
                bout.close();
            }
            response.setContentType(format);
            response.setContentLength(bout.size());
            response.getOutputStream().write(bout.toByteArray());
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("Error while generating barcode", e);
        } 
	}
	
	/**
     * Check the request for the desired output format.
     * @param request the request to use
     * @return MIME type of the desired output format.
     */
    protected String determineFormat(HttpServletRequest request) {
    	String format = request.getParameter(BARCODE_FORMAT);
        
        format = MimeTypes.expandFormat(format);
        //change_image_type
       
        if (format == null) format = MimeTypes.MIME_JPEG;
        return format;
    }

    /**
     * Build an Avalon Configuration object from the request.
     * @param request the request to use
     * @return the newly built COnfiguration object
     * @todo Change to bean API
     */
    protected Configuration buildCfg(HttpServletRequest request) {
    	DefaultConfiguration cfg = new DefaultConfiguration("barcode");
        //Get type
        String type = "code128";
        DefaultConfiguration child = new DefaultConfiguration(type);
        cfg.addChild(child);
        
        
        //以下方便并未执行
        //Get additional attributes
        DefaultConfiguration attr;
        String height = request.getParameter(BARCODE_HEIGHT);
        if (height != null) {
            attr = new DefaultConfiguration("height");
            attr.setValue(height);
            child.addChild(attr);
        }
        String moduleWidth = request.getParameter(BARCODE_MODULE_WIDTH);
        if (moduleWidth != null) {
            attr = new DefaultConfiguration("module-width");
            attr.setValue(moduleWidth);
            child.addChild(attr);
        }
        String wideFactor = request.getParameter(BARCODE_WIDE_FACTOR);
        if (wideFactor != null) {
            attr = new DefaultConfiguration("wide-factor");
            attr.setValue(wideFactor);
            child.addChild(attr);
        }
        String quietZone = request.getParameter(BARCODE_QUIET_ZONE);
        if (quietZone != null) {
            attr = new DefaultConfiguration("quiet-zone");
            if (quietZone.startsWith("disable")) {
                attr.setAttribute("enabled", "false");
            } else {
                attr.setValue(quietZone);
            }
            child.addChild(attr);
        }

        // creating human readable configuration according to the new Barcode Element Mappings
        // where the human-readable has children for font name, font size, placement and
        // custom pattern.
        String humanReadablePosition = request.getParameter(BARCODE_HUMAN_READABLE_POS);
        String pattern = request.getParameter(BARCODE_HUMAN_READABLE_PATTERN);
        String humanReadableSize = request.getParameter(BARCODE_HUMAN_READABLE_SIZE);
        String humanReadableFont = request.getParameter(BARCODE_HUMAN_READABLE_FONT);
        if (!((humanReadablePosition == null)&& (pattern == null)&& (humanReadableSize == null)&& (humanReadableFont == null))) {
            attr = new DefaultConfiguration("human-readable");

            DefaultConfiguration subAttr;
            if (pattern != null) {
                subAttr = new DefaultConfiguration("pattern");
                subAttr.setValue(pattern);
                attr.addChild(subAttr);
            }
            if (humanReadableSize != null) {
                subAttr = new DefaultConfiguration("font-size");
                subAttr.setValue(humanReadableSize);
                attr.addChild(subAttr);
            }
            if (humanReadableFont != null) {
                subAttr = new DefaultConfiguration("font-name");
                subAttr.setValue(humanReadableFont);
                attr.addChild(subAttr);
            }
            if (humanReadablePosition != null) {
              subAttr = new DefaultConfiguration("placement");
              subAttr.setValue(humanReadablePosition);
              attr.addChild(subAttr);
            }

            child.addChild(attr);
        }

        return cfg;
    }
    
	@RequestMapping("/queryDraftPaperForReview")
	@ResponseBody
	public Map<String, Object> queryDraftPaperForReview(@RequestBody PaperParams paperParams) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("rows", paperSerivce.queryDraftPaperForReview(paperParams));
		result.put("total", paperParams.getTotalNum());
		return result;
	}
	
	@RequestMapping("/queryFormalPaperForUse")
	@ResponseBody
	public Map<String, Object> queryFormalPaperForUse(@RequestBody PaperParams paperParams) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("rows", paperSerivce.queryFormalPaperForUse(paperParams));
		result.put("total", paperParams.getTotalNum());
		return result;
	}
	
	@RequestMapping("/getBatchPapers/{id}")
	@ResponseBody
	public Map<String, Object> getBatchPapers(@PathVariable int id) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<Paper> list = paperSerivce.queryByBatchId(id);
		result.put("rows", list);
		return result;
	}
	
	@RequestMapping("/queryBatchPapers")
	@ResponseBody
	public Map<String, Object> queryBatchPapers(@RequestBody PaperParams pp) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<Paper> list = paperSerivce.queryBatchPapers(pp);
		result.put("rows", list);
		result.put("total", pp.getTotalNum());
		return result;
	}
	
	@RequestMapping("/getTotalCount")
	public void getTotalCount(HttpServletResponse response,@RequestBody PaperParams pp){
		JSONObject object = new JSONObject();
		//根据批次id 查询该批次id下的所有试卷、然后统计相应的已上传的试卷、已上传的答案、已上传的专卡
		pp.setRukuType(1);
		int paperCount=paperSerivce.getTotalCountByBatchId(pp);
		pp.setRukuType(2);
		int standardAnswerPathCount=paperSerivce.getTotalCountByBatchId(pp);
		pp.setRukuType(3);
		int answerSheetPathCount=paperSerivce.getTotalCountByBatchId(pp);
		pp.setRukuType(4);
		int separatePaperPath=paperSerivce.getTotalCountByBatchId(pp);
		pp.setRukuType(5);
		int wPaperPath=paperSerivce.getTotalCountByBatchId(pp);
		
		pp.setIsOutBoundScanned(1);
		int isOutBoundScannedCount=paperPaperBatchService.getCountIsOutBoundScanned(pp);
		pp.setIsStorageScanned(1);
		int isStorageScannedCount=paperPaperBatchService.getCountIsStorageScanned(pp);
		
		object.put("isOutBoundScannedCount", isOutBoundScannedCount);
		object.put("isStorageScannedCount", isStorageScannedCount);
		object.put("paperCount", paperCount);
		object.put("standardAnswerPathCount", standardAnswerPathCount);
		object.put("answerSheetPathCount", answerSheetPathCount);
		object.put("separatePaperPath", separatePaperPath);
		object.put("wPaperPath", wPaperPath);
		this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/getTotalPaper")
	public void getTotalPaper(HttpServletResponse response,@RequestBody PaperParams pp){
		JSONObject object = new JSONObject();
		//根据批次id 查询该批次id下的所有试卷、然后统计相应的已上传的试卷、已上传的答案、已上传的专卡
		pp.setStatus(PaperStatusEnum.PAPER_DRAFT.getKey());;
		int DRAFT=paperSerivce.getTotalPaper(pp);
		pp.setStatus(PaperStatusEnum.PAPER_FORMAL.getKey());;
		int FORMAL=paperSerivce.getTotalPaper(pp);
		pp.setStatus(PaperStatusEnum.PAPER_USED.getKey());;
		int USED=paperSerivce.getTotalPaper(pp);
		pp.setRukuType(1);
		int paperPath=paperSerivce.getTotalPathPaper(pp);
		pp.setRukuType(2);
		int answerPath=paperSerivce.getTotalPathPaper(pp);
		pp.setRukuType(3);
		int answerSheetPath=paperSerivce.getTotalPathPaper(pp);
		pp.setRukuType(4);
		int separatePaperPath=paperSerivce.getTotalPathPaper(pp);
		pp.setRukuType(5);
		int wPaperPath=paperSerivce.getTotalPathPaper(pp);
		
		object.put("DRAFT", DRAFT);
		object.put("FORMAL", FORMAL);
		object.put("USED", USED);
		object.put("paperPath", paperPath);
		object.put("answerPath", answerPath);
		object.put("answerSheetPath", answerSheetPath);
		object.put("separatePaperPath", separatePaperPath);
		object.put("wPaperPath", wPaperPath);
		this.outJsonString(response, object.toString());
	}

	@RequestMapping("/saveBatch")
	public void saveBatch(HttpServletRequest request,HttpServletResponse response, @RequestBody PaperBatch pb) {
		int flag = paperBatchService.isSameCode(pb.getCode());
		JSONObject object = new JSONObject();
		if (flag == 0) {
			paperBatchService.insertBatch(pb);
			object.put("result", "success");
			this.outJsonString(response, object.toString());
		} else {
			object.put("result", "fail");
			this.outJsonString(response, object.toString());
		}
	}
	
	@RequestMapping("/validataCode")
	public void validataCode(HttpServletResponse response, @RequestBody Paper paper) {
		List<String> ls=paperSerivce.getAllCode();
		boolean flag=ls.contains(paper.getCode());
		JSONObject object = new JSONObject();
		if (flag) {
			object.put("result", "fail");
			this.outJsonString(response, object.toString());
		} else {
			object.put("result", "success");
			this.outJsonString(response, object.toString());
		}
	}
	
	@RequestMapping("/updatePaper")
	public void updatePaper(HttpServletRequest request,HttpServletResponse response, @RequestBody Paper paper) {
		int flag = paperSerivce.updateInfoPaper(paper);
		JSONObject object = new JSONObject();
		if (flag > 0) {
			object.put("result", "success");
			this.outJsonString(response, object.toString());
		} else {
			object.put("result", "fail");
			this.outJsonString(response, object.toString());
		}
	}
	/**
	 * 上传DBF文件
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/DBFUpload/{id}")
	public void uploadDBFFile(HttpServletRequest request,HttpServletResponse response, @PathVariable int id) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
		InputStream stream = null;
		List<String> existPaperCodes = new ArrayList<String>();
		JSONObject object=new JSONObject();
		try {
			stream = file.getInputStream();
			String fileName = file.getOriginalFilename();
			// 调用解析DBF格式文件
			List<Paper> ls = null;
			if(fileName.toLowerCase().endsWith(".dbf")){
				ls = ReadDBF.readDBFFile(stream);
			}else if(fileName.toLowerCase().endsWith(".xls")){
				ls = ReadDBF.readXlsFile(stream);
			}else{
				throw new RuntimeException("不可解析的文件：" + fileName + "，只支持.dbf和.xls文件.");
			}
			if (ls != null) {
				List<String> list = paperSerivce.getAllCode();
				for (Paper p : ls) {
					if (list.contains(p.getCode())) {
						existPaperCodes.add(p.getCode());
					} else {
						paperSerivce.insertPaper(p);
						PaperPaperBatch ppb = new PaperPaperBatch(id,
								p.getId(), 0, 0, 0, 0, 0, p.getBookId(),
								p.getBookName(), p.getBookAuthor(),
								p.getBookPress(), p.getBookPressYear(),
								p.getSchool(), p.getRemark());
						paperPaperBatchService.insertPaperPaperBatch(ppb);
					}
				}
				
				PaperBatch pb=new PaperBatch();
				pb.setUpdatedTime(new Date());
				pb.setId(id);
				int rs=updateUpdateTime(pb);
				if(rs>0){
					object.put("result", true);
					if(ls.size() - existPaperCodes.size() > 0){
						object.put("successMsg", "导入成功：" + (ls.size()-existPaperCodes.size()) + "条试卷记录");
					}
					if (existPaperCodes.size() > 0) {
						object.put("errorMsg", "导入失败：" + existPaperCodes.size() + "条试卷记录，失败原因：试卷编号在系统中已存在。");
						object.put("existPaperCodes", existPaperCodes);
					}
				}else{
					object.put("result", false);
				}
			} else {
				object.put("result", false);
			}
			this.outJsonString(response, object.toString());
			
		} catch(Exception e){
			log.error(e.getMessage(), e);
			object.put("result", false);
			object.put("errorMsg", e.getMessage());
			this.outJsonString(response, object.toString());
		} finally {
			General.close(stream);
		}
	}

	/**
	 * 导入试卷 2014年8月26日
	 * 
	 * @author 钟辉
	 * @description
	 * @param request
	 * @param response
	 */
	@RequestMapping("/paperUpload/{id}")
	public void uploadPaperFFile(HttpServletRequest request,HttpServletResponse response, @PathVariable int id) {

		// 将导入的zip包进行处理
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
		// 服务器相对路径
		String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
		if(!realPath.endsWith("/") && !realPath.endsWith("\\")){
			realPath = realPath + "/";
		}
		
		//删除存放临时目录的文件夹
		String delPath=realPath+"temporary/";
		FileTool.delFolder(delPath);
		
		JSONObject object = new JSONObject();
		// 上传文件名
		String fileName = file.getOriginalFilename();

		String path = realPath + "zip";
		// 复制到指定的位置
		FileTool.writeFile(file, path, fileName);

		// 解压.zip文件
		CompressZIP.unZipFiles(path + "/" + fileName, path + "/");

		File rootFile = new File(path);
		List<String> files = new ArrayList<String>(); // 文件夹目录下是所有文件的路径
		FileTool.deletefile(path + "/" + fileName);  //删除.zip文件
		// 导入试卷的时候需要解决一个问题:例如导入dbf的时候包含10条记录的试卷、导入的.zip包却包含100套试卷
		// 需要过滤出其中的10套试卷到指定目录

		FileTool.showAllFiles(files, rootFile); // D:\test\zip\00032140901A\00032140901A.doc
												// --->filesModel
		PaperParams paperparams = new PaperParams();
		paperparams.setBatchId(id);
		int count = paperSerivce.getMPListCount(paperparams);
		paperparams.setRows(count);
		List<Paper> list = paperSerivce.getMPList(paperparams); // 查询出该批次下的试卷集合

		List<String> ls = new ArrayList<String>();
		for (Paper p : list) {
			ls.add(p.getCode());
		}
		
		List<Suffix> suffixs=suffixService.getAllSuffix();
		List<String> suffixName=new ArrayList<String>();
		for(Suffix s :suffixs){
			suffixName.add(s.getSuffix());
		}
		
		boolean flag=true;
		int successZyCount=0;
		int failZyCount=0;
		int successAnswerCount=0;
		int failAnswerCount=0;
		int successAnswerCardCount=0;
		int failAnswerCardCount=0;
		int successSeparatePaperCount = 0;
		int failSeparatePaperCount = 0;
		int successWPaperCount = 0;
		int failWPaperCount = 0;
		
		for (String ff : files) {
			String[] ss = ff.split("\\\\");
			String oldFolder="";
			String copyFolderName="";
			String fileNameAndSuffix = ss[ss.length - 1];
			String[] name = fileNameAndSuffix.split("\\.");
			String code = name[0];
			
			if(!suffixName.contains(name[1])){
				continue;
			}
			
			for(int i=0;i<ss.length-1;i++){
				if(i+1==ss.length-1){
					copyFolderName=ss[i];
				}
				
				if(i!=0){
					oldFolder=oldFolder+"/"+ss[i];
				}else{
					oldFolder+=ss[i];
				}
			}
			
			//判断文件是否为标答
			boolean isStandardAnswer = false;
			if (code.length() == 15 && code.endsWith("N")) {
				isStandardAnswer = true;
				code = code.substring(0, code.length() - 1);
			}
			
			//判断文件是否为分卷
			boolean isSeparatePaper = false;
			if(code.length() == 15 && code.endsWith("F")){
				isSeparatePaper = true;
				code = code.substring(0, code.length() - 1);
			}
			
			//判断文件是否为网评卷
			boolean isWPaper = false;
			if(code.length() == 15 && code.endsWith("W")){
				isWPaper = true;
				code = code.substring(0, code.length() - 1);
			}
			
			//判断文件是否为转印说明
			boolean isZhuanyin = false;
			if(code.length() == 16 && code.endsWith("ZY")){
				isZhuanyin = true;
				code = code.substring(0, code.length() - 2);
			}

			//判断试卷代码是否在批次下存在
			if (ls.contains(code)) {
				// 移动试卷到指定位置
				Paper paper = paperSerivce.getPaperByCodeBatchId(code, id);
				if (null == paper) {
					continue;
				} else {
					String folderName = "";
					if ("DRAFT".equalsIgnoreCase(paper.getStatus())) {
						folderName = "maopi";
					} else if ("FORMAL".equalsIgnoreCase(paper.getStatus())) {
						folderName = "qingyang";
					} else if ("USED".equalsIgnoreCase(paper.getStatus())) {
						folderName = "qiyong";
					}

					PaperParams pp = new PaperParams();
					String newPath = realPath + "paper/" + folderName;
					if (isStandardAnswer) {
						newPath += "/answer/";
						pp.setStandardAnswerPath(newPath + fileNameAndSuffix);
						
						successAnswerCount++;
					} else {
						newPath += "/" + code + "/";
						if (name[1].equals("cdr")) {
							pp.setIsSpecialAnswerSheet(1);
							pp.setAnswerSheetPath(newPath + fileNameAndSuffix);
							successAnswerCardCount++;
						} else if(isSeparatePaper){
							pp.setSeparatePaperPath(newPath + fileNameAndSuffix);
							successSeparatePaperCount++;
						} else if(isZhuanyin) {
							pp.setZyPath(newPath + fileNameAndSuffix);
							successZyCount++;
						} else if(isWPaper) {
							pp.setwPaperPath(newPath + fileNameAndSuffix);
							successWPaperCount++;
						} else{
							continue;
						}
					}
					FileTool.copyFile(ff, newPath, fileNameAndSuffix);
					pp.setCode(code);
					paperSerivce.updatePaper(pp);
				}
			}else{
				//将试卷移动到指定位置
				String temporaryPath = realPath + "temporary/" ;		//这是一个临时目录
				if (isStandardAnswer) {
					temporaryPath += "answer/";
					failAnswerCount++;
				} else {
					temporaryPath+=copyFolderName+"/";
					if (name[1].equals("cdr")) {
						failAnswerCardCount++;
					} else if(isSeparatePaper){
						failSeparatePaperCount++;
					} else if(isZhuanyin) {
						failZyCount++;
					} else {
						failWPaperCount++;
					}
				}
//				FileTool.copyFolder(oldFolder, temporaryPath);
				FileTool.copyFile(ff, temporaryPath, fileNameAndSuffix);
				flag=false;
			}
		}
		FileTool.delAllFile(path + "/");
		if(flag){
			PaperBatch pb=new PaperBatch();
			pb.setUpdatedTime(new Date());
			pb.setId(id);
			int rs=updateUpdateTime(pb);
			if(rs>0){
				object.put("result", true);
			}else{
				object.put("result", false);
				object.put("msg", "更新批次信息失败！");
			}
		}else{
			object.put("result", false);
			object.put("msg", "导入的部分文档在当前批次不存在！");
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("allCount", list.size());
		map.put("successZyCount", successZyCount);
		map.put("failZyCount", failZyCount);
		map.put("folderName", realPath + "temporary/");
		map.put("successAnswerCount", successAnswerCount);
		map.put("failAnswerCount", failAnswerCount);
		map.put("successAnswerCardCount", successAnswerCardCount);
		map.put("failAnswerCardCount", failAnswerCardCount);
		map.put("successSeparatePaperCount", successSeparatePaperCount);
		map.put("failSeparatePaperCount", failSeparatePaperCount);
		map.put("successWPaperCount", successWPaperCount);
		map.put("failWPaperCount", failWPaperCount);
		
		object.put("data", map);
		object.put("type", "paper");
		this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/paperReviewedUpload/{batchId}")
	public void uploadReviewedPaperFiles(HttpServletRequest request,HttpServletResponse response, @PathVariable int batchId) {
		
		// 将导入的zip包进行处理
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
		// 服务器相对路径
		String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
		if(!realPath.endsWith("/") && !realPath.endsWith("\\")){
			realPath = realPath + "/";
		}
		
		//删除存放临时目录的文件夹
		String delPath=realPath+"temporary/";
		FileTool.delFolder(delPath);
		
		JSONObject object = new JSONObject();
		// 上传文件名
		String fileName = file.getOriginalFilename();
		
		String path = realPath + "zip";
		// 复制到指定的位置
		FileTool.writeFile(file, path, fileName);
		
		// 解压.zip文件
		CompressZIP.unZipFiles(path + "/" + fileName, path + "/");
		
		File rootFile = new File(path);
		List<String> files = new ArrayList<String>(); // 文件夹目录下是所有文件的路径
		FileTool.deletefile(path + "/" + fileName);  //删除.zip文件
		// 导入试卷的时候需要解决一个问题:例如导入dbf的时候包含10条记录的试卷、导入的.zip包却包含100套试卷
		// 需要过滤出其中的10套试卷到指定目录
		
		FileTool.showAllFiles(files, rootFile); // D:\test\zip\00032140901A\00032140901A.doc
		// --->filesModel
		
		PaperBatch pb = paperBatchService.findById(batchId);
		
		List<Paper> batchPapers = paperSerivce.queryByBatchId(batchId);
		
		Map<String, Paper> codePaperMap = new HashMap<String, Paper>();
		for (Paper p : batchPapers) {
			codePaperMap.put(p.getCode(), p);
		}
		
		//获取上传文件过滤后缀名
		List<Suffix> suffixs=suffixService.getAllSuffix();
		List<String> suffixName=new ArrayList<String>();
		for(Suffix s :suffixs){
			suffixName.add(s.getSuffix());
		}
		
		boolean flag=true;
		int successZyCount=0;
		int failZyCount=0;
		int successAnswerCount=0;
		int failAnswerCount=0;
		int successAnswerCardCount=0;
		int failAnswerCardCount=0;
		int successSeparatePaperCount = 0;
		int failSeparatePaperCount = 0;
		int successWPaperCount = 0;
		int failWPaperCount = 0;
		
		for (String ff : files) {
			String[] ss = ff.split("\\\\");
			String oldFolder="";
			String copyFolderName="";
			String fileNameAndSuffix = ss[ss.length - 1];
			String[] name = fileNameAndSuffix.split("\\.");
			String code = name[0];
			
			if(!suffixName.contains(name[1])){
				continue;
			}
			
			for(int i=0;i<ss.length-1;i++){
				if(i+1==ss.length-1){
					copyFolderName=ss[i];
				}
				
				if(i!=0){
					oldFolder=oldFolder+"/"+ss[i];
				}else{
					oldFolder+=ss[i];
				}
			}
			
			//判断文件是否为标答
			boolean isStandardAnswer = false;
			if (code.length() == 15 && code.endsWith("N")) {
				isStandardAnswer = true;
				code = code.substring(0, code.length() - 1);
			}
			
			//判断文件是否为分卷
			boolean isSeparatePaper = false;
			if(code.length() == 15 && code.endsWith("F")){
				isSeparatePaper = true;
				code = code.substring(0, code.length() - 1);
			}
			
			//判断文件是否为网评卷
			boolean isWPaper = false;
			if(code.length() == 15 && code.endsWith("W")){
				isWPaper = true;
				code = code.substring(0, code.length() - 1);
			}
			
			//判断文件是否为网评卷
			boolean isHPaper = false;
			if(code.length() == 14){
				isHPaper = true;
			}
			
			//判断文件是否为转印说明
			boolean isZhuanyin = false;
			if(code.length() == 16 && code.endsWith("ZY")){
				isZhuanyin = true;
				code = code.substring(0, code.length() - 2);
			}
			
			//判断试卷代码是否在批次下存在
			if (codePaperMap.keySet().contains(code)) {
				// 移动试卷到指定位置
				Paper paper = codePaperMap.get(code);
				String folderName = "";
				if ("DRAFT".equalsIgnoreCase(paper.getStatus())) {
					folderName = "maopi";
				} else if ("FORMAL".equalsIgnoreCase(paper.getStatus())) {
					folderName = "qingyang";
				} else if ("USED".equalsIgnoreCase(paper.getStatus())) {
					folderName = "qiyong";
				}
				
				PaperPaperBatch ppb = new PaperPaperBatch();
				String newPath = realPath + "paper/" + folderName;
				if (isStandardAnswer) {
					newPath += "/answer/";
					ppb.setIsStandadAnswerReturn(1);
					paper.setStandardAnswerPath(newPath + fileNameAndSuffix);
					successAnswerCount++;
				} else {
					newPath += "/" + code + "/";
					if (name[1].equals("cdr")) {
						ppb.setIsAnswerSheetReturn(1);
						paper.setAnswerSheetPath(newPath + fileNameAndSuffix);
						successAnswerCardCount++;
					} else if(isSeparatePaper){
						ppb.setIsSeparatePaperReturn(1);
						paper.setSeparatePaperPath(newPath + fileNameAndSuffix);
						successSeparatePaperCount++;
					} else if(isZhuanyin) {
						ppb.setIsZyReturn(1);
						paper.setZyPath(newPath + fileNameAndSuffix);
						successZyCount++;
					} else if(isWPaper)  {
						ppb.setIsWPaperReturn(1);
						paper.setwPaperPath(newPath + fileNameAndSuffix);
						successWPaperCount++;
					} else if(isHPaper)  {
						ppb.setIsPaperReturn(1);
						paper.setPaperPath(newPath + fileNameAndSuffix);
					}else{
						continue;
					}
				}
				FileTool.copyFile(ff, newPath, fileNameAndSuffix);
				ppb.setPaperId(paper.getId());;
				ppb.setBatchId(pb.getId());
				paperPaperBatchService.updatePaperPaperBatch(ppb);
				paperSerivce.updateStatusPath(paper);
			}else{
				//将试卷移动到指定位置
				String temporaryPath = realPath + "/temporary/" ;		//这是一个临时目录
				if (isStandardAnswer) {
					temporaryPath += "/answer/";
					failAnswerCount++;
				} else {
					temporaryPath+=copyFolderName+"/";
					if (name[1].equals("cdr")) {
						failAnswerCardCount++;
					} else if(isSeparatePaper){
						failSeparatePaperCount++;
					} else if(isZhuanyin) {
						failZyCount++;
					} else {
						failWPaperCount++;
					}
				}
//				FileTool.copyFolder(oldFolder, temporaryPath);
				FileTool.copyFile(ff, temporaryPath, fileNameAndSuffix);
				flag=false;
			}
		}
		FileTool.delAllFile(path + "/");
		if(flag){
			pb.setUpdatedTime(new Date());
			int rs=updateUpdateTime(pb);
			if(rs>0){
				object.put("result", true);
			}else{
				object.put("result", false);
				object.put("msg", "更新批次信息失败！");
			}
		}else{
			object.put("result", false);
			object.put("msg", "导入的部分文档在当前批次不存在！");
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("allCount", batchPapers.size());
		map.put("successZyCount", successZyCount);
		map.put("failZyCount", failZyCount);
		map.put("folderName", realPath + "temporary/");
		map.put("successAnswerCount", successAnswerCount);
		map.put("failAnswerCount", failAnswerCount);
		map.put("successAnswerCardCount", successAnswerCardCount);
		map.put("failAnswerCardCount", failAnswerCardCount);
		map.put("successSeparatePaperCount", successSeparatePaperCount);
		map.put("failSeparatePaperCount", failSeparatePaperCount);
		map.put("successWPaperCount", successWPaperCount);
		map.put("failWPaperCount", failWPaperCount);
		
		object.put("data", map);
		object.put("type", "paper");
		this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/checkOver")
	public void checkOverPaper(HttpServletResponse response,@RequestBody PaperParams pp){
		JSONObject object = new JSONObject();
		try{
			if(pp.getBatchId()==-1){	//试卷检索操作的结束检查
				//1.先查出不符合条件的所有试卷  电子试卷 、题卡没上传且是专卡的专卡没上传
				List<Paper> papers=paperSerivce.getCheckOverPaper();
				//2.删除相对应的批次关系
				String[] arr=new String[papers.size()];
				for(int i=0;i<papers.size();i++){
					arr[i]=String.valueOf(papers.get(i).getId());
				}
				pp.setArray(arr);
				paperPaperBatchService.removePaperFromBatch(pp);
				for(Paper p:papers){
					if(p.getStandardAnswerPath()!=null){
						FileTool.deletefile(p.getStandardAnswerPath());	//删除标答
					}
					if(p.getPaperPath()!=null){
						//获取paper_path文件夹路径  数据库数据为:D:/qrzk_papers//paper/maopi/00032141001A/00032141001A.doc 需要得到D:/qrzk_papers//paper/maopi/00032141001A/文件夹路径
						String paperPath=p.getPaperPath();
						String[] arr1=paperPath.split("/");
						StringBuffer sb=new StringBuffer();
						for(int i=0;i<arr1.length-1;i++){
							sb.append(arr1[i]).append("/");
						}
						
						FileTool.delFolder(sb.toString());//删除试卷
					}
				}
				paperSerivce.deletePaper(pp);						//移除qr_paper表记录
				object.put("type", "success");
			}else{	//入库批次的结束检查
				//1.查询所有未入库扫描的试卷
				List<PaperStateView> notScannedPapers = paperStateViewRepo.findByBatchIdAndIsStorageScanned(pp.getBatchId(), false);
				int usedBySupplyBatchPaperCount = 0;
				int usedByOtherBatchPaper = 0;
				if(notScannedPapers.size() > 0){
					for(PaperStateView psw : notScannedPapers){
						com.qmth.qrzk.paper.model.Paper p = psw.getPaper();
						
						//判断试卷是否被供卷批次启用
						List<SupplyCourse> supplyCourses = supplyCourseRepo.findByPaperId(p.getId());
						if(supplyCourses.size() > 0){
							usedBySupplyBatchPaperCount++;
							continue;
						}
						
						List<PaperStateView> allPaperRelates = paperStateViewRepo.findByPaperId(p.getId());
						if(allPaperRelates.size() > 1){
							usedByOtherBatchPaper++;
							continue;
						}
						
						if(p.getStandardAnswerPath()!=null){
							FileTool.deletefile(p.getStandardAnswerPath());	//删除标答
						}
						if(p.getPaperPath()!=null){
							//获取paper_path文件夹路径  数据库数据为:D:/qrzk_papers//paper/maopi/00032141001A/00032141001A.doc 需要得到D:/qrzk_papers//paper/maopi/00032141001A/文件夹路径
							String paperPath=p.getPaperPath();
							String[] arr1=paperPath.split("/");
							StringBuffer sb=new StringBuffer();
							for(int i=0;i<arr1.length-1;i++){
								sb.append(arr1[i]).append("/");
							}
							
							FileTool.delFolder(sb.toString());//删除试卷
						}
						paperStateViewRepo.delete(psw);
						paperRepo.delete(p);
					}

					PaperBatch pb=new PaperBatch();
					pb.setUpdatedTime(new Date());
					pb.setId(pp.getBatchId());
					updateUpdateTime(pb);					
				}
				
				object.put("result", true);
				if(usedBySupplyBatchPaperCount > 0 || usedByOtherBatchPaper > 0){
					String supplyMsg = usedBySupplyBatchPaperCount > 0 ? usedBySupplyBatchPaperCount + " 条被供卷批次启用的试卷未清除！ " : "";
					String FormalMsg = usedByOtherBatchPaper > 0 ? usedByOtherBatchPaper + " 条被复审批次选中未清除！" : "";
					
					object.put("msg", (notScannedPapers.size()-usedBySupplyBatchPaperCount - usedByOtherBatchPaper) + supplyMsg + FormalMsg);
				}else{
					object.put("msg", notScannedPapers.size() + " 条不满足记录的数据被清除。");
				}
				
			}
		}catch(Exception e){
			object.put("result", false);
			object.put("msg", e.getMessage());
		}
		this.outJsonString(response, object.toString());
	}

	/**
	 * 下载列表(下载指定批次下的DBF文件) 2014年8月27日
	 * 
	 * @author 钟辉
	 * @description
	 * @param request
	 * @param response
	 * @param id
	 *            批次id
	 */
	@RequestMapping("/downloadDBF/{batchId}")
	public void downLoadDBF(HttpServletRequest request,HttpServletResponse response, @PathVariable Integer batchId) {
		
		List<com.qmth.qrzk.paper.model.Paper> list = new ArrayList<com.qmth.qrzk.paper.model.Paper>();
		
		SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyyMMdd");
		String fileName = formatter.format(new Date()) + ".DBF";
		
		if(batchId != 0){
			List<PaperStateView> pswList = paperStateViewRepo.findByBatchId(batchId);
			for(PaperStateView psw : pswList){
				list.add(psw.getPaper());
			}
			PaperBatch pb = paperBatchService.findById(batchId);
			fileName = pb.getTitle() + "("+ pb.getType() +")"+formatter.format(new Date()) + ".DBF";
		}else{
			list = paperRepo.findAll();
		}
		
		String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
		if(!realPath.endsWith("/") && !realPath.endsWith("\\")){
			realPath = realPath + "/";
		}
		File file = new File(realPath,"DBF");
		if (!file.exists()) {
			file.mkdirs();
		}
		
		try {
			WriteDBF.writeToDBF(list, file + "/" + fileName);

			File ff = new File(file + "/" + fileName);// 构造要下载的文件
			if (ff.exists()) {
				InputStream ins = new FileInputStream(ff);// 构造一个读取文件的IO流对象
				BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面
				OutputStream outs = response.getOutputStream();// 获取文件输出IO流
				BufferedOutputStream bouts = new BufferedOutputStream(outs);
				response.setContentType("application/x-download");// 设置response内容的类型
				response.setHeader("Content-disposition","attachment;filename="+ new String(fileName.getBytes("GB18030"),"ISO8859-1"));// 设置头部信息
				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				// 开始向网络传输文件流
				while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
					bouts.write(buffer, 0, bytesRead);
				}
				bouts.flush();// 这里一定要调用flush()方法
				ins.close();
				bins.close();
				outs.close();
				bouts.close();
				File f = new File(realPath + "DBF/" + fileName);
				if (f.exists()) {
					f.delete();
				}
			} else {
				System.out.println("下载的文件不存在");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
//
//	@RequestMapping("/downFORMALDBF")
//	public void downFORMALDBF(HttpServletRequest request,HttpServletResponse response, PaperParams pp) {
//		List<Paper> list=new ArrayList<Paper>();
//		
//		pp.setRows(Integer.MAX_VALUE);
//		list = paperSerivce.getQYList(pp);
//		
//		
//		String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
//		File file = new File(realPath + "/DBF/");
//		if (!file.exists()) {
//			file.mkdirs();
//		}
//		SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyyMMdd"); 
//		String fileName=null;
//		if(pp.getName()==null){
//			fileName = formatter.format(new Date()) + ".DBF";
//		}else{
//			fileName= pp.getName()+formatter.format(new Date()) + ".DBF";
//		}
//		try {
//			WriteDBF.writeToFORMALDBF(list, file + "/" + fileName);
//
//			File ff = new File(file + "/" + fileName);// 构造要下载的文件
//			if (ff.exists()) {
//				InputStream ins = new FileInputStream(ff);// 构造一个读取文件的IO流对象
//				BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面
//				OutputStream outs = response.getOutputStream();// 获取文件输出IO流
//				BufferedOutputStream bouts = new BufferedOutputStream(outs);
//				response.setContentType("application/x-download");// 设置response内容的类型
//				response.setHeader("Content-disposition","attachment;filename="+ new String(fileName.getBytes("GB18030"),"ISO8859-1"));// 设置头部信息
//				int bytesRead = 0;
//				byte[] buffer = new byte[8192];
//				// 开始向网络传输文件流
//				while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
//					bouts.write(buffer, 0, bytesRead);
//				}
//				bouts.flush();// 这里一定要调用flush()方法
//				ins.close();
//				bins.close();
//				outs.close();
//				bouts.close();
//				File f = new File(realPath + "/DBF/" + fileName);
//				if (f.exists()) {
//					f.delete();
//				}
//			} else {
//				System.out.println("下载的文件不存在");
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}
	/**
	 * 下载试卷 2014年8月28日
	 * 
	 * @author 钟辉
	 * @description
	 * @param request
	 * @param response
	 * @param id
	 *            批次id
	 */
	@RequestMapping("/downloadPaper/{batchId}")
	public void downloadPaper(HttpServletRequest request,HttpServletResponse response,  @PathVariable int batchId) {
		JSONObject object = new JSONObject(); 
		String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
		if(!realPath.endsWith("/") && !realPath.endsWith("\\")){
			realPath = realPath + "/";
		}
		String zipFilePath = realPath + "zip/";
		String downPath=realPath + "down/";
		String downLoadPath=realPath + "download/";
		try{
			// 根据批次id查询出该批次是毛坯、清样、启用试卷
			PaperBatch pb = paperBatchService.findTypeById(batchId);
			
			if(pb == null){
				object.put("result", false);
				object.put("msg", "批次不存在！");
			}else{
				SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyyMMdd");
				List<CodeBook> codeBooks=codeBookService.getAllCodeBook();
				Random random=new Random(codeBooks.size());
				int index=random.nextInt(codeBooks.size());
				CodeBook codeBook=codeBooks.get(index);
				ZipUtil z = new ZipUtil();
				
				String zipName=formatter.format(new Date())+".zip";
				
				String fileName = pb.getCode()+zipName;
				
				List<Paper> batchPapers = paperSerivce.queryByBatchId(batchId);
				for (Paper p : batchPapers) {
					String newPath=zipFilePath +"/" +p.getCode()+"/";

					int folderNameIndex = p.getwPaperPath().lastIndexOf("/");
					String folderName = p.getwPaperPath().substring(0, folderNameIndex);
					FileTool.copyFolder(folderName, newPath);
					
					String[] answer=p.getStandardAnswerPath().split("/");
					String answerName=answer[answer.length-1];
					
					if(Consts.BATCH_TYPE_QIYONG.equals(pb.getType())){
						//启用批次下载电子试卷时，需要把答案和试卷分开存放。答案放在统一的目录。
						FileTool.copyFile(p.getStandardAnswerPath(), zipFilePath+ "/answer/", answerName);
					}else{
						//清样出库下载电子试卷时，需要把答案和试卷放在一个文件夹
						FileTool.copyFile(p.getStandardAnswerPath(), newPath, answerName);
					}
				}
				
				try {
					z.compress(zipFilePath, downPath+fileName, codeBook.getPassword(), true);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				File file=new File(downPath+"random.txt");
				if(!file.exists()){
					try {
						file.createNewFile();
						FileUtils.writeStringToFile(file, "随机码:"+codeBook.getRandomCode());
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
					
				CompressZIP.fileToZip(downPath, downLoadPath, zipName); // 打包成zip包
				
				object.put("result", true);
				codeBookService.deleteCodeBook(codeBook);
				FileTool.downLoad(response, downLoadPath, zipName);
				
			}
			
		}catch(Exception e){
			object.put("result", false);
		}finally{
			FileTool.delAllFile(zipFilePath); // 删除zip文件夹所有文件
			FileTool.delAllFile(downPath);
		}
	}

	/**
	 * 开始执行下载程序
	 * @param request
	 * @param response
	 * @param paperParams
	 */
	@RequestMapping("/beginDown")
	public void beginDown(HttpServletRequest request,HttpServletResponse response,  PaperParams paperParams) {
		try{
			FileTool.downLoad(response, paperParams.getPaperPath(), paperParams.getName()); // 下载试卷
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			FileTool.delAllFile(paperParams.getPaperPath());
		}
	}
	
	@RequestMapping("/makeZIPFile")
	public void makeZIPFile(HttpServletRequest request,HttpServletResponse response, @RequestBody PaperParams paperParams) {
		JSONObject object = new JSONObject(); 

		String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
		// 根据批次id查询出该批次是毛坯、清样、启用试卷
		PaperBatch pb = paperBatchService.findTypeById(paperParams.getBatchId());
		String header="";
		if (Consts.BATCH_TYPE_QINGYANG.equals(pb.getType())) {
			header="QYKJS";
		} else if (Consts.BATCH_TYPE_QIYONG.equals(pb.getType())) {
			header="CJ";
		}
		
		SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyyMMdd");
		String zipFilePath = realPath + "zip/";
		
		//删除zip目录下的文件
		FileTool.delAllFile(zipFilePath);
		
		String fileName = header +formatter.format(new Date())+ ".zip";
		
		List<Paper> papers=paperSerivce.getPapersByBatchId("", paperParams.getBatchId());
		for (Paper p : papers) {
//			String[] paper=p.getPaperPath().split("/");
			
			String folderPath=getFolderPath(p.getPaperPath());
			
			String newPath=zipFilePath +"/" +p.getCode()+"/";
			
//			FileTool.copyFile(p.getPaperPath(), newPath ,paperName);
			FileTool.copyFolder(folderPath, newPath);
			
			String[] answer=p.getStandardAnswerPath().split("/");
			String answerName=answer[answer.length-1];
			
			FileTool.copyFile(p.getStandardAnswerPath(), zipFilePath+ "/answer/", answerName);
		}
		String downPath = realPath + "/down/";
		CompressZIP.fileToZip(zipFilePath, downPath, fileName); // 打包成zip包
		
		object.put("type", "success");
		this.outJsonString(response, object.toString());
	}

	/**
	 * 扫描纸质试卷并且入库
	 * 
	 * 将扫描枪扫描到的条码与数据库中的试卷编码进行核对 如果数据库存在则修改入库状态 否则给予页面提示
	 * 
	 * 2014年9月3日 F
	 * 
	 * @author 钟辉
	 * @description
	 * @param code
	 *            扫描枪扫描到的条码
	 */
	@RequestMapping("/instorage")
	public void storageScanned(HttpServletRequest request,HttpServletResponse response, @RequestBody PaperParams paperParams) {
		//入库扫描 前提条件是 :检验电子文档是否全部入库 
		int result = paperSerivce.queryPaperCountByCodeAndBatchId(paperParams.getCode(), paperParams.getBatchId());
		Paper pp=paperSerivce.getPaperByCodeBatchId(paperParams.getCode(), paperParams.getBatchId());
		//检查该试卷是否已经出库扫描
		PaperPaperBatch ppb=null;
		if(pp!=null){
			ppb=paperPaperBatchService.findPaperPaperBatch(paperParams.getBatchId(), pp.getId());
		}
		
		JSONObject object = new JSONObject();
		// result>0表示根据查询条件查出相应code,
		if (result == 1) {
			
			Paper paper = paperSerivce.getPaperByCodeBatchId(paperParams.getCode(), paperParams.getBatchId());
			
			PaperBatch paperBatch = paperBatchService.findTypeById(paperParams.getBatchId());

			boolean isUpdateScanStatus = false;
		
			if(PaperBatch.QINGYANG.equalsIgnoreCase(paperBatch.getType())){
				PaperPaperBatch paperPaperBatch = paperPaperBatchService.findPaperPaperBatch(paperParams.getBatchId(), paper.getId());
//				boolean isPaperReturned = (paperPaperBatch.getIsPaperReturn() == 1) ? true : false;
				boolean isPaperReturned = true;
				//boolean isStandardAnswerReturned = (paperPaperBatch.getIsStandadAnswerReturn() == 1) ? true : false;
				boolean isAnswerSheetReturned = (paper.getIsSpecialAnswerSheet() == 1) ? (paperPaperBatch.getIsAnswerSheetReturn() == 1) : true;
				boolean isSeparatePaperReturned = (paper.getSeparatePaperPath() != null) ? (paperPaperBatch.getIsSeparatePaperReturn() == 1) : true;
				boolean isWPaperReturned = (paper.getwPaperPath() != null) ? (paperPaperBatch.getIsWPaperReturn() == 1) : true;
				boolean isZyReturned = (paper.getZyPath() != null) ? (paperPaperBatch.getIsZyReturn() == 1) : true;
				
				isUpdateScanStatus = isPaperReturned  && isAnswerSheetReturned && isSeparatePaperReturned && isWPaperReturned && isZyReturned;
			} else if(PaperBatch.RUKU.equalsIgnoreCase(paperBatch.getType())){
				if(paper.isPaperFilesUploaded()){
					isUpdateScanStatus = true;
				}else{
					isUpdateScanStatus = false;
					object.put("result", false);
					object.put("msg", "请先上传电子文档再入库扫描!");
				}
			} else if(PaperBatch.QIYONG.equalsIgnoreCase(paperBatch.getType())){
				isUpdateScanStatus = true;
				if(ppb!=null){
					if(ppb.getIsOutBoundScanned()==0){
						isUpdateScanStatus=false;
						object.put("result", false);
						object.put("msg", "请先做出库扫描后再进行入库扫描！");
					}
				}
				
				//启用回库的话 需要将状态修改成清样、将该试卷信息(试卷、标答、专卡移到清样目录下)
				
				String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
				if(!realPath.endsWith("/") && !realPath.endsWith("\\")){
					realPath = realPath + "/";
				}
				Paper p=paperSerivce.getPaperByCodeBatchId(paperParams.getCode(), paperParams.getBatchId());
				if(p.getStatus().equals(PaperStatusEnum.PAPER_USED.getKey())){
					
					p.setStatus(PaperStatusEnum.PAPER_FORMAL.getKey());
					
					FileTool.copyFolder(realPath+"paper/qiyong/"+p.getCode(), realPath+"paper/qingyang/"+p.getCode());
					FileTool.delFolder(realPath+"paper/qiyong/"+p.getCode());
					
					String[] answer=p.getStandardAnswerPath().split("/");
					String answerName=answer[answer.length-1];
					
					String[] paperPath=p.getPaperPath().split("/");
					String paperName=paperPath[paperPath.length-1];
					
					FileTool.copyFile(p.getStandardAnswerPath(), realPath+"paper/qingyang/answer/", answerName);
					FileTool.deletefile(p.getStandardAnswerPath());
					p.setPaperPath(realPath+"paper/qingyang/"+p.getCode()+"/"+paperName);
					p.setStandardAnswerPath(realPath+"paper/qingyang/answer/"+answerName);
					paperSerivce.updateStatusPath(p);
				}
			}
			if(isUpdateScanStatus){
				// 修改相应的入库状态
				PaperBatchParams pbp = new PaperBatchParams();
				pbp.setCode(paperParams.getCode());
				pbp.setBatchId(paperParams.getBatchId());
				pbp.setIsStorageScanned(1);
				paperPaperBatchService.updateInfo(pbp);
				
				PaperBatch pb=new PaperBatch();
				pb.setUpdatedTime(new Date());
				pb.setId(paperParams.getBatchId());
				int rs=updateUpdateTime(pb);
				if(rs>0){
					object.put("result", true);
				}else{
					object.put("result", false);
				}
			}
			object.put("paper", paper);
		} else {
			object.put("result", false);
			object.put("msg", "试卷在当前批次不存在！");
		}
		this.outJsonString(response, object.toString());
	}

	/**
	 * 出库扫描 2014年9月9日
	 * 
	 * @author 钟辉
	 * @description
	 * @param request
	 * @param response
	 * @param code
	 *            扫描枪扫描到的条码
	 */
	@RequestMapping("/outbound")
	public void outbound(HttpServletRequest request,HttpServletResponse response, @RequestBody PaperParams paperParams) {
		int result = paperSerivce.queryPaperCountByCodeAndBatchId(paperParams.getCode(), paperParams.getBatchId());

		JSONObject object = new JSONObject();
		// result>0表示根据查询条件查出相应code,
		if (result > 0) {
			// 修改相应的出库状态
			PaperBatchParams pbp = new PaperBatchParams();
			pbp.setCode(paperParams.getCode());
			pbp.setBatchId(paperParams.getBatchId());
			pbp.setIsOutBoundScanned(1);
			pbp.setIsStorageScanned(0);//将入库状态重置
			paperPaperBatchService.updateInfo(pbp);

			Paper paper = paperSerivce.getPaperByCodeBatchId(
					paperParams.getCode(), paperParams.getBatchId());
			object.put("paper", paper);
			
			object.put("result", true);
		} else {
			object.put("result", false);
		}
		this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/reviewInScan")
	public void reviewInScan(HttpServletRequest request,HttpServletResponse response, @RequestBody PaperParams paperParams) {
		Paper paper = paperSerivce.getPaperByCodeBatchId(paperParams.getCode(), paperParams.getBatchId());
		
		JSONObject object = new JSONObject();
		// result>0表示根据查询条件查出相应code,
		if (paper != null) {
			PaperPaperBatch ppb = paperPaperBatchService.findPaperPaperBatch(paperParams.getBatchId(), paper.getId());	
			
			if(ppb.getIsStorageScanned() != 1){
				boolean allFileUploaded = 
//						ppb.getIsPaperReturn() == 1 
//						&& 
						ppb.getIsStandadAnswerReturn() == 1
						&& (paper.getAnswerSheetPath() != null ? ppb.getIsAnswerSheetReturn() == 1 : true)
						&& (paper.getSeparatePaperPath() != null ? ppb.getIsSeparatePaperReturn() == 1 : true)
						&& (paper.getwPaperPath() != null ? ppb.getIsWPaperReturn() == 1 : true)
						&& (paper.getZyPath() != null ? ppb.getIsZyReturn() == 1 : true);
				
				if(allFileUploaded){
					// 修改相应的出库状态
					ppb.setIsStorageScanned(1);
					paperPaperBatchService.updatePaperPaperBatch(ppb);
					
					//移动试卷位置
					String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
					String oldPath = realPath + "paper/maopi/" + paper.getCode();
					
					String answerPath = paper.getStandardAnswerPath();
					String[] ss = answerPath.split("/");
					String name = ss[ss.length - 1];
					
					String newPath = realPath + "paper/qingyang/" + paper.getCode();
					
					FileTool.copyFolder(oldPath, newPath); // 复制文件夹
					FileTool.copyFile(answerPath, realPath + "paper/qingyang/answer/",name); // 复制标答
					
					FileTool.delFolder(oldPath);
					FileTool.deletefile(realPath + "paper/maopi/answer/" + name);
				
					//修改试卷状态
					paper.setStandardAnswerPath(paper.getStandardAnswerPath().replace("maopi", "qingyang"));
					if(paper.getAnswerSheetPath() != null){
						paper.setAnswerSheetPath(paper.getAnswerSheetPath().replace("maopi", "qingyang"));
					}
					if(paper.getSeparatePaperPath() != null){
						paper.setSeparatePaperPath(paper.getSeparatePaperPath().replace("maopi", "qingyang"));
					}
					if(paper.getPaperPath() != null){
						paper.setPaperPath(paper.getPaperPath().replace("maopi", "qingyang"));
					}
					if(paper.getwPaperPath() != null){
						paper.setwPaperPath(paper.getwPaperPath().replace("maopi", "qingyang"));
					}
					if(paper.getZyPath() != null){
						paper.setZyPath(paper.getZyPath().replace("maopi", "qingyang"));
					}
					paper.setStatus("FORMAL");
					paperSerivce.updateStatusPath(paper);
					
					object.put("paper", paper);
					object.put("result", true);
					
				}else{
					object.put("result", false);
					object.put("msg", "试卷文档没有全部上传！");
				}
			}else{
				//如果试卷已经回库，则返回正常状态
				object.put("paper", paper);
				object.put("result", true);
			}
		} else {
			object.put("result", false);
			object.put("msg", "试卷编号在当前批次不存在！");
		}
		this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/useInScan")
	public void useInScan(HttpServletRequest request,HttpServletResponse response, @RequestBody PaperParams paperParams) {
		Paper paper = paperSerivce.getPaperByCodeBatchId(paperParams.getCode(), paperParams.getBatchId());
		
		JSONObject object = new JSONObject();
		//禁止有共卷的课程试卷回库
		List<BatchGJCourse> gjCourses = gjRepo.findByBatchId(paperParams.getBatchId(), null);
		boolean isGjCourse = false;
		if(gjCourses.size() > 0){
			Set<String> courseCodes = new HashSet<String>();
			for(BatchGJCourse gjCourse : gjCourses){
				courseCodes.add(gjCourse.getCourseCode());
				courseCodes.add(gjCourse.getbCourseCode());
			}
			
			String inScanCourseCode = paperParams.getCode().substring(0, 5);
			
			if(courseCodes.contains(inScanCourseCode)){
				isGjCourse = true;
				object.put("result", false);
				object.put("msg", "共卷的课程试卷不能回库！");
			}
		}
		
		if(!isGjCourse){
			// result>0表示根据查询条件查出相应code,
			if (paper != null) {
				PaperPaperBatch ppb = paperPaperBatchService.findPaperPaperBatch(paperParams.getBatchId(), paper.getId());	
				
				if(ppb.getIsStorageScanned() != 1){
					// 修改相应的出库状态
					ppb.setIsStorageScanned(1);
					ppb.setIsOutBoundScanned(0); //将出库扫描状态重置
					paperPaperBatchService.updatePaperPaperBatch(ppb);
					
					//移动试卷位置
					String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
					String oldPath = realPath + "paper/qiyong/" + paper.getCode();
					
					String answerPath = paper.getStandardAnswerPath();
					String[] ss = answerPath.split("/");
					String name = ss[ss.length - 1];
					
					String newPath = realPath + "paper/qingyang/" + paper.getCode();
					
					FileTool.copyFolder(oldPath, newPath); // 复制文件夹
					FileTool.copyFile(answerPath, realPath + "paper/qingyang/answer/",name); // 复制标答
					
					FileTool.delFolder(oldPath);
					FileTool.deletefile(realPath + "paper/qiyong/answer/" + name);
					
					//修改试卷状态
					paper.setStandardAnswerPath(paper.getStandardAnswerPath().replace("qiyong", "qingyang"));
					if(paper.getAnswerSheetPath() != null){
						paper.setAnswerSheetPath(paper.getAnswerSheetPath().replace("qiyong", "qingyang"));
					}
					if(paper.getSeparatePaperPath() != null){
						paper.setSeparatePaperPath(paper.getSeparatePaperPath().replace("qiyong", "qingyang"));
					}
					if(paper.getPaperPath() != null){
						paper.setPaperPath(paper.getPaperPath().replace("qiyong", "qingyang"));
					}
					if(paper.getwPaperPath() != null){
						paper.setwPaperPath(paper.getwPaperPath().replace("qiyong", "qingyang"));
					}
					paper.setStatus("FORMAL");
					paperSerivce.updateStatusPath(paper);
					
					object.put("paper", paper);
					object.put("result", true);
				}else{
					//如果试卷已经回库，则返回正常状态
					object.put("paper", paper);
					object.put("result", true);
				}
			} else {
				object.put("result", false);
				object.put("msg", "试卷编号在当前批次不存在！");
			}
		}
		
		this.outJsonString(response, object.toString());
	}

	/**
	 * 撤销入库操作 2014年9月4日
	 * 
	 * @author 钟辉
	 * @description
	 * @param request
	 * @param response
	 * @param code
	 *            条码
	 */
	@RequestMapping("/revocationInStorage")
	public void revocationInStorage(HttpServletRequest request,
			HttpServletResponse response, @RequestBody PaperParams pp) {
		PaperBatchParams pbp = new PaperBatchParams();
		pbp.setCode(pp.getCode());
		pbp.setBatchId(pp.getBatchId());
		pbp.setIsStorageScanned(0);

		pbp.setIsAnswerSheetReturn(1);
		pbp.setIsPaperReturn(1);
		pbp.setIsStandardAnswerReturn(1);
		pbp.setIsOutBoundScanned(1);

		int result = paperPaperBatchService.updateRevocation(pbp);

		JSONObject object = new JSONObject();
		if (result > 0) {
			object.put("type", "success");
		} else {
			object.put("type", "fail");
		}
		this.outJsonString(response, object.toString());
	}

	@RequestMapping("/revocationOutBound")
	public void revocationOutBound(HttpServletRequest request,
			HttpServletResponse response, @RequestBody PaperParams pp) {

		PaperBatchParams pbp = new PaperBatchParams();
		pbp.setCode(pp.getCode());
		pbp.setBatchId(pp.getBatchId());
		pbp.setIsOutBoundScanned(0);

		pbp.setIsAnswerSheetReturn(1);
		pbp.setIsPaperReturn(1);
		pbp.setIsStandardAnswerReturn(1);
		pbp.setIsStorageScanned(1);
		int result = paperPaperBatchService.updateRevocation(pbp);

		JSONObject object = new JSONObject();
		if (result > 0) {
			object.put("type", "success");
		} else {
			object.put("type", "fail");
		}
		this.outJsonString(response, object.toString());
	}

	/**
	 * 撤销清样 2014年9月23日
	 * 
	 * @author 钟辉
	 * @description
	 * @param request
	 * @param response
	 * @param pp
	 */
	@RequestMapping("/rejectFormal")
	public void rejectFormal(HttpServletRequest request,HttpServletResponse response, @RequestBody PaperParams pp) {
		String[] ids = pp.getArray();
		JSONObject object = new JSONObject();
		String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
		for (int i = 0; i < ids.length; i++) {
			Paper paper = paperSerivce.findPaperById(Integer.parseInt(ids[i]));
			// 1.修改试卷状态
			Paper p = new Paper(Integer.parseInt(ids[i]), "DRAFT");
			paperSerivce.updateStatusPath(p);

			// 2.移动试卷从清样移出
			String newPath = realPath + "paper/maopi/" + paper.getCode();
			String oldPath = realPath + "paper/qingyang/" + paper.getCode();

			String answerPath = paper.getStandardAnswerPath();
			String[] ss = answerPath.split("/");
			String name = ss[ss.length - 1];

			String path = realPath + "paper/maopi/answer/" + name;

			FileTool.copyFolder(oldPath, newPath); // 复制文件夹
			FileTool.copyFile(answerPath, realPath + "paper/maopi/answer/",name); // 复制标答

			FileTool.delFolder(oldPath);
			FileTool.deletefile(realPath + "paper/qingyang/answer/" + name);

			// 3.修改paper_path路径
			// 是专卡
			if (paper.getIsSpecialAnswerSheet() == 1) {
				String paperPath = paper.getPaperPath();
				String[] s = paperPath.split("/");
				String paperName = s[s.length - 1];
				String answerSheetPath=paper.getAnswerSheetPath();
				String[] sss = answerSheetPath.split("/");
				String answerSheetName=sss[sss.length-1];
				Paper updatePaper = new Paper(paper.getId(),newPath+"/"+paperName, path, newPath+"/"+answerSheetName);
				try {
					paperSerivce.updateStatusPath(updatePaper);
					object.put("type", "success");
				} catch (Exception e) {
					e.printStackTrace();
					object.put("type", "fail");
				}
			} else {
				String paperPath = paper.getPaperPath();
				String[] s = paperPath.split("/");
				String paperName = s[s.length - 1];
				
				
				Paper updatePaper = new Paper(paper.getId(),newPath+"/"+paperName, path);
				try {
					paperSerivce.updateStatusPath(updatePaper);
					object.put("type", "success");
				} catch (Exception e) {
					e.printStackTrace();
					object.put("type", "fail");
				}
			}
			
			PaperBatch pb=new PaperBatch();
			pb.setUpdatedTime(new Date());
			pb.setId(pp.getBatchId());
			int rs=updateUpdateTime(pb);
			if(rs>0){
				object.put("type", "success");
			}else{
				object.put("type", "fail");
			}
		}
		this.outJsonString(response, object.toString());
	}

	/**
	 * 确认启用 2014年9月24日
	 * 
	 * @author 钟辉
	 * @description
	 */
	@RequestMapping("/confirmUsedPapers")
	public void confirmUsedPapers(HttpServletRequest request,
			HttpServletResponse response, @RequestBody PaperParams pp) {
		String[] ids = pp.getArray();
		JSONObject object = new JSONObject();
		String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
		for (int i = 0; i < ids.length; i++) {
			Paper paper = paperSerivce.findPaperById(Integer.parseInt(ids[i]));
			// 1.修改试卷状态
			Paper p = new Paper(Integer.parseInt(ids[i]), "USED");
			paperSerivce.updateStatusPath(p);

			// 2.移动试卷文件夹至启用
			String oldPath = realPath + "paper/qingyang/" + paper.getCode();

			String answerPath = paper.getStandardAnswerPath();
			String[] ss = answerPath.split("/");
			String name = ss[ss.length - 1];

			String newPath = realPath + "paper/qiyong/" + paper.getCode();
			String path = realPath + "paper/qiyong/answer/" + name;

			FileTool.copyFolder(oldPath, newPath); // 复制文件夹
			FileTool.copyFile(answerPath, realPath + "paper/qiyong/answer/",name); // 复制标答

			FileTool.delFolder(oldPath);
			FileTool.deletefile(realPath + "paper/qingyang/answer/" + name);

			// 3.修改paper_path路径
			// 是专卡
			if (paper.getIsSpecialAnswerSheet() == 1) {
				String paperPath = paper.getPaperPath();
				String[] s = paperPath.split("/");
				String paperName = s[s.length - 1];
				String answerSheetPath=paper.getAnswerSheetPath();
				String[] sss = answerSheetPath.split("/");
				String answerSheetName=sss[sss.length-1];
				Paper updatePaper = new Paper(paper.getId(),newPath+"/"+paperName, path, newPath+"/"+answerSheetName);
				try {
					paperSerivce.updateStatusPath(updatePaper);
					object.put("type", "success");
				} catch (Exception e) {
					e.printStackTrace();
					object.put("type", "fail");
				}
			} else {
				String paperPath = paper.getPaperPath();
				String[] s = paperPath.split("/");
				String paperName = s[s.length - 1];
				
				
				Paper updatePaper = new Paper(paper.getId(),newPath+"/"+paperName, path);
				try {
					paperSerivce.updateStatusPath(updatePaper);
					object.put("type", "success");
				} catch (Exception e) {
					e.printStackTrace();
					object.put("type", "fail");
				}
			}
			
			PaperBatch pb=new PaperBatch();
			pb.setUpdatedTime(new Date());
			pb.setId(pp.getBatchId());
			updateUpdateTime(pb);
		}

		this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/confirmUsedPapersAll")
	public void confirmUsedPapersAll(HttpServletRequest request,HttpServletResponse response, @RequestBody PaperParams pp) {
		//1.根据批次id 从qr_paper_paper_batch表中查询出该批次下存在没有做入库扫描的
		JSONObject object = new JSONObject();
		PaperParams paperParams=new PaperParams();
		paperParams.setBatchId(pp.getBatchId());
		paperParams.setIsOutBoundScanned(0);
		int count=paperPaperBatchService.getCountIsOutBoundScanned(paperParams);
		if(count>0){
			object.put("type", "fail");
			object.put("msg", "有未出库扫描的试卷，无法全部启用！");
		}else{
			object.put("type", "success");
			
			List<Paper> ls=paperSerivce.getPapersByBatchId("", pp.getBatchId()); //该批次下所有的试卷id
			String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
			for(Paper paper:ls){
				if(paper.getStatus().equals(PaperStatusEnum.PAPER_FORMAL.getKey())){	//避免将该批次下启用的试卷进行清样操作
					//Paper paper = paperSerivce.findPaperById(Integer.parseInt(ids[i]));
					// 1.修改试卷状态
					Paper p = new Paper(paper.getId(), PaperStatusEnum.PAPER_USED.getKey());
					paperSerivce.updateStatusPath(p);

					// 2.移动试卷文件夹至启用
					String oldPath = realPath + "paper/qingyang/" + paper.getCode();

					String answerPath = paper.getStandardAnswerPath();
					String[] ss = answerPath.split("/");
					String name = ss[ss.length - 1];

					String newPath = realPath + "paper/qiyong/" + paper.getCode();
					String path = realPath + "paper/qiyong/answer/" + name;

					FileTool.copyFolder(oldPath, newPath); // 复制文件夹
					FileTool.copyFile(answerPath, realPath + "paper/qiyong/answer/",name); // 复制标答

					FileTool.delFolder(oldPath);
					FileTool.deletefile(realPath + "paper/qingyang/answer/" + name);

					// 3.修改paper_path路径
					// 是专卡
					if (paper.getIsSpecialAnswerSheet() == 1) {
						String paperPath = paper.getPaperPath();
						String[] s = paperPath.split("/");
						String paperName = s[s.length - 1];
						String answerSheetPath=paper.getAnswerSheetPath();
						String[] sss = answerSheetPath.split("/");
						String answerSheetName=sss[sss.length-1];
						Paper updatePaper = new Paper(paper.getId(),newPath+"/"+paperName, path, newPath+"/"+answerSheetName);
						try {
							paperSerivce.updateStatusPath(updatePaper);
							object.put("type", "success");
						} catch (Exception e) {
							e.printStackTrace();
							object.put("type", "fail");
						}
					} else {
						String paperPath = paper.getPaperPath();
						String[] s = paperPath.split("/");
						String paperName = s[s.length - 1];
						
						
						Paper updatePaper = new Paper(paper.getId(),newPath+"/"+paperName, path);
						try {
							paperSerivce.updateStatusPath(updatePaper);
							object.put("type", "success");
						} catch (Exception e) {
							e.printStackTrace();
							object.put("type", "fail");
						}
					}
				}
			}
		}
		this.outJsonString(response, object.toString());		
	}

	/**
	 * 撤销启用 2014年9月24日
	 * 
	 * @author 钟辉
	 * @description
	 */
	@RequestMapping("/revertUsedPapersToFormal")
	public void revertUsedPapersToFormal(HttpServletRequest request,HttpServletResponse response, @RequestBody PaperParams pp) {
		String[] ids = pp.getArray();
		JSONObject object = new JSONObject();
		String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
		for (int i = 0; i < ids.length; i++) {
			Paper paper = paperSerivce.findPaperById(Integer.parseInt(ids[i]));
			// 1.修改试卷状态
			Paper p = new Paper(Integer.parseInt(ids[i]), "FORMAL");
			paperSerivce.updateStatusPath(p);

			// 2.移动试卷从启用移出
			String newPath = realPath + "paper/qingyang/" + paper.getCode();
			String oldPath = realPath + "paper/qiyong/" + paper.getCode();

			String answerPath = paper.getStandardAnswerPath();
			String[] ss = answerPath.split("/");
			String name = ss[ss.length - 1];

			String path = realPath + "paper/qingyang/answer/" + name;

			FileTool.copyFolder(oldPath, newPath); // 复制文件夹
			FileTool.copyFile(answerPath, realPath + "paper/qingyang/answer/",name); // 复制标答

			FileTool.delFolder(oldPath);
			FileTool.deletefile(realPath + "paper/qiyong/answer/" + name);

			// 3.修改paper_path路径
			// 是专卡
			if (paper.getIsSpecialAnswerSheet() == 1) {
				String paperPath = paper.getPaperPath();
				String[] s = paperPath.split("/");
				String paperName = s[s.length - 1];
				String answerSheetPath=paper.getAnswerSheetPath();
				String[] sss = answerSheetPath.split("/");
				String answerSheetName=sss[sss.length-1];
				Paper updatePaper = new Paper(paper.getId(),newPath+"/"+paperName, path, newPath+"/"+answerSheetName);
				try {
					paperSerivce.updateStatusPath(updatePaper);
					object.put("type", "success");
				} catch (Exception e) {
					e.printStackTrace();
					object.put("type", "fail");
				}
			} else {
				String paperPath = paper.getPaperPath();
				String[] s = paperPath.split("/");
				String paperName = s[s.length - 1];
				
				
				Paper updatePaper = new Paper(paper.getId(),newPath+"/"+paperName, path);
				try {
					paperSerivce.updateStatusPath(updatePaper);
					object.put("type", "success");
				} catch (Exception e) {
					e.printStackTrace();
					object.put("type", "fail");
				}
			}
			
			PaperBatch pb=new PaperBatch();
			pb.setUpdatedTime(new Date());
			pb.setId(pp.getBatchId());
			updateUpdateTime(pb);
		}
		this.outJsonString(response, object.toString());
	}

	/**
	 * 添加试卷到清样批次 2014年9月5日
	 * 
	 * @author 钟辉
	 * @description
	 * @param arr
	 * @param batchId
	 *            清样的批次号
	 */
	@RequestMapping("/addPapersToBatch")
	@ResponseBody
	public Map<String, Object> addPapersToBatch(int batchId,@RequestParam(value = "paperIds") String[] paperIds) {
		try {
			for(String paperId : paperIds){
				PaperPaperBatch ppb = new PaperPaperBatch();
				ppb.setBatchId(batchId);
				ppb.setPaperId(Integer.parseInt(paperId));
				paperSerivce.insertPaperPaperBatch(ppb);
			}
			return this.successResult(null);
		} catch (Exception e) {
			e.printStackTrace();
			return this.failedResult("操作失败！");
		}
	}

	@RequestMapping("/addPaperToBatch")
	@ResponseBody
	public Map<String, Object> addPaperToBatch(@RequestBody PaperPaperBatch ppb) {
		try {
			//paperSerivce.removePapersFromOldBatch(paperIds);
			paperSerivce.insertPaperPaperBatch(ppb);
			return this.successResult(null);
		} catch (Exception e) {
			e.printStackTrace();
			return this.failedResult("操作失败！");
		}
	}
	
	@RequestMapping("/removePaperFromBatch")
	@ResponseBody
	public Map<String, Object> removePaperFromBatch(@RequestBody PaperPaperBatch ppb) {
		try {
			//paperSerivce.removePapersFromOldBatch(paperIds);
			paperSerivce.deletePaperPaperBatch(ppb);
			return this.successResult(null);
		} catch (Exception e) {
			e.printStackTrace();
			return this.failedResult("操作失败！");
		}
	}
	/**
	 * 添加试卷 2014年9月8日
	 * 
	 * @author 钟辉
	 * @description
	 */
	@RequestMapping("/addPaper")
	public void addPaper(HttpServletRequest request,
			HttpServletResponse response, @RequestBody Paper paper) {

		JSONObject object = new JSONObject();
		try {
			paperSerivce.addPaper(paper);
			object.put("type", "success");
		} catch (Exception e) {
			e.printStackTrace();
			object.put("type", "fail");
		}
		this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/addPaperInfo/{id}")
	public void addPaperInfo(HttpServletResponse response, @RequestBody Paper p,@PathVariable int id) {
		JSONObject object = new JSONObject();
		
		List<String> ls=paperSerivce.getAllCode();
		boolean isCodeExists=ls.contains(p.getCode());
		if(isCodeExists){
			object.put("result", false);
			object.put("msg", "试卷编码已存在！");
		}else{
			try {
				paperSerivce.insertPaper(p);
				PaperPaperBatch ppb = new PaperPaperBatch(id,
						p.getId(), 0, 0, 0, 0, 0, p.getBookId(),
						p.getBookName(), p.getBookAuthor(),
						p.getBookPress(), p.getBookPressYear(),
						p.getSchool(), p.getRemark());
				paperPaperBatchService.insertPaperPaperBatch(ppb);
				object.put("result", true);
			} catch (Exception e) {
				e.printStackTrace();
				object.put("result", false);
			}
		}
		this.outJsonString(response, object.toString());
	}

	@RequestMapping("/deletePaper/{batchId}/{paperId}")
	public AjaxResponse deletePaper(HttpServletRequest request,HttpServletResponse response, @PathVariable Integer batchId, @PathVariable Long paperId) {
		List<PaperStateView> allPaperRelates = paperStateViewRepo.findByPaperId(paperId);
		if(allPaperRelates.size() > 1){
			AjaxResponse result = new AjaxResponse(false);
			result.setMsg("试卷被其他批次关联，无法删除！");
			return result;
		}
		
		List<SupplyCourse> relatedSupplyCourse = supplyCourseRepo.findByPaperId(paperId);
		if(relatedSupplyCourse.size() > 0){
			AjaxResponse result = new AjaxResponse(false);
			result.setMsg("试卷被供卷批次启用，无法删除！");
			return result;
		}		
		
		List<PaperStateView> psws = paperStateViewRepo.findByBatchIdAndPaperId(batchId, paperId);

		for(PaperStateView psw : psws){
			// 1先删除 关联表信息
			paperStateViewRepo.delete(psw);
		}
		AjaxResponse object = new AjaxResponse(false);
		
		com.qmth.qrzk.paper.model.Paper p = paperRepo.findOne(paperId);
		paperRepo.delete(p); //2. 删除试卷信息
		
		// 3 删除指定位置下的对应的文件信息
		String realPath = ServerConfig.getInstance().getWorkInfo()
				.getProperty("URL");
		realPath += "paper/maopi/";
		FileTool.delFolder(realPath + p.getCode());
		FileTool.deletefile(realPath+"answer/"+p.getCode()+"N.doc");
		FileTool.deletefile(realPath+"answer/"+p.getCode()+"N.docx");

		PaperBatch pb=new PaperBatch();
		pb.setUpdatedTime(new Date());
		pb.setId(batchId);
		int rs=updateUpdateTime(pb);
		if(rs>0){
			object.setResult(true);
		}
		
		return object;
	}
	
	private int updateUpdateTime(PaperBatch pb){
		return paperBatchService.updateTime(pb);
	}

	@RequestMapping("/removeFromBatch")
	public void removeFromBatch(HttpServletRequest request,
			HttpServletResponse response, @RequestBody PaperParams pp) {

		int result = paperPaperBatchService.removeFromBatch(pp);
		JSONObject object = new JSONObject();
		if (result > 0) {
			object.put("type", "success");
		} else {
			object.put("type", "fail");
		}
		this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/validateRemoveBatch")
	public void validateRemoveBatch(HttpServletResponse response,@RequestBody PaperParams pp){
		int count=paperPaperBatchService.findPaperIdByBatchId(pp.getBatchId()).size();
		JSONObject object = new JSONObject();
		if(count>0){
			object.put("type", "fail");
		}else{
			object.put("type", "success");
		}
		this.outJsonString(response, object.toString());
	}
	@RequestMapping("/removeBatch")
	public void removeBatch(HttpServletResponse response,@RequestBody PaperParams pp){
		String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
		if(pp.getDeleteBatch()!=null){
			List<Integer> paperIds=paperPaperBatchService.findPaperIdByBatchId(pp.getBatchId());
			String[] array=new String[paperIds.size()];
			for(int i=0;i<paperIds.size();i++){
				array[i]=paperIds.get(i).toString();
			}
			pp.setArray(array);
			List<Paper> papers=paperSerivce.queryPapers(pp);
			paperPaperBatchService.deleteByBatchId(pp.getBatchId());
			paperBatchService.deleteBatch(pp.getBatchId());
			paperSerivce.deletePaper(pp);
			for(Paper p:papers){
				String type="";
				if(p.getStatus().equals(PaperStatusEnum.PAPER_DRAFT.getKey())){
					type="maopi";
				}else if(p.getStatus().equals(PaperStatusEnum.PAPER_FORMAL.getKey())){
					type="qingyang";
				}else if(p.getStatus().equals(PaperStatusEnum.PAPER_USED.getKey())){
					type="qiyong";
				}
				FileTool.delFolder(realPath+"paper/"+type+"/"+p.getCode());
				FileTool.deletefile(p.getStandardAnswerPath());
			}
		}else{
			paperBatchService.deleteBatch(pp.getBatchId());
		}
		JSONObject object = new JSONObject();
		object.put("type", "success");
		this.outJsonString(response, object.toString());
	}

	@RequestMapping("/list")
	public ModelAndView list() {
		ModelAndView view = new ModelAndView(BASE_JSP_PATH + "list");
		List<PaperBatch> ls = paperBatchService.findAllBatch();
		view.addObject("batchs", ls);
		return view;
	}
	
	@RequestMapping("/stock")
	public ModelAndView stock() {
		ModelAndView view = new ModelAndView(BASE_JSP_PATH + "stock");
		return view;
	}
	
	@RequestMapping("/listBatch")
	@ResponseBody
	public String listBatch() {
		JSONArray array = new JSONArray();
		List<PaperBatch> ls = paperBatchService.findAllBatch();
		for (PaperBatch pb : ls) {
			JSONObject object = new JSONObject();
			object.put("id", pb.getId());
			object.put("code", pb.getCode());
			object.put("type", pb.getType());
			array.add(object);
		}
		return array.toString();
	}

	/**
	 * 试卷检索页面提供的查询 2014年9月14日
	 * 
	 * @author 钟辉
	 * @description
	 * @param pp
	 * @return
	 */
	@RequestMapping("/paperSearch")
	@ResponseBody
	public Map<String, Object> paperSearch(@RequestBody PaperParams pp) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<Paper> list = paperSerivce.paperSearch(pp);
		int total = paperSerivce.paperSearchCount(pp);
			result.put("rows", list);
			result.put("total", total);
		return result;
	}
	
	@RequestMapping("/queryTotal")
	@ResponseBody
	public Map<String, Object> queryTotal(@RequestBody PaperParams pp) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<Paper> list = paperSerivce.queryTotal(pp);
		int total = paperSerivce.queryTotalCount(pp);
		result.put("rows", list);
		result.put("total", total);
		return result;
	}

	@RequestMapping(value = "/printAllCodeInfo/{batchId}")
	public ModelAndView printAllCodeInfo(HttpServletRequest request, @PathVariable String batchId) {
		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH+ "printCode");
		PaperBatch pb = paperBatchService.findById(Integer.parseInt(batchId));
		List<Paper> papers = paperSerivce.queryByBatchId(pb.getId());
		modelAndView.addObject("paperBatch", pb);
		modelAndView.addObject("papers", papers);
		modelAndView.addObject("paperSize", papers == null ? 0 : papers.size());
		return modelAndView;
	}
	
	@RequestMapping(value = "/printAllAnswerCodeInfo/{batchId}")
	public ModelAndView printAllAnswerCodeInfo(HttpServletRequest request, @PathVariable String batchId) {
		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH+ "printCode");
		PaperBatch pb = paperBatchService.findById(Integer.parseInt(batchId));
		List<Paper> papers = paperSerivce.queryByBatchId(pb.getId());
		
		for(Paper p:papers){
			p.setCode(p.getCode()+"N");
		}
		modelAndView.addObject("paperBatch", pb);
		modelAndView.addObject("papers", papers);
		modelAndView.addObject("paperSize", papers == null ? 0 : papers.size());
		return modelAndView;
	}
	
	@RequestMapping(value = "/printAnswerCodeInfo/{arr}")
	public ModelAndView printAnswerCodeInfo(HttpServletRequest request, @PathVariable String arr) {
		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH+ "printCode");
		PaperParams pp=new PaperParams();
		String[] array=arr.split(",");
		pp.setArray(array);
		List<Paper> papers = paperSerivce.queryPapers(pp);
		for(Paper p:papers){
			p.setCode(p.getCode()+"N");
		}
		modelAndView.addObject("papers", papers);
		return modelAndView;
	}
	
	
	@RequestMapping(value = "/printCodeInfo/{arr}")
	public ModelAndView printCodeInfo(HttpServletRequest request, @PathVariable String arr) {
		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH+ "printCode");
		PaperParams pp=new PaperParams();
		String[] array=arr.split(",");
		pp.setArray(array);
		List<Paper> papers = paperSerivce.queryPapers(pp);
		modelAndView.addObject("papers", papers);
		return modelAndView;
	}
	
	@RequestMapping(value = "/record/{arr}")
	public ModelAndView record(HttpServletRequest request, @PathVariable String arr) {
		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH+ "registry");
		PaperParams pp=new PaperParams();
		String[] strArr=arr.split(",");
		String[] array=new String[strArr.length];
		
		String[] indexs=new String[strArr.length];
		for(int i=0;i<strArr.length;i++){
			array[i]=strArr[i].split("-")[0];
			indexs[i]=strArr[i].split("-")[1];
		}
		pp.setArray(array);
		List<Paper> papers = paperSerivce.queryPapers(pp);
		for(int i=0;i<papers.size();i++){
			papers.get(i).setPageIndex(Integer.parseInt(indexs[i]));
		}
		modelAndView.addObject("papers", papers);
		return modelAndView;
	}
	
	@RequestMapping(value = "/recordByBatchId/{batchId}")
	public ModelAndView recordByBatchId(HttpServletRequest request, @PathVariable String batchId) {
		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH+ "registry");
		List<Paper> papers=paperSerivce.queryByBatchId(Integer.parseInt(batchId));
		for(int i=0;i<papers.size();i++){
			papers.get(i).setPageIndex(i+1);
		}
		modelAndView.addObject("papers", papers);
		return modelAndView;
	}
	
	@RequestMapping(value = "/batchPaperInfoPrint/{batchId}")
	public ModelAndView printBatchPaperInfo(HttpServletRequest request, @PathVariable String batchId) {
		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH+ "batchPaperInfoPrint");
		PaperBatch pb = paperBatchService.findById(Integer.parseInt(batchId));
		List<Paper> papers = paperSerivce.queryByBatchId(pb.getId());
		modelAndView.addObject("paperBatch", pb);
		modelAndView.addObject("papers", papers);
		modelAndView.addObject("paperSize", papers == null ? 0 : papers.size());
		return modelAndView;
	}

	
//	@RequestMapping("/downExcel")
//	public ModelAndView download(HttpServletRequest request,HttpServletResponse response, PaperParams pp) {
//		ExcelUtil excelUtil=new ExcelUtil();
//		Map<String,Paper> map=new HashMap<String,Paper>();
//		pp.setRows(Integer.MAX_VALUE);
//		List<Paper> paper = paperSerivce.getQYList(pp);
//		for(Paper p:paper){
//			map.put(p.getCode(), p);
//		}
//		try {
//			excelUtil.render(map, request, response);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return new ModelAndView(excelUtil, map);   
//	}
	
	@RequestMapping("/removePapersFromBatch")
	@ResponseBody
	public Map<String, Object> removePapersFromBatch(HttpServletResponse response, int paperBatchId,
			@RequestParam(value = "relatedPaperIds") Integer[] relatedPaperIds) {
		try {
			paperSerivce.removePapersFromBatch(paperBatchId, relatedPaperIds);
			PaperBatch pb=new PaperBatch();
			pb.setUpdatedTime(new Date());
			pb.setId(paperBatchId);
			int rs=updateUpdateTime(pb);
			if(rs>0){
				return this.successResult(null);
			}else{
				return this.failedResult("操作失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return this.failedResult("操作失败！");
		}
	}

	private String getFolderPath(String filePath){
		String[] arr=filePath.split("/");
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<arr.length-1;i++){
			sb.append(arr[i]).append("/");
		}
		return sb.toString();
	}
	
	/**
	 * 2015-11-5 库存统计 wubaizhi
	 * @param pp
	 * @return
	 */
	@RequestMapping("/queryStock")
	@ResponseBody
	public Map<String, Object> queryStock(@RequestBody QueryParams pp) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<Stock> list = paperSerivce.queryStock(pp);
		int total = paperSerivce.queryStockCount(pp);
		result.put("rows", list);
		result.put("total", total);
		return result;
	}
	
	@RequestMapping("/uploadGJCourses/{batchId}")
	public void uploadGJCoursesFile(HttpServletResponse response, @PathVariable Integer batchId,@RequestParam("file") MultipartFile file) throws IOException {
		byte[] bytes;

		JSONObject object=new JSONObject();
        if (!file.isEmpty()) {
             bytes = file.getBytes();
             String errorMsg = usedBatchService.uploadGJCourses(file.getInputStream(), batchId);
            
        	 object.put("result", errorMsg == null);
        	 object.put("message", errorMsg);
        }else{
        	object.put("result", false);
        	object.put("message", "empty file");
        }
		
        this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/getGJCourses/{batchId}")
	@ResponseBody
	public Map<String, Object> getGJCourses(@PathVariable Integer batchId) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<BatchGJCourse> list = gjRepo.findByBatchId(batchId, null);
		
		List<BatchGJCourse> gjCourseRelPapers = dao.getList("getGJCourseRelPapers", batchId);
		for(BatchGJCourse gjCoursePaper : gjCourseRelPapers){
			String relPaperCodes = gjCoursePaper.getRelPaperCodes();
			String[] paperCodesArr = relPaperCodes.split(",");
			if(paperCodesArr.length > 1 && paperCodesArr[1].trim().equals(paperCodesArr[0].trim())){
				relPaperCodes = paperCodesArr[1];
			}
			
			for(BatchGJCourse gjCourse : list){
				if(gjCoursePaper.getCourseCode().equals(gjCourse.getCourseCode()) 
						&& gjCoursePaper.getbCourseCode().equals(gjCourse.getbCourseCode())){
					gjCourse.setRelPaperCodes(relPaperCodes);
					break;
				}
			}
		}
		
		result.put("rows", list);
		result.put("total", list.size());
		return result;
	}
	
}
