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

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
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.conditions.query.LambdaQueryWrapper;
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.PagerReq;
import com.qmth.exam.reserve.bean.login.LoginUser;
import com.qmth.exam.reserve.bean.studentimport.StudentImportTaskExport;
import com.qmth.exam.reserve.bean.studentimport.StudentImportTaskVO;
import com.qmth.exam.reserve.controller.BaseController;
import com.qmth.exam.reserve.entity.StudentImportTaskEntity;
import com.qmth.exam.reserve.enums.ImportStatus;
import com.qmth.exam.reserve.enums.Role;
import com.qmth.exam.reserve.service.StudentImportTaskService;
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 + "/admin/std")
@Aac(strict = false, auth = true)
public class StudentImportTaskController extends BaseController {

    @Autowired
    private StudentImportTaskService studentImportService;

    @ApiOperation(value = "考生信息导入分页列表")
    @PostMapping(value = "/page")
    public PageResult<StudentImportTaskVO> page(@RequestBody PagerReq req) {
        return studentImportService.page(req);
    }

    @ApiOperation(value = "考生信息模版下载")
    @GetMapping(value = "/import/template")
    public void downloadTemplate(HttpServletResponse response) {
        exportFile("考生信息导入模板.xlsx", ResourceUtil.getStream("templates/studentImport.xlsx"));
    }

    @ApiOperation(value = "考生信息导入")
    @PostMapping(value = "/upload")
    public void upload(MultipartFile file) {
        LoginUser user = this.curLoginUser();
        if (!Role.ADMIN.equals(user.getRole())) {
            throw new StatusException("没有权限");
        }
        LambdaQueryWrapper<StudentImportTaskEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentImportTaskEntity::getStatus, ImportStatus.RUNNING.toString());
        StudentImportTaskEntity exists = studentImportService.getOne(wrapper);
        if (exists != null)
            throw new StatusException("正在导入，请稍后再试");
        try {
            studentImportService.importStudent(user.getId(), file.getOriginalFilename(), file.getInputStream());
        } catch (IOException e) {
            throw new StatusException("文件读取出错", e);
        }
    }

    @ApiOperation(value = "导出异常信息")
    @GetMapping(value = "/export/message")
    public void exportExcepionMessage(@ApiParam("导入的任务ID") @RequestParam Long id, HttpServletResponse response) {
        try {
            String fileName = URLEncoder.encode("异常信息", "UTF-8");
            response.setHeader("Content-Disposition", "inline; filename=" + fileName + ".xlsx");
            response.setContentType("application/vnd.ms-excel");
            ExcelWriter writer = ExcelWriter.create(ExcelType.XLSX);
            List<StudentImportTaskExport> exportList = studentImportService.exportPage(id);
            if (exportList == null || exportList.isEmpty()) {
                throw new StatusException("没有异常信息");
            }
            writer.writeObjects("异常信息", null, StudentImportTaskExport.class, exportList.iterator());
            writer.output(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
