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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.servlet.mvc.support.RedirectAttributes;

import cn.com.qmth.stmms.admin.exam.parameter.BaseParameterController;
import cn.com.qmth.stmms.admin.vo.StatisticsVO;
import cn.com.qmth.stmms.biz.exam.model.ExamSubject;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.exam.service.query.ExamSubjectSearchQuery;
import cn.com.qmth.stmms.common.utils.DateUtils;
import cn.com.qmth.stmms.common.utils.ExportExcel;

/**
 * 分段统计
 */
@Controller
@RequestMapping("/admin/exam/statistics")
public class StatisticsController extends BaseParameterController {

    protected static Logger log = LoggerFactory.getLogger(StatisticsController.class);

    @Autowired
    private ExamSubjectService subjectService;
    @Autowired
    private ExamStudentService examStudentService;

    @RequestMapping
    public String list(Model model, HttpServletRequest request, ExamSubjectSearchQuery query,
    		@RequestParam(required = false) Boolean upload,@RequestParam(required = false) Boolean breach) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            query.setExamId(examId);
            query = subjectService.findByQuery(query);
            List<StatisticsVO> statisticsVOs = new ArrayList<StatisticsVO>(); 
            for (ExamSubject subject : query.getResult()) {
            	StatisticsVO vo = new StatisticsVO(subject);
            	vo = getStatisticsInfo(vo,upload,breach);
            	statisticsVOs.add(vo);
			}
            model.addAttribute("statisticsVOs", statisticsVOs);
            model.addAttribute("query", query);
            model.addAttribute("upload", upload);
            model.addAttribute("breach", breach);
            model.addAttribute("subjectList", getExamSubject(examId));
            model.addAttribute("levelList", subjectService.listLevel(examId));
            model.addAttribute("categoryList", subjectService.listCategory(examId));
            return "modules/exam/statisticsInfo";
        } else {
            return "redirect:/admin/exam/list";
        }
    }

	private StatisticsVO getStatisticsInfo(StatisticsVO vo,Boolean upload,Boolean breach) {
		List<Object[]> list = null;
        /**
         *   没有违纪或者缺考的查询条件
         * 1.先查询不违纪和不缺考的情况下每个阶段分数个数
         * 2.然后分别查询违纪和缺考的记录个数之和减去同时是违纪和缺考的记录个数，并其个数归属到0-49分数段中
         *   查询条件：不缺考（上传 不缺考）
         * 1.先查询不缺考和不违纪的情况下每个阶段分数个数
         * 2.然后查询不缺考和违纪的记录个数，并其个数归属到0-49分数段中
         *   查询条件：不违纪
         * 1.先查询不违纪和不缺考的情况下每个阶段分数个数
         * 2.然后查询不违纪和缺考的记录个数，并将其个数归属到0-49分数段中
         *   查询条件：不违纪和不缺考
         * 1.直接查出不违纪和不缺考的情况下每个阶段分数个数
         */
        list = examStudentService.statisticsByAbsentAndBreach(vo.getExamId(),vo.getCode(),true,false,false);
        if(upload == null && breach == null){
            vo.setStudentCount(examStudentService.countByExamIdAndSubjectCode(vo.getExamId(), vo.getCode()));
            //缺考的个数
            long absentCount = examStudentService.countByAbsentAndBreach(vo.getExamId(),vo.getCode(),true,null);
            //违纪的个数
            long breachCount = examStudentService.countByAbsentAndBreach(vo.getExamId(),vo.getCode(),null,true);
            //即使违纪也是缺考的个数
            long absentAndBreachCount = examStudentService.countByAbsentAndBreach(vo.getExamId(),vo.getCode(),true,true);
            vo.setCount0_49((long) (list.get(0)[0]==null?0L:list.get(0)[0])+absentCount+breachCount-absentAndBreachCount);
            vo.setCount0_60((long) (list.get(0)[6]==null?0L:list.get(0)[6])+absentCount+breachCount-absentAndBreachCount);
        }else if(upload != null && breach == null){
            vo.setStudentCount(examStudentService.countByExamIdAndSubjectCode(vo.getExamId(), vo.getCode(), upload,false));
            //不缺考和违纪的记录个数
            long noAbsentAndBreachCount = examStudentService.countByNoAbsentAndBreach(vo.getExamId(),vo.getCode(),upload,false,true);
            vo.setCount0_49((long) (list.get(0)[0]==null?0L:list.get(0)[0])+noAbsentAndBreachCount);
            vo.setCount0_60((long) (list.get(0)[6]==null?0L:list.get(0)[6])+noAbsentAndBreachCount);
        }else if(upload == null && breach != null){
            vo.setStudentCount(examStudentService.countByAbsentAndBreach(vo.getExamId(),vo.getCode(),null,false));
            //不违纪和缺考的记录个数
            long noBreachAndAbsent = examStudentService.countByAbsentAndBreach(vo.getExamId(),vo.getCode(),true,false);
            vo.setCount0_49((long) (list.get(0)[0]==null?0L:list.get(0)[0])+noBreachAndAbsent);
            vo.setCount0_60((long) (list.get(0)[6]==null?0L:list.get(0)[6])+noBreachAndAbsent);
        }else {
            vo.setStudentCount(examStudentService.countByNoAbsentAndBreach(vo.getExamId(),vo.getCode(),true,false,false));
            vo.setCount0_49((long) (list.get(0)[0]==null?0L:list.get(0)[0]));
            vo.setCount0_60((long) (list.get(0)[6]==null?0L:list.get(0)[6]));
        }
		vo.setCount50_59((long) (list.get(0)[1]==null?0L:list.get(0)[1]));
		vo.setCount60_69((long) (list.get(0)[2]==null?0L:list.get(0)[2]));
		vo.setCount70_79((long) (list.get(0)[3]==null?0L:list.get(0)[3]));
		vo.setCount80_89((long) (list.get(0)[4]==null?0L:list.get(0)[4]));
		vo.setCount90_100((long) (list.get(0)[5]==null?0L:list.get(0)[5]));
		vo.setCount60_100((long) (list.get(0)[7]==null?0L:list.get(0)[7]));
		if(vo.getStudentCount()!=0){
			vo.setPercent0_49(new BigDecimal(vo.getCount0_49()*100.0/vo.getStudentCount()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
			vo.setPercent50_59(new BigDecimal(vo.getCount50_59()*100.0/vo.getStudentCount()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
			vo.setPercent60_69(new BigDecimal(vo.getCount60_69()*100.0/vo.getStudentCount()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
			vo.setPercent70_79(new BigDecimal(vo.getCount70_79()*100.0/vo.getStudentCount()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
			vo.setPercent80_89(new BigDecimal(vo.getCount80_89()*100.0/vo.getStudentCount()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
			vo.setPercent90_100(new BigDecimal(vo.getCount90_100()*100.0/vo.getStudentCount()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
			vo.setPercent0_60(new BigDecimal(vo.getCount0_60()*100.0/vo.getStudentCount()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
			vo.setPercent60_100(new BigDecimal(vo.getCount60_100()*100.0/vo.getStudentCount()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
		}
		return vo;
	}

	@RequestMapping(value = "/export", method = RequestMethod.POST)
	public String exportFile(ExamSubjectSearchQuery query,
			@RequestParam(required = false) Boolean upload,@RequestParam(required = false) Boolean breach,
			HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		int examId = getSessionExamId(request);
		try {
			query.setPageNumber(1);
			query.setPageSize(Integer.MAX_VALUE);
			query.setExamId(examId);
			String fileName = "分段统计" + DateUtils.getDate("yyyyMMdd") + ".xlsx";
			query = subjectService.findByQuery(query);
			List<StatisticsVO> statisticsVOs = new ArrayList<StatisticsVO>();
			for (ExamSubject subject : query.getResult()) {
				StatisticsVO vo = new StatisticsVO(subject);
				vo = getStatisticsInfo(vo, upload,breach);
				statisticsVOs.add(vo);
			}
			new ExportExcel("分段统计", StatisticsVO.class)
					.setDataList(statisticsVOs).write(response, fileName)
					.dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出数据失败！" + e.getMessage());
		}
		return "redirect:/admin/exam/statistics";
	}
}
