package com.qmth.qrzk.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import 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.RequestMethod;
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.repository.explort.beans.ExportQuestion;
import com.qmth.qrzk.repository.explort.beans.ExportQuestionAttachment;
import com.qmth.qrzk.repository.explort.beans.ExportQuestionOptions;
import com.qmth.qrzk.repository.explort.beans.ExportQuestionSet;
import com.qmth.qrzk.repository.service.query.QueryParams;
import com.qmth.qrzk.repository.user.model.Question;
import com.qmth.qrzk.repository.user.model.QuestionAttachment;
import com.qmth.qrzk.repository.user.model.QuestionImportHistory;
import com.qmth.qrzk.repository.user.model.QuestionOption;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.user.service.IQuestionAttachmentService;
import com.qmth.qrzk.repository.user.service.IQuestionImportHistoryService;
import com.qmth.qrzk.repository.user.service.IQuestionOptionService;
import com.qmth.qrzk.repository.user.service.IQuestionService;
import com.qmth.qrzk.repository.utils.DESCoder;
import com.qmth.qrzk.repository.utils.ParamUtils;
import com.qmth.woxJavaSource.wox.serial.Easy;

/**
 * 文件上传、导入
 * 
 * @author 钟辉
 * 
 */			
@Controller("mulipartFileController")
public class MulipartFileController extends BaseAjaxController {

	@Autowired
	@Qualifier("questionServiceImpl")
	private IQuestionService questionService;
	@Autowired
	@Qualifier("questionOptionServiceImpl")
	private IQuestionOptionService questionOptionService;
	@Autowired
	@Qualifier("questionAttachmentServiceImpl")
	private IQuestionAttachmentService questionAttachmentService;
	@Autowired  
	@Qualifier("questionImportHistoryServiceImpl")
	private IQuestionImportHistoryService questionImportHistoryService;

