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

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.boot.tools.excel.ExcelWriter;
import com.qmth.boot.tools.excel.enums.ExcelType;
import com.qmth.exam.reserve.bean.Constants;
import com.qmth.exam.reserve.bean.login.LoginUser;
import com.qmth.exam.reserve.bean.student.StudentExportVO;
import com.qmth.exam.reserve.bean.student.StudentReq;
import com.qmth.exam.reserve.bean.student.StudentVO;
import com.qmth.exam.reserve.controller.BaseController;
import com.qmth.exam.reserve.enums.Role;
import com.qmth.exam.reserve.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

@RestController
@Api(tags = "【管理端】考生相关接口")
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + "/admin/student")
@Aac(strict = false, auth = true)
public class StudentAdminController extends BaseController {

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

    @Autowired
    private StudentService studentService;

    @ApiOperation(value = "考生管理分页")
    @PostMapping(value = "/page")
    public PageResult<StudentVO> page(@RequestBody StudentReq req) {
        LoginUser loginUser = this.curLoginUser();
        if(loginUser.getRole().equals(Role.TEACHING)) {
            req.setTeachingId(loginUser.getCategoryId());
        }
        return studentService.pageStudent(req);
    }

    @ApiOperation(value = "删除考生")
    @PostMapping(value = "/delete")
    public void delete(@ApiParam("考生ID") @RequestParam Long[] ids) {
        LoginUser loginUser = this.curLoginUser();
        if (loginUser.getRole().equals(Role.TEACHING)) {
            throw new StatusException("没有权限");
        }
        studentService.delete(ids, loginUser);
    }

    @ApiOperation(value = "修改考生可预约次数")
    @PostMapping(value = "/modify/apply/number")
    public void modifyApplyNumber(@ApiParam("考生ID") @RequestParam Long id, @ApiParam("可预约次数") @RequestParam Integer applyNumber) {
        LoginUser loginUser = this.curLoginUser();
        if (!loginUser.getRole().equals(Role.ADMIN)) {
            throw new StatusException("没有权限");
        }
        studentService.modifyApplyNumber(id, loginUser.getId(), applyNumber);
    }

    @ApiOperation(value = "上传考生的照片")
    @PostMapping(value = "upload/photo")
    public void uploadStudentPhoto(@RequestParam MultipartFile file) {
        LoginUser loginUser = this.curLoginUser();
        if (loginUser.getRole().equals(Role.TEACHING)) {
            throw new StatusException("没有权限");
        }

        String filename = file.getOriginalFilename();
        if (filename != null && !filename.toLowerCase().endsWith(".jpg") && !filename.toLowerCase().endsWith(".png")
                && !filename.toLowerCase().endsWith(".jpeg")) {
            throw new StatusException("请上传后缀为jpg、png或者jpeg的考生头像");
        }
        studentService.uploadStudentPhoto(loginUser.getId(), file);
    }


    @ApiOperation(value = "上传考生的照片-异步多文件上传")
    @PostMapping(value = "upload/student/photo")
    public String uploadStudentPhotoAsync(@RequestParam MultipartFile file) throws IOException {
        if (!Objects.requireNonNull(file.getOriginalFilename()).endsWith(".zip")) {
            throw new StatusException("请上传zip文件");
        }
        LoginUser loginUser = this.curLoginUser();
        studentService.uploadStudentPhotoAsync(loginUser.getId(), file);
        return Constants.ASYNC_TIPS;
    }

    @ApiOperation(value = "导出考生")
    @PostMapping(value = "/export")
    public void export(@RequestParam(value = "taskId", required = false) Long taskId, @RequestParam(value = "teachingId", required = false) Long teachingId,
            @RequestParam(value = "name", required = false) String name, @RequestParam(value = "identityNumber", required = false) String identityNumber,
            @RequestParam(value = "studentCode", required = false) String studentCode, HttpServletResponse response) {
        //参数设置
        StudentReq req = new StudentReq();
        req.setTeachingId(teachingId);
        req.setName(name);
        req.setIdentityNumber(identityNumber);
        req.setStudentCode(studentCode);
        req.setTaskId(taskId);
        // 教学点管理员设置
        LoginUser loginUser = this.curLoginUser();
        if (loginUser.getRole().equals(Role.TEACHING)) {
            req.setTeachingId(loginUser.getCategoryId());
        }
        try {
            String fileName = URLEncoder.encode(System.currentTimeMillis() + "", "UTF-8");
            response.setHeader("Content-Disposition", "inline; filename=" + fileName + ".xlsx");
            response.setContentType("application/vnd.ms-excel");
            ExcelWriter writer = ExcelWriter.create(ExcelType.XLSX);
            List<StudentExportVO> exportList = studentService.exportPage(req);
            if (exportList == null || exportList.isEmpty()) {
                throw new StatusException("无考生信息");
            }
            writer.writeObjects("考生信息", null, StudentExportVO.class, exportList.iterator());
            writer.output(response.getOutputStream());
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new StatusException(e.getMessage());
        }

    }


}
