package cn.com.qmth.stmms.subjectheader.example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.servlet.ModelAndView;

import cn.com.qmth.stmms.biz.distributpaper.model.FormallyLibrary;
import cn.com.qmth.stmms.biz.distributpaper.model.StandardLibrary;
import cn.com.qmth.stmms.biz.distributpaper.model.TryLibrary;
import cn.com.qmth.stmms.biz.distributpaper.service.FormallyLibraryService;
import cn.com.qmth.stmms.biz.distributpaper.service.StandardLibraryService;
import cn.com.qmth.stmms.biz.distributpaper.service.TryLibraryService;
import cn.com.qmth.stmms.biz.exam.model.SubjectiveBlock;
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.SubjectiveBlockService;
import cn.com.qmth.stmms.biz.subjectheader.model.SubjectHeader;
import cn.com.qmth.stmms.biz.subjectheader.query.StandardLibrarySearchQuery;
import cn.com.qmth.stmms.biz.subjectheader.service.SubjectHeaderService;
import cn.com.qmth.stmms.common.controller.BaseController;
import cn.com.qmth.stmms.common.enums.LibraryStatus;
import cn.com.qmth.stmms.common.session.model.StmmsSession;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller
@RequestMapping("/subjectheader/standard")
public class StandardController extends BaseController {

    @Autowired
    private StandardLibraryService standardLibraryService;

    @Autowired
    private SubjectiveBlockService subjectiveBlockService;

    @Autowired
    private SubjectHeaderService subjectHeaderService;

    @Autowired
    private TryLibraryService tryLibraryService;

    @Autowired
    private FormallyLibraryService formallyLibraryService;

    @Autowired
    private ExamSubjectService examSubjectService;

    @Autowired
    private ExamService examService;

    @Value("${slice.image.server}")
    private String imageServer;

    @RequestMapping
    public ModelAndView index(HttpServletRequest request) {
        StmmsSession session = RequestUtils.getSession(request);
        int examId = Integer.parseInt(session.getParameter("examId"));
        String subjectCode = session.getParameter("subjectCode");

        List<SubjectiveBlock> bList = null;
        bList = subjectiveBlockService.findBlockByExamIdAndSubjectCode(examId, subjectCode);

        ModelAndView view = new ModelAndView("subjectheader/standard/list");
        view.addObject("bList", bList);
        return view;
    }

    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> pageList(HttpServletRequest request, @RequestParam Integer page,
            @RequestParam Integer rows, StandardLibrarySearchQuery query) {
        StmmsSession session = RequestUtils.getSession(request);
        String examId = session.getParameter("examId");
        String subjectCode = session.getParameter("subjectCode");
        SubjectHeader subjectHeader = RequestUtils.getWebUser(request).getSubjectHeader();

        if (query.getBlockId() != null && query.getCount() != null) {
            standardLibraryService.example(Integer.parseInt(examId), subjectCode, query.getBlockId(), query.getCount(),
                    subjectHeader.getId());
        }
        query.setExamId(Integer.parseInt(examId));
        query.setSubjectCode(subjectCode);
        query.setPageNumber(page);
        if (query.getCount() != null) {
            query.setPageSize(query.getCount());
        } else {
            query.setPageSize(rows);
        }
        query = standardLibraryService.findByQuery(query);

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("rows", query.getResult());
        result.put("total", query.getTotalCount());
        return result;
    }

    @RequestMapping(value = "/mark/{id}", method = RequestMethod.GET)
    public ModelAndView mark(HttpServletRequest request, @PathVariable Integer id) {
        StandardLibrary standardLibrary = standardLibraryService.findById(id);
        List<StandardLibrary> list = standardLibraryService.findByExamIdAndBlockId(standardLibrary.getExamId(),
                standardLibrary.getBlockId());

        SubjectHeader subjectHeader = RequestUtils.getWebUser(request).getSubjectHeader();
        ModelAndView view = new ModelAndView("subjectheader/standard/view");
        StmmsSession session = RequestUtils.getSession(request);
        session.setParameter("imageServer", imageServer);
        view.addObject("imageServer", imageServer);

        view.addObject("list", list);
        view.addObject("subjectHeader", subjectHeader);
        view.addObject("standardLibraryId", id);
        return view;
    }

    @RequestMapping("/getlibrary")
    @ResponseBody
    public StandardLibrary getLibrary(HttpServletRequest request, @RequestParam Integer libraryId) {
        StandardLibrary standardLibrary = standardLibraryService.findById(libraryId);
        SubjectiveBlock block = subjectiveBlockService.findBlockById(standardLibrary.getBlockId());
        standardLibrary.setSubjectiveBlock(block);
        standardLibrary.setPictureConfig(block.getPictureConfig());
        // standardLibrary.setPictureUrls(PictureUrlBuilder.getSliceUrls(standardLibrary.getExamId(),
        // standardLibrary.getCampusCode(), block.getSubjectCode(),
        // standardLibrary.getExamNumber(),
        // standardLibrary.getPicCount()));
        return standardLibrary;
    }

    @RequestMapping(value = "/mark", method = RequestMethod.POST)
    public ModelAndView save(HttpServletRequest request, @RequestParam Integer libraryId,
            @RequestParam Integer nextLibraryId, @RequestParam String scoreList, @RequestParam double totalScore) {
        SubjectHeader subjectHeader = RequestUtils.getWebUser(request).getSubjectHeader();
        StandardLibrary standardLibrary = standardLibraryService.findById(libraryId);
        standardLibrary.setScoreList(scoreList);
        standardLibrary.setTotalScore(totalScore);
        standardLibrary.setStatus(LibraryStatus.MARKED);
        standardLibrary.setCreateTime(new Date());
        standardLibrary.setCreator(subjectHeader.getId());
        standardLibraryService.save(standardLibrary);

        // 试评
        List<TryLibrary> tryLibraryList = tryLibraryService.findByBlockIdAndSecretNo(standardLibrary.getBlockId(),
                standardLibrary.getSecretNo());
        for (TryLibrary tryLibrary : tryLibraryList) {
            tryLibrary.setHeaderScore(totalScore);
            tryLibrary.setHeaderScoreList(scoreList);
            tryLibrary.setStatus(LibraryStatus.MARKED);
            tryLibraryService.save(tryLibrary);
        }
        // 正评
        List<FormallyLibrary> formallyLibraryList = formallyLibraryService.findByBlockIdAndSecretNo(
                standardLibrary.getBlockId(), standardLibrary.getSecretNo());
        for (FormallyLibrary formallyLibrary : formallyLibraryList) {
            formallyLibrary.setHeaderScore(totalScore);
            formallyLibrary.setHeaderScoreList(scoreList);
            formallyLibrary.setStatus(LibraryStatus.MARKED);
            formallyLibraryService.save(formallyLibrary);
        }
        ModelAndView view;
        if (nextLibraryId != null) {
            view = new ModelAndView("redirect:/subjectheader/standard/mark/" + nextLibraryId);
        } else {
            view = new ModelAndView("redirect:/subjectheader/standard/mark/" + libraryId);
        }
        return view;
    }
}
