package com.qmth.qrzk.web.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
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.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.qmth.qrzk.dbf.DbfImportException;
import com.qmth.qrzk.dbf.ReadDBF;
import com.qmth.qrzk.paper.vo.UseBatchStock;
import com.qmth.qrzk.repository.service.query.DbfPaperInfoQueryParams;
import com.qmth.qrzk.repository.service.query.PaperParams;
import com.qmth.qrzk.repository.user.model.DbfPaperInfo;
import com.qmth.qrzk.repository.user.model.Paper;
import com.qmth.qrzk.repository.user.model.PaperBatch;
import com.qmth.qrzk.repository.user.service.IPaperBatchService;
import com.qmth.qrzk.repository.user.service.impl.DbfPaperInfoServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.PaperServiceImpl;
import com.qmth.qrzk.repository.utils.excel.ExcelRepertoryUtil;

@Controller
@RequestMapping("/dbfPaperInfo")
public class DbfPaperInfoController  extends BaseAjaxController {
	
	@Autowired
	private DbfPaperInfoServiceImpl dbfPaperInfoSerivce;
	
	@Autowired
	private PaperServiceImpl paperSerivce;
	
	@Autowired
	@Qualifier("paperBatchServiceImpl")
	private IPaperBatchService paperBatchService;
	
