package cn.com.qmth.stmms.api.controller;

import cn.com.qmth.stmms.api.exception.ApiException;
import cn.com.qmth.stmms.biz.exam.model.Exam;
import cn.com.qmth.stmms.biz.exam.model.ExamPackage;
import cn.com.qmth.stmms.biz.exam.service.ExamPackageService;
import cn.com.qmth.stmms.biz.exam.service.ExamService;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.file.service.FileService;
import cn.com.qmth.stmms.common.annotation.Logging;
import cn.com.qmth.stmms.common.annotation.RoleRequire;
import cn.com.qmth.stmms.common.domain.ApiUser;
import cn.com.qmth.stmms.common.enums.LogType;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.utils.RequestUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
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.*;

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

import java.util.List;
import java.util.stream.Collectors;

@Controller("examPackageApiController")
@RequestMapping("/api")
public class ExamPackageController extends BaseApiController {

    protected static Logger logger = LoggerFactory.getLogger(ExamPackageController.class);

    @Autowired
    private ExamStudentService examStudentService;

    @Autowired
    private ExamService examService;

    @Autowired
    private ExamPackageService packageService;

    @Autowired
    private FileService fileService;

    @RoleRequire({ Role.SCHOOL_ADMIN, Role.SCANNER })
    @RequestMapping(value = "/package/{examId}", method = RequestMethod.GET)
    @ResponseBody
    public JSONArray getPackageCode(HttpServletRequest request, @PathVariable Integer examId) {
        ApiUser user = RequestUtils.getApiUser(request);
        JSONArray array = new JSONArray();
        Exam exam = examService.findById(examId);
        if (exam != null && exam.getSchoolId().equals(user.getSchoolId())) {
            List<String> list = examStudentService.findDistinctPackageCode(examId);
            if (list != null) {
                for (String code : list) {
                    array.add(StringUtils.trimToEmpty(code));
                }
            }
        } else {
            throw ApiException.EXAM_NOT_ACCESSIBLED;
        }
        return array;
    }

    @Logging(menu = "扫描端-修改签到表数量", type = LogType.UPDATE)
    @RoleRequire({ Role.SCHOOL_ADMIN, Role.SCANNER })
    @RequestMapping(value = "/package/{examId}", method = RequestMethod.POST)
    @ResponseBody
    public int updatePackage(HttpServletRequest request, @PathVariable Integer examId,
            @RequestBody ExamPackage examPackage) {
        Exam exam = examService.findById(examId);
        if (exam != null) {
            ExamPackage obj = packageService.find(examId, examPackage.getCode());
            if (obj != null && examPackage.getPicCount() != null) {
                obj.setPicCount(examPackage.getPicCount());
                obj = packageService.save(obj);
                return obj.getPicCount();
            }
        } else {
            throw ApiException.EXAM_NOT_ACCESSIBLED;
        }
        return -1;
    }

    @RoleRequire({ Role.SCHOOL_ADMIN, Role.SCANNER })
    @RequestMapping(value = "/package/count/{examId}", method = RequestMethod.GET)
    @ResponseBody
    public JSONArray getPackageCount(HttpServletRequest request, HttpServletResponse response,
            @PathVariable Integer examId, @RequestParam(required = false) Boolean upload,
            @RequestParam(required = false) Boolean withUrl) {
        ApiUser user = RequestUtils.getApiUser(request);
        JSONArray array = new JSONArray();
        Exam exam = examService.findById(examId);
        if (exam != null && exam.getSchoolId().equals(user.getSchoolId())) {
            List<ExamPackage> list = upload != null ? packageService.list(examId, upload) : packageService.list(examId);
            if (list != null) {
                for (ExamPackage ep : list) {
                    JSONObject obj = new JSONObject();
                    obj.accumulate("code", ep.getCode());
                    obj.accumulate("picCount", ep.getPicCount());
                    if (withUrl != null && withUrl.booleanValue()) {
                        obj.accumulate(
                                "urls",
                                fileService.getPackageUris(ep.getExamId(), ep.getCode(), 1, ep.getPicCount()).stream()
                                        .map(uri -> fileService.getFileServer().concat(uri))
                                        .collect(Collectors.toList()));
                    }
                    array.add(obj);
                }
            }
        } else {
            throw ApiException.EXAM_NOT_ACCESSIBLED;
        }
        return array;
    }

}