	/**
	 * 文件上传请求地址
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public void uploadFile(HttpServletRequest request,
			HttpServletResponse response) {
		writeFile(request, "upload/");
	}

	@RequestMapping(value = "/againImportQuestion", method = RequestMethod.POST)
	public void againImportQuestion(HttpServletRequest request,HttpServletResponse response, @RequestBody User user) {
		String realPath=ParamUtils.TemporaryDirPath;
		realPath += "import/";
		String fileName = user.getName().split("/.")[0] + ".xml";
		String file = realPath + fileName;
		// s标示写入的xml文件
		Object obj = Easy.load(file);

		// 解密后得到ExportQuestionSet
		ExportQuestionSet eqset = (ExportQuestionSet) obj;

		ExportQuestion[] eqs = eqset.getQuestions();

//		QuestionImportHistory qih = new QuestionImportHistory(
//				fileName.split("/.")[0] + ".qmq", eqset.getUuid(), eqset.name,
//				new Date(), user.getId(), eqs.length);
		QuestionImportHistory qih = new QuestionImportHistory();
		questionImportHistoryService.saveQuestionImportHistory(qih);

		// 遍历试题集合
		String status="QUESTION_DRAFT";
		List<Question> list=new ArrayList<Question>();
		for (ExportQuestion eq : eqs) {
			byte[] bodyWord = eq.body_word.getBytes();
			byte[] answerWord = eq.answer_word.getBytes();
			// 将具体某一个question得到后插入数据库
			
			Question question = new Question(eq.question_no, eq.course_id,
					eq.type_id, eq.book_id, eq.batch_id,
					eq.estimate_difficulty_code, eq.measured_difficulty_code,
					eq.grade_code, eq.ability_code, eq.chapter, eq.section,
					eq.item, eq.page, eq.score, bodyWord, eq.body,
					eq.body_summary, answerWord, eq.answer, eq.answer_summary,eq.answerSheet,
					status, eq.enable_time, eq.set_time, eq.set_by,
					eq.set_teacher_name, eq.remark, eq.created_time,
					eq.created_by, eq.updated_time, eq.updated_by, 0,
					qih.getId());
			questionService.importQuestion(question);
			list.add(question);
			int questionId=question.getId();
			if (eq.option_count != 0) {
				ExportQuestionOptions[] eqos = eq.pop_option;
				for (ExportQuestionOptions eqo : eqos) {
					int result = -1;
					if (eqo.is_correct_option) {
						result = 0;
					} else {
						result = 1;
					}
					byte[] contentWord=eqo.content_word.getBytes();
					String content="";
					if(eqo.content.equals("")||eqo.content==null){
						content=eqo.summary;
					}else{
						content=eqo.content;
					}
					QuestionOption qo = new QuestionOption(
							questionId, eqo.option_no, result,
							content,contentWord,eqo.summary, eqo.created_time,
							eqo.created_by, eqo.updated_time,
							eqo.updated_by);
					questionOptionService.saveQuestionOption(qo);
				}
			}

			if (eq.pop_attachment_count != 0) {
				ExportQuestionAttachment[] eqas = eq.pop_attachment;
				for (ExportQuestionAttachment eqa : eqas) {
					byte[] content = eqa.content.getBytes();
					QuestionAttachment qa = new QuestionAttachment(
							questionId, eqa.parent_type, eqa.extension,
							eqa.name, eqa.size, eqa.check_code, content,
							eqa.created_time, eqa.created_by);
					questionAttachmentService.saveAttachment(qa);
				}
			}
		}
		// 导入后删除该文件
		File ff = new File(file);
		if(ff.exists()){
			ff.delete();
		}

		
		
		//导入的题目创建索引
//		new AppendLuceneIndex().appendListIndex(list);
		
		JSONObject object = new JSONObject();
		object.put("uuid", eqset.getUuid());
		object.put("type", "success");
		this.outJsonString(response, object.toString());
	}

	@RequestMapping("/historylist")
	public ModelAndView historylist() {
		ModelAndView model = new ModelAndView("/question/importHistory");
		return model;
	}

	@RequestMapping("/queryHistorylist")
	@ResponseBody
	public Map<String, Object> queryHistorylist(QueryParams params) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<QuestionImportHistory> rows = questionImportHistoryService
				.queryHistories(params);
		int total = questionImportHistoryService.getCount(params);
		result.put("rows", rows);
		result.put("total", total);
		return result;
	}

	/**
	 * 导入试题请求地址,导入后的数据进行逻辑处理存入数据库
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/importQuestion", method = RequestMethod.POST)
	public void importQuestion(HttpServletRequest request,
			HttpServletResponse response, int importBy) {
		writeFile(request, "import/");
		// 写入服务器文件后就存储到数据库、然后删除
		
		String realPath=ParamUtils.TemporaryDirPath;
		realPath += "import/";
		File f = new File(realPath);
		String[] ss = f.list();
		for (String s : ss) {
			// s标示写入的xml文件
			Object obj = Easy.load(realPath + s);

			// 解密后得到ExportQuestionSet
			ExportQuestionSet eqset = (ExportQuestionSet) obj;
			int count = questionImportHistoryService
					.findByUUId(eqset.getUuid());
			if (count > 0) {
				JSONObject object = new JSONObject();
				object.put("uuid", eqset.getUuid());
				object.put("type", "fail");
				this.outJsonString(response, object.toString());
			} else {
				ExportQuestion[] eqs = eqset.getQuestions();

//				QuestionImportHistory qih = new QuestionImportHistory(
//						s.split("/.")[0] + ".qmq", eqset.getUuid(),
//						eqset.name, new Date(), importBy, eqs.length);
				QuestionImportHistory qih = new QuestionImportHistory();
				questionImportHistoryService.saveQuestionImportHistory(qih);

				String status="QUESTION_DRAFT";
				
				List<Question> list=new ArrayList<Question>();
				// 遍历试题集合
				for (ExportQuestion eq : eqs) {
					byte[] bodyWord = eq.body_word.getBytes();
					byte[] answerWord = eq.answer_word.getBytes();
					// 将具体某一个question得到后插入数据库
					Question question = new Question(eq.question_no,
							eq.course_id, eq.type_id, eq.book_id, eq.batch_id,
							eq.estimate_difficulty_code,
							eq.measured_difficulty_code, eq.grade_code,
							eq.ability_code, eq.chapter, eq.section, eq.item,
							eq.page, eq.score, bodyWord, eq.body,
							eq.body_summary, answerWord, eq.answer,
							eq.answer_summary, eq.answerSheet,status, eq.enable_time,
							eq.set_time, eq.set_by, eq.set_teacher_name,
							eq.remark, eq.created_time, eq.created_by,
							eq.updated_time, eq.updated_by, 0, qih.getId());
					questionService.importQuestion(question);
					
					
					list.add(question);
					int questionId=question.getId();
					if (eq.option_count != 0) {
						ExportQuestionOptions[] eqos = eq.pop_option;
						for (ExportQuestionOptions eqo : eqos) {
							int result = -1;
							if (eqo.is_correct_option) {
								result = 0;
							} else {
								result = 1;
							}
							byte[] contentWord=eqo.content_word.getBytes();
							String content="";
							if(eqo.content.equals("")||eqo.content==null){
								content=eqo.summary;
							}else{
								content=eqo.content;
							}
							QuestionOption qo = new QuestionOption(
									questionId, eqo.option_no, result,
									content,contentWord,eqo.summary, eqo.created_time,
									eqo.created_by, eqo.updated_time,
									eqo.updated_by);
							questionOptionService.saveQuestionOption(qo);
						}
					}

					if (eq.pop_attachment_count != 0) {
						ExportQuestionAttachment[] eqas = eq.pop_attachment;
						for (ExportQuestionAttachment eqa : eqas) {
							byte[] content = eqa.content.getBytes();
							QuestionAttachment qa = new QuestionAttachment(
									questionId, eqa.parent_type,
									eqa.extension, eqa.name, eqa.size,
									eqa.check_code, content, eqa.created_time,
									eqa.created_by);
							questionAttachmentService.saveAttachment(qa);
						}
					}
				}

				File ff = new File(realPath + s);
				ff.delete();

				
//				new AppendLuceneIndex().appendListIndex(list);
				JSONObject object = new JSONObject();
				object.put("uuid", eqset.getUuid());
				object.put("type", "success");
				this.outJsonString(response, object.toString());
			}
		}
	}

	@RequestMapping(value = "/downLoadFile/{id}", method = RequestMethod.GET)
	public void downLoadFile(HttpServletRequest request,HttpServletResponse response, @PathVariable int id) {
		QuestionAttachment qa = questionAttachmentService.downLoadById(id);
		byte[] bytes = qa.getContent();

		OutputStream os = null;
		try {
			os = response.getOutputStream();
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition", "attachment; filename="
					+ new String(qa.getName().getBytes("GB18030"), "ISO8859-1"));
			os.write(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(os!=null){
				try {
					os.flush();
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}


	/**
	 * 写入服务器临时目录 一边后续处理
	 * 
	 * @param request
	 * @param path
	 *            是上传文件 还是导入的文件
	 */
	public void writeFile(HttpServletRequest request, String path) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
				.getFile("Filedata");
		String realPath=ParamUtils.TemporaryDirPath;
		realPath += path;
		File ff = new File(realPath);
		if (!ff.exists()) {
			ff.mkdirs();
		}

