package com.qmth.exam.reserve.controller.admin;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.qmth.boot.api.annotation.Aac;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.boot.core.collection.PageResult;
import com.qmth.boot.core.exception.StatusException;
import com.qmth.exam.reserve.bean.login.LoginUser;
import com.qmth.exam.reserve.bean.stdapply.CategoryVO;
import com.qmth.exam.reserve.bean.stdapply.SignInVO;
import com.qmth.exam.reserve.bean.stdapply.StudentApplyReq;
import com.qmth.exam.reserve.bean.stdapply.StudentApplyVO;
import com.qmth.exam.reserve.controller.BaseController;
import com.qmth.exam.reserve.enums.Role;
import com.qmth.exam.reserve.service.ApplyTaskService;
import com.qmth.exam.reserve.service.CategoryService;
import com.qmth.exam.reserve.service.ExamSiteService;
import com.qmth.exam.reserve.service.StudentApplyService;
import com.qmth.exam.reserve.util.ResourceUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@Api(tags = "考生预约明细相关接口")
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + "/apply")
@Aac(strict = false, auth = true)
public class StudentApplyController extends BaseController {

    @Autowired
    private StudentApplyService studentApplyService;

    @Autowired
    private ApplyTaskService applyTaskService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ExamSiteService examSiteService;

    @ApiOperation(value = "预约任务列表")
    @PostMapping(value = "/task/list")
    public List<CategoryVO> listTask() {
        return applyTaskService.listTask();
    }

    @ApiOperation(value = "教学点列表")
    @PostMapping(value = "/teaching/list")
    public List<CategoryVO> listTeaching() {
        LoginUser user = this.curLoginUser();
        return categoryService.listTeaching(user);
    }

    @ApiOperation(value = "考点列表")
    @PostMapping(value = "/agent/list")
    public List<CategoryVO> listAgent(@ApiParam("教学点ID") @RequestParam Long id) {
        return examSiteService.listExamSite(id);
    }

    @ApiOperation(value = "考生预约名单详情分页")
    @PostMapping(value = "/std/page")
    public PageResult<StudentApplyVO> page(@RequestBody StudentApplyReq req) {
        LoginUser user = this.curLoginUser();
        if (user.getRole().equals(Role.TEACHING)) {
            req.setTeachingId(user.getCategoryId());
        }
        return studentApplyService.page(req);
    }

    @ApiOperation(value = "取消预约")
    @PostMapping(value = "/std/cancel")
    public void cancel(@ApiParam("预约结果ID") @RequestParam Long id) {
        LoginUser user = this.curLoginUser();
        studentApplyService.cancel(user, id);
    }

    @ApiOperation(value = "导入预考模版下载")
    @PostMapping(value = "/imp/template")
    public void download(HttpServletResponse response) {
        exportFile("导入预考模板.xlsx", ResourceUtil.getStream("templates/preExamImport.xlsx"));
    }

    @ApiOperation(value = "导入预考")
    @PostMapping(value = "/import")
    public Map<String, Object> importPreExamStd(@ApiParam("教学点ID") @RequestParam(required = false) Long teachingId,
            @ApiParam("教学点所在的层级") @RequestParam(required = false) Integer level, @RequestParam MultipartFile file) {
        LoginUser user = this.curLoginUser();
        if (Role.TEACHING.equals(user.getRole())) {
            teachingId = user.getCategoryId();
        }
        List<Map<String, Object>> failRecords = new ArrayList<Map<String, Object>>();
        try {
            failRecords = studentApplyService.importPreExam(user.getId(), teachingId, level, file.getInputStream());
        } catch (IOException e) {
            throw new StatusException("文件读取出错", e);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("hasError", CollectionUtils.isNotEmpty(failRecords));
        map.put("failRecords", failRecords);
        return map;
    }

    @ApiOperation(value = "一键自动分配")
    @PostMapping(value = "/std/auto/assign")
    public void autoAssign(@ApiParam("任务ID") @RequestParam Long taskId) {
        if (taskId == null) {
            throw new StatusException("请选择预约任务");
        }
        LoginUser user = this.curLoginUser();
        if (!Role.ADMIN.equals(user.getRole())) {
            throw new StatusException("没有权限");
        }
        studentApplyService.autoAssign(taskId, user.getId());
    }

    @ApiOperation(value = "打印签到表")
    @PostMapping(value = "/std/auto/sign/in/print")
    public void printSignIn(@ApiParam("教学点ID") @RequestParam(required = false) Long teachingId,
            @ApiParam("考点ID") @RequestParam(required = false) Long agentId,
            @ApiParam("考试日期") @RequestParam(required = true) Long examDate) {
        LoginUser user = this.curLoginUser();
        if (Role.ADMIN.equals(user.getRole()) && teachingId == null) {
            throw new StatusException("请选择教学点");
        }
        if (Role.TEACHING.equals(user.getRole())) {
            teachingId = user.getCategoryId();
        }
        File signInZip = studentApplyService.downloadSignIn(teachingId, agentId, examDate);
        exportFile(signInZip.getName(), signInZip);
        signInZip.delete();
    }

    @Aac(strict = false, auth = false)
    @ApiOperation(value = "自动排考")
    @PostMapping(value = "/std/auto/layout")
    public void autoLayout(@ApiParam("教学点ID") @RequestParam(required = false) Long teachingId) {
        // LoginUser user = this.curLoginUser();
        // if (!Role.ADMIN.equals(user.getRole())) {
        // throw new StatusException("没有权限");
        // }
        studentApplyService.autoLayout(teachingId);
    }

    @ApiOperation(value = "可打印签到表的日期")
    @PostMapping(value = "/sign/in/date")
    public List<SignInVO> listSignInDate(@ApiParam("预约任务ID") @RequestParam(required = false) Long taskId) {
        return studentApplyService.listSignInDate(taskId);
    }

}
