package cn.com.qmth.stmms.admin.exam;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

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

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.com.qmth.stmms.biz.exam.bean.SubjectSplit;
import cn.com.qmth.stmms.biz.exam.model.Exam;
import cn.com.qmth.stmms.biz.exam.model.ExamSubject;
import cn.com.qmth.stmms.biz.exam.service.ExamService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.exam.service.query.ExamSubjectSearchQuery;
import cn.com.qmth.stmms.biz.mark.model.PictureConfigItem;
import cn.com.qmth.stmms.biz.school.model.School;
import cn.com.qmth.stmms.biz.school.service.SchoolService;
import cn.com.qmth.stmms.common.annotation.Logging;
import cn.com.qmth.stmms.common.annotation.RoleRequire;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.ExamStatus;
import cn.com.qmth.stmms.common.enums.LogType;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.utils.ExportExcel;
import cn.com.qmth.stmms.common.utils.ImportExcel;
import cn.com.qmth.stmms.common.utils.RequestUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

@Controller
@RequestMapping("/admin/exam/subject")
public class SubjectController extends BaseExamController {
	private static Logger log = LoggerFactory.getLogger(SubjectController.class);
	@Autowired
	private ExamSubjectService subjectService;

	@Autowired
	private ExamService examService;
	@Autowired
	private SchoolService schoolService;
	@Value("${file.temp}")
	private String tempFile;

	@RequestMapping("/list")
	@ResponseBody
	public JSONArray list(HttpServletRequest request, @RequestParam Integer examId) {
		List<ExamSubject> list = subjectService.list(examId);
		JSONArray array = new JSONArray();
		for (ExamSubject subject : list) {
			JSONObject obj = new JSONObject();
			obj.accumulate("code", subject.getCode());
			obj.accumulate("name", subject.getName());
			obj.accumulate("level", StringUtils.trimToEmpty(subject.getLevel()));
			obj.accumulate("category", StringUtils.trimToEmpty(subject.getCategory()));
			array.add(obj);
		}
		return array;
	}

	@RequestMapping("/edit")
	@RoleRequire(Role.SCHOOL_ADMIN)
	public String edit(HttpServletRequest request, @RequestParam String code, Model model,
			RedirectAttributes redirectAttributes, ExamSubjectSearchQuery query,
			@RequestParam(required = false) String queryCode, @RequestParam(required = false) Boolean upload) {
		ExamSubject subject = subjectService.find(getSessionExamId(request), code);
		if (subject == null) {
			addMessage(redirectAttributes, "科目代码有误，科目不存在");
			return "redirect:/admin/exam/paper";
		}
		model.addAttribute("subject", subject);
		model.addAttribute("pictureConfig", buildPictureConfig(subject.getSheetConfig()));
		model.addAttribute("passScore", subject.getPassScore());
		model.addAttribute("excellentScore", subject.getExcellentScore());
		Exam exam = examService.findById(subject.getExamId());
		model.addAttribute("examType", exam.getType());
		query.setCode(queryCode);
		model.addAttribute("query", query);
		model.addAttribute("upload", upload);
		return "modules/exam/subjectEdit";
	}

	@Logging(menu = "科目设置", type = LogType.UPDATE)
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@RoleRequire(Role.SCHOOL_ADMIN)
	public String save(RedirectAttributes redirectAttributes, HttpServletRequest request, ExamSubject subject,
			Model model, @RequestParam String picList, @RequestParam(required = false) Double passScore,
			@RequestParam(required = false) Double excellentScore, ExamSubjectSearchQuery query,
			@RequestParam(required = false) String queryCode, @RequestParam(required = false) Boolean upload) {
		String u = upload == null ? "" : upload.toString();
		String t = query.getTotalScoreNotEqual() == null ? "" : query.getTotalScoreNotEqual().toString();
		String url = "redirect:/admin/exam/paper?code=" + queryCode + "&pageNumber=" + query.getPageNumber()
				+ "&category=" + query.getCategory() + "&level=" + query.getLevel() + "&upload=" + u
				+ "&totalScoreNotEqual=" + t;
		ExamSubject previous = subjectService.find(getSessionExamId(request), subject.getCode());
		if (previous == null) {
			addMessage(redirectAttributes, "科目代码有误，科目不存在");
			return url;
		}
		if (previous != null && StringUtils.isNotBlank(picList)) {
			String sheetConfig = StringEscapeUtils.unescapeHtml(picList);
			JSONArray array = JSONArray.fromObject(sheetConfig);
			List<PictureConfigItem> list = JSONArray.toList(array, new PictureConfigItem(), new JsonConfig());
			previous.setSheetConfig(list == null ? null : StringUtils.join(list, PictureConfigItem.DB_ITEM_JOINER));
		}
		JSONObject sasConfig = new JSONObject();
		sasConfig.accumulate("passScore", passScore);
		sasConfig.accumulate("excellentScore", excellentScore);
		previous.setSasConfig(sasConfig.toString());
		previous.setEnableSplit(subject.getEnableSplit());
		previous.setAutoScroll(subject.getAutoScroll());
		previous.setDisplayQuestionName(
				subject.getDisplayQuestionName() == null ? false : subject.getDisplayQuestionName());
		subjectService.save(previous);
		model.addAttribute("message", "修改成功");

		return url;
	}