		InputStream stream = null;
		try {
			stream = file.getInputStream();
			String fileName = file.getOriginalFilename();
			fileName = new String(fileName.getBytes(), "utf-8");
			if (path.contains("import")) {
				byte[] buffer = new byte[stream.available()];
				stream.read(buffer);
				byte[] bytes = DESCoder.desDecrypt(buffer);
				
				List<Byte> ls=new ArrayList<Byte>();
				for(int i=0;i<bytes.length;i++){
					if(bytes[i]!=0){
						ls.add(bytes[i]);
					}
				}
				byte[] nByte=new byte[ls.size()];
				for(int i=0;i<ls.size();i++){
					nByte[i]=ls.get(i);
				}
				
				FileOutputStream outStream = new FileOutputStream(realPath
						+ (fileName.split("/.")[0] + ".xml"));
				outStream.write(nByte);
				outStream.flush();
				outStream.close();
				stream.close();

			} else {
				String fileNameFull = realPath + fileName;
				OutputStream bos = new FileOutputStream(fileNameFull);
				int bytesRead = 0;
				byte[] buffer = new byte[2048];
				while ((bytesRead = stream.read(buffer, 0, 2048)) != -1) {
					bos.write(buffer, 0, bytesRead);
				}
				bos.close();
				stream.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 上传 导入完成后删除临时文件
	 * 
	 * @param request
	 * @param response
	 * @param fileName
	 */
	@RequestMapping("/deleteFile")
	public void deleteFile(HttpServletRequest request,
			HttpServletResponse response, @RequestBody String fileName) {
		
		String realPath=ParamUtils.TemporaryDirPath;
		if (fileName.contains(".qmq"))
			realPath += "import/";
		else
			realPath += "upload/";
		JSONObject obj = JSONObject.fromObject(fileName);
		String name = obj.getString("name");
		File file = new File(realPath + name);
		if (file.exists()) {
			file.delete();
		}
	}
}
