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

import java.util.LinkedList;
import java.util.List;

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

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.com.qmth.stmms.biz.exam.model.ExamSubject;
import cn.com.qmth.stmms.biz.exam.query.SubjectHeaderSearchQuery;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.subjectheader.model.SubjectHeader;
import cn.com.qmth.stmms.biz.subjectheader.service.SubjectHeaderService;
import cn.com.qmth.stmms.common.utils.DateUtils;
import cn.com.qmth.stmms.common.utils.ExportExcel;

@Controller("subjectHeaderController")
@RequestMapping("/admin/exam-param/header")
public class SubjectHeaderController extends BaseParameterController {

    @Autowired
    private SubjectHeaderService headerService;

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    protected Validator validator;

    @RequestMapping
    public String list(HttpServletRequest request, Model model, SubjectHeaderSearchQuery query) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            query.setExamId(examId);
            query.orderByLoginName();
            query = headerService.findByQuery(query);
            if (query.getCurrentCount() > 0) {
                for (SubjectHeader header : query.getResult()) {
                    header.setSubject(subjectService.find(header.getExamId(), header.getSubjectCode()));
                }
            }
            model.addAttribute("query", query);
            model.addAttribute("subjectList", getExamSubject(examId));
            return "modules/exam/param/headerList";
        } else {
            return "redirect:/admin/exam/list";
        }
    }

    @RequestMapping("/batch-create")
    public String createInit(Model model, HttpServletRequest request) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            return "modules/exam/param/headerCreate";
        } else {
            return "redirect:/admin/exam/list";
        }
    }

    @RequestMapping(value = "/batch-create", method = RequestMethod.POST)
    public ModelAndView create(HttpServletRequest request, @RequestParam Integer count, @RequestParam String password) {
        int examId = getSessionExamId(request);
        ModelAndView view = new ModelAndView("redirect:/admin/exam-param/header");
        if (examId > 0 && count > 0 && StringUtils.isNotBlank(password)) {
            List<ExamSubject> subjectList = subjectService.list(examId);
            for (ExamSubject subject : subjectList) {
                headerService.batchCreate(subject, count, password);
            }
        }
        return view;
    }

    @RequestMapping(value = "/delete")
    public String delete(@RequestParam Integer id) {
        headerService.deleteById(id);
        return "redirect:/admin/exam-param/header?repage";
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject deleteMarker(@RequestParam Integer id) {
        SubjectHeader header = headerService.findById(id);
        JSONObject obj = new JSONObject();
        if (header != null) {
            headerService.deleteById(id);
            obj.accumulate("success", true);
        } else {
            obj.accumulate("success", false);
            obj.accumulate("message", "该评卷员不存在");
        }
        return obj;
    }

    @RequestMapping(value = "export", method = RequestMethod.POST)
    public String exportFile(SubjectHeaderSearchQuery query, HttpServletRequest request, HttpServletResponse response,
            RedirectAttributes redirectAttributes) {
        int examId = getSessionExamId(request);
        query.setExamId(examId);
        try {
            String fileName = "科组长数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";

            query.setPageNumber(1);
            query.setPageSize(Integer.MAX_VALUE);
            query.orderByLoginName();
            query = headerService.findByQuery(query);
            new ExportExcel("科组长数据", SubjectHeader.class).setDataList(query.getResult()).write(response, fileName)
                    .dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出科组长失败！失败信息：" + e.getMessage());
        }
        return "redirect:/admin/exam-param/header?repage";
    }

    @RequestMapping(value = "/multi-delete", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject multiDelete(@RequestParam Integer[] headerIds) {
        JSONObject obj = new JSONObject();
        List<Integer> success = new LinkedList<Integer>();
        if (headerIds != null) {
            for (int id : headerIds) {
                SubjectHeader header = headerService.findById(id);
                if (header != null) {
                    if (isMarking(header.getExamId(), header.getSubjectCode())) {
                        obj.accumulate("success", false);
                        obj.accumulate("message", "评卷已开始，不能进行修改");
                    } else {
                        headerService.deleteById(id);
                        obj.accumulate("success", true);
                        success.add(id);
                    }
                }
            }
        }
        obj.accumulate("count", success.size());
        obj.accumulate("ids", StringUtils.join(success, ","));
        return obj;
    }

}