	@RoleRequire({ Role.SYS_ADMIN })
	@RequestMapping(value = "split")
	public String split(Model model, HttpServletRequest request, @RequestParam Integer schoolId) {
		School s = schoolService.findById(schoolId);
		model.addAttribute("schoolId", schoolId);
		model.addAttribute("schoolName", s.getName());
		List<Exam> examList = examService.findBySchoolId(schoolId);
		if (examList != null && examList.size() > 0) {
			List<Exam> tem = examList.stream().filter(e -> !ExamStatus.FINISH.equals(e.getStatus()))
					.collect(Collectors.toList());
			model.addAttribute("examList", tem);
		} else {
			model.addAttribute("examList", examList);
		}
		return "modules/exam/subjectSplit";
	}

	@RoleRequire({ Role.SYS_ADMIN })
	@RequestMapping(value = "split/save")
	public String splitSave(RedirectAttributes redirectAttributes, Model model, HttpServletRequest request,
			MultipartFile file, @RequestParam Integer schoolId, @RequestParam Integer examId) {
		try {
			School s = schoolService.findById(schoolId);
			model.addAttribute("examId", examId);
			model.addAttribute("schoolId", schoolId);
			model.addAttribute("schoolName", s.getName());
			List<Exam> examList = examService.findBySchoolId(schoolId);
			model.addAttribute("examList", examList);
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<SubjectSplit> list = ei.getDataList(SubjectSplit.class);
			String errMsg = subjectService.split(schoolId, examId, list);
			if (StringUtils.isBlank(errMsg)) {
				model.addAttribute("message", "已成功导入");
			} else {
				WebUser wu = RequestUtils.getWebUser(request);
				File errFile = new File(getSubjectSplitErrFile(wu.getId()));
				errFile.getParentFile().mkdirs();
				if (errFile.exists()) {
					errFile.delete();
				}
				FileUtils.write(errFile, errMsg, "utf-8");
				model.addAttribute("errmsgFile", true);
				model.addAttribute("errmsg", "导入信息有误，请查看error.txt文件");
			}
		} catch (Exception e) {
			log.error("导入失败", e);
			model.addAttribute("errmsg", "导入失败：" + e.getMessage());
		}
		return "modules/exam/subjectSplit";
	}

	@RequestMapping(value = "split/err", method = RequestMethod.GET)
	public void getImportTemplate(HttpServletRequest request, HttpServletResponse response) {
		WebUser wu = RequestUtils.getWebUser(request);
		File file = new File(getSubjectSplitErrFile(wu.getId()));
		exportFile("error.txt", file, response);
	}

	private String getSubjectSplitErrFile(Integer userId) {
		String path = tempFile + File.separator + "subject-split-err" + File.separator + userId + File.separator + "error.txt";
		return path;
	}

	@RequestMapping(value = "split/template")
	public String splitTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			List<SubjectSplit> list = new ArrayList<>();
			list.add(new SubjectSplit());
			new ExportExcel("科目拆分数据", SubjectSplit.class, 2).setDataList(list).write(response, "科目拆分导入模板.xlsx")
					.dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:/admin/exam/subject/split";
	}
}