	@RequestMapping("/DBFUpload/{batchId}")
	public void uploadDBFFile(HttpServletRequest request,HttpServletResponse response, @PathVariable int batchId) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
		InputStream stream = null;
		try {
			stream = file.getInputStream();

			// 调用解析DBF格式文件
			List<DbfPaperInfo> ls = ReadDBF.readDbfPaperInfo(stream);
			dbfPaperInfoSerivce.addDbfPaperInfos(ls, batchId);
			
		}catch(DbfImportException e){
			this.outJsonString(response, e.getMessage());
		}catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		PaperBatch pb=new PaperBatch();
		pb.setUpdatedTime(new Date());
		pb.setId(batchId);
		int rs=updateUpdateTime(pb);
		if(rs>0){
			this.outJsonString(response, "success");
		}else{
			this.outJsonString(response, "fail");
		}
	}
	
	
	private int updateUpdateTime(PaperBatch pb){
		return paperBatchService.updateTime(pb);
	}
	@RequestMapping("/queryDbfPaperInfo/{batchId}")
	@ResponseBody
	public Map<String, Object> queryDbfPaperInfo(@PathVariable int batchId, @RequestBody DbfPaperInfoQueryParams params) {
		Map<String,Object> result = new HashMap<String, Object>();
		params.setPaperBatchId(batchId);
		List<DbfPaperInfo> rows = dbfPaperInfoSerivce.queryDbfPaperInfo(params);
		if(rows.size()>0){
			result.put("rows", rows);
			result.put("total", params.getTotalNum());
		}else{
			result.put("rows", "");
			result.put("total", 0);
		}
		
		return result;
	}
	
	
	@RequestMapping("/autoMatchPapers/{batchId}")
	@ResponseBody
	public Map<String, Object> autoMatchPapers(HttpServletResponse response, @PathVariable int batchId) {
		try{
			PaperBatch paperBatch = paperBatchService.findTypeById(batchId);
			Map<String, Object> result = dbfPaperInfoSerivce.autoMatchPapers(paperBatch);
			if((Boolean)result.get("success") == true){
				PaperBatch pb=new PaperBatch();
				pb.setUpdatedTime(new Date());
				pb.setId(batchId);
				updateUpdateTime(pb);
			}
			return result;
		}catch(Exception e){
			return this.failedResult("操作失败！");
		}
	}
	
	
	@RequestMapping("/queryRelatedPapers")
	@ResponseBody
	public Map<String,Object> queryRelatedPapers(HttpServletResponse response, Integer dbfPaperInfoId) {
		Map<String,Object> result = new HashMap<String, Object>();
		
		if(dbfPaperInfoId != null){
			List<Paper> rows = dbfPaperInfoSerivce.queryRelatedPapers(dbfPaperInfoId);
			result.put("rows", rows);
			result.put("total", rows.size());
		}else{
			result.put("rows", "");
			result.put("total", 0);
		}
		
		return result;
	}
	
	@RequestMapping("/searchRelatedPapers")
	@ResponseBody
	public Map<String,Object> searchRelatedPapers(HttpServletResponse response, DbfPaperInfoQueryParams params) {
		Map<String,Object> result = new HashMap<String, Object>();
		
		if(null == params.getDbfPaperInfoId()){
			result.put("rows", "");
			result.put("total", 0);
			return result;
		}
		
		List<Paper> rows = dbfPaperInfoSerivce.searchRelatedPapers(params);
		result.put("rows", rows);
		result.put("total", rows.size());
		
		return result;
	}
	
	@RequestMapping("/manualAddMatchedPapers")
	@ResponseBody
	public Map<String,Object> manualAddMatchedPapers(HttpServletResponse response, int dbfPaperInfoId, @RequestParam(value = "relatedPaperIds[]") Integer[] relatedPaperIds) {
		try{
			dbfPaperInfoSerivce.manualAddMatchedPapers(dbfPaperInfoId, relatedPaperIds);
			return this.successResult(null);
		}catch(Exception e){
			return this.failedResult("操作失败！");
		}
	}
	
	@RequestMapping("/removePaperFromUsedBatch")
	@ResponseBody
	public Map<String,Object> removePaperFromUsedBatch(HttpServletResponse response, int dbfPaperInfoId, @RequestParam(value = "relatedPaperIds") Integer[] relatedPaperIds) {
		try{
			dbfPaperInfoSerivce.removePaperFromUsedBatch(dbfPaperInfoId, relatedPaperIds);
			return this.successResult(null);
		}catch(Exception e){
			return this.failedResult("操作失败！");
		}
	}
	
	@RequestMapping("/updateDF")
	public void updateDF(HttpServletResponse response, @RequestBody DbfPaperInfo info) {
		JSONObject object = new JSONObject();
		try{
			dbfPaperInfoSerivce.updateDbfPaperInfo(info);
			object.put("type", "success");
		}catch(Exception e){
			object.put("type", "fail");
		}
		this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/queryUseBatchStock")
	@ResponseBody
	public Map<String, Object> queryUseBatchStock(@RequestBody PaperParams pp) {
		Map<String,Object> result = new HashMap<String, Object>();
		
		List<UseBatchStock> rows = dbfPaperInfoSerivce.queryUseBatchStock(pp);
		int total = dbfPaperInfoSerivce.queryUseBatchStockCount(pp);
		result.put("rows", rows);
		result.put("total", total);
		
		return result;
	}
	
	@RequestMapping("/downloadUseBatchStockToExcel/{batchId}")
	public ModelAndView downUseBatchStockToExcel(HttpServletRequest request,HttpServletResponse response, @PathVariable int batchId) {
		PaperParams pp = new PaperParams();
		pp.setBatchId(batchId);
		
		List<UseBatchStock> rows = dbfPaperInfoSerivce.queryAllUseBatchStock(pp);
		Map<String, UseBatchStock> map=new HashMap<String, UseBatchStock>();
		for(int i = 0; i < rows.size(); i++){
			map.put(String.valueOf(i), rows.get(i));
		}
			
		ExcelRepertoryUtil util=new ExcelRepertoryUtil();
		try {
			util.render(map, request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ModelAndView(util, map);   
	}
	
	@RequestMapping("/downExcelTotalRepertory")
	public ModelAndView downExcelRepertory(HttpServletRequest request,HttpServletResponse response,PaperParams pp) {
		pp.setRows(Integer.MAX_VALUE);
		
		List<Paper> list = paperSerivce.queryTotal(pp);
		for(Paper paper:list){
			int total=paperSerivce.queryRepertory(paper);
			paper.setResidueFormal(total);
		}
		
		Map<String,Paper> map=new HashMap<String,Paper>();
		int i=0;
		for(Paper r:list){
			map.put(String.valueOf(i), r);
			i++;
		}
		
		ExcelRepertoryUtil util=new ExcelRepertoryUtil();
		try {
			util.render(map, request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ModelAndView(util, map);
	}
	
//	@RequestMapping("/downDBFRepertory")
//	public void downDBFRepertory(HttpServletRequest request,HttpServletResponse response,DbfPaperInfoQueryParams params) {
//		params.setRows(Integer.MAX_VALUE);
//		List<Paper> list=dbfPaperInfoSerivce.getPaperInfo(params);
//		List<Repertory> ls=new ArrayList<Repertory>();
//		commonMethod(ls,list);
//		
//		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=formatter.format(new Date()) + ".DBF";
//		try {
//			WriteDBF.writeToDBFInfo(ls, 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("/removeDbfPaperInfoFromBatch")
	@ResponseBody
	public Map<String,Object> removeDbfPaperInfoFromBatch(HttpServletResponse response, @RequestParam(value = "dbfPaperInfoIds") Integer[] relatedPaperIds, boolean isRemoveRelatedPapers) {
		try{
			dbfPaperInfoSerivce.removeDbfPaperInfoFromBatch(relatedPaperIds, isRemoveRelatedPapers);
			return this.successResult(null);
		}catch(Exception e){
			e.printStackTrace();
			return this.failedResult("操作失败！");
		}
	}
	
	
	
}
