package cn.com.qmth.examcloud.core.questions.api.controller;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.com.qmth.examcloud.api.commons.security.bean.User;
import cn.com.qmth.examcloud.commons.exception.StatusException;
import cn.com.qmth.examcloud.core.questions.base.enums.PaperSeqMode;
import cn.com.qmth.examcloud.core.questions.dao.ExportServiceManageRepo;
import cn.com.qmth.examcloud.core.questions.service.ExportPaperService;
import cn.com.qmth.examcloud.core.questions.service.export.SydxExportPaperService;
import cn.com.qmth.examcloud.web.support.ControllerSupport;
import io.swagger.annotations.ApiOperation;

/**
 * Created by songyue on 17/3/30.
 */
@Controller
@RequestMapping("${api_cqb}/")
public class ExportPaperController extends ControllerSupport {

    private static final Logger log = LoggerFactory.getLogger(ExportPaperController.class);

    @Autowired
    ExportServiceManageRepo exportServiceManageRepo;

    @Autowired
    SydxExportPaperService sydxExportPaperService;

    @Autowired
    private ExportPaperService exportPaperService;

    /**
     * 导出单个试卷
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "导出试卷", notes = "导出试卷")
    @GetMapping(value = "/paper/export/{id}/{exportContentList}/{examType}")
    public void getPaperById(HttpServletRequest request, HttpServletResponse response, @PathVariable String id, @PathVariable String exportContentList,
            @PathVariable String examType,@RequestParam(required = false) PaperSeqMode seqMode) {
        log.info("导出开始");
        String psw = request.getParameter("psw");
        User user = getAccessUser();
        exportPaperService.exportPaperFile(id, exportContentList, response, seqMode,
                examType, psw, user);
        log.info("导出结束");
    }

    /**
     * 批量导出试卷
     *
     * @param request
     * @param response
     * @param paperIds
     * @param orgName
     * @param exportContentList
     * @param loginName
     */
    @ApiOperation(value = "批量导出试卷", notes = "批量导出")
    @GetMapping(value = "/paper/batch_export/{paperIds}/{exportContentList}/{examType}")
    public void getPaperByIds(HttpServletRequest request, HttpServletResponse response, @PathVariable String paperIds,
            @PathVariable String exportContentList,
            @PathVariable String examType,@RequestParam(required = false) PaperSeqMode seqMode) {
        log.info("批量导出");
        List<String> paperList = Stream.of(paperIds.split(",")).collect(Collectors.toList());
        try {
            User user = getAccessUser();
            exportPaperService.exportPaperFiles(paperList, exportContentList, response,
            		seqMode, examType, user);
        } catch (Exception e) {
            log.error("导出异常",e);
        }
        log.info("导出结束");
    }

    @ApiOperation(value = "导出试题分布数量（按课程）", notes = "导出试题分布数量（按课程）")
    @GetMapping(value = "/paper/export/course/question/{courseNo}")
    public void downQuestionDistribute(HttpServletResponse response, @PathVariable String courseNo) {
        log.info("开始导出Excel");
        try {
            exportPaperService.downQuestionDistribute(courseNo, response);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    @ApiOperation(value = "导出试题分布数量（按试卷）", notes = "导出试题分布数量（按试卷）")
    @GetMapping(value = "/paper/export/course/question/papers/{paperIds}")
    public void downQuestionDistributeByPapers(HttpServletResponse response, @PathVariable String paperIds) {
        log.info("开始导出Excel");
        try {
            exportPaperService.downQuestionDistributeByPapers(paperIds, response);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    @ApiOperation(value = "导出原始导入的试卷", notes = "导出原始导入的试卷")
    @GetMapping(value = "/originalPaper/export/{paperId}/{loginName}")
    public void downOriginalPaper(HttpServletResponse response, @PathVariable String paperId,
            @PathVariable String loginName) {
        try {
            exportPaperService.downOriginalPaper(paperId, loginName, response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        log.info("开始导出原始导入的试卷");
    }

    @ApiOperation(value = "导出原始导入的试卷", notes = "导出原始导入的试卷")
    @GetMapping(value = "/originalPaper/exportPlus/{paperId}/{loginName}")
    public void downOriginalPaperPlus(HttpServletResponse response, @PathVariable String paperId,
            @PathVariable String loginName) {
        User user=getAccessUser();
        try {
			exportPaperService.downOriginalPaperPlus(paperId, user.getRootOrgId(), response);
		} catch (IOException e) {
			throw new StatusException("500", e.getMessage(),e);
		}
        log.info("开始导出原始导入的试卷");
    }
}
