package yangtz.cs.liu.campus.controller.examination;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import yangtz.cs.liu.campus.constant.ArtExamConstant;
import yangtz.cs.liu.campus.domain.examination.EduArtStudent;
import yangtz.cs.liu.campus.domain.examination.SchoolArtExam;
import yangtz.cs.liu.campus.domain.examination.SchoolArtRelation;
import yangtz.cs.liu.campus.domain.examination.SchoolTestProject;
import yangtz.cs.liu.campus.service.examination.*;
import yangtz.cs.liu.campus.vo.examination.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xuten
 */
@RestController
@RequestMapping("/artExam")
public class SchoolArtExamController extends BaseController {
    @Autowired
    private ISchoolArtExamService artExamService;

    @Autowired
    private ISchoolArtStudentService artStudentService;

    @Autowired
    private ISchoolArtRelationService artRelationService;

    @Autowired
    private IEduArtStudentService eduArtStudentService;

    @Autowired
    private ISchoolTestProjectService projectService;

    /**
     * 考务管理-考试管理-列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SchoolArtExam exam) {
        startPage();
        return getDataTable(artExamService.queryList(exam));
    }

    /**
     * 考务管理-考试管理-新增时点击保存
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SchoolArtExamVo exam) {
        SchoolArtExam entity = new SchoolArtExam();
        BeanUtils.copyProperties(exam,entity);
        entity.setStatus(ArtExamConstant.NOPUB);
        //将测试项目ids,整成id之间用逗号隔开的字符串
        String projectIds = StringUtils.join(exam.getProjectIdList(),",");
        entity.setProjectIds(projectIds);
        entity.insert();
        return toAjax(artExamService.save(entity));
    }

    /**
     * 考务管理-考试管理-新增时点击发布
     */
    @PostMapping("/addPub")
    public AjaxResult addPub(@RequestBody SchoolArtExamVo exam) {
        SchoolArtExam entity = new SchoolArtExam();
        BeanUtils.copyProperties(exam,entity);
        entity.setStatus(ArtExamConstant.INFOCHECK);
        //将测试项目ids,整成id之间用逗号隔开的字符串
        String projectIds = StringUtils.join(exam.getProjectIdList(),",");
        entity.setProjectIds(projectIds);
        entity.insert();
        return toAjax(artExamService.save(entity));
    }

    /**
     * 考务管理-考试管理-获取详情
     */
    @GetMapping("/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        SchoolArtExam entity = artExamService.getById(id);
        SchoolArtExamVo exam = new SchoolArtExamVo();
        BeanUtils.copyProperties(entity,exam);
        //id之间用逗号隔开的字符串 整成Long数组
        String[] strArr = entity.getProjectIds().split(",");
        List<Long> projectIdList = new ArrayList<>();
        for(String str : strArr){
            projectIdList.add(Long.parseLong(str));
        }

        //获取测试项目名
        LambdaQueryWrapper<SchoolTestProject> lqw = new LambdaQueryWrapper<>();
        lqw.in(SchoolTestProject::getId,projectIdList).orderByDesc(SchoolTestProject::getCreateTime);
        List<SchoolTestProject> projects = projectService.list(lqw);
        exam.setProjectName(projects.stream().map(SchoolTestProject::getProject).collect(Collectors.joining(",")));
        exam.setProjectIdList(projectIdList);
        return AjaxResult.success(exam);
    }

    /**
     * 考务管理-考试管理-修改时点击保存
     */
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody SchoolArtExamVo exam) {
        if (StringUtils.isNull(exam.getId())) {
            throw new ServiceException("id为空,请检查");
        }
        SchoolArtExam entity = new SchoolArtExam();
        BeanUtils.copyProperties(exam,entity);
        //将测试项目ids,整成id之间用逗号隔开的字符串
        String projectIds = StringUtils.join(exam.getProjectIdList(),",");
        entity.setProjectIds(projectIds);
        entity.update();
        return toAjax(artExamService.updateById(entity));
    }

    /**
     * 考务管理-考试管理-修改时点击发布（考试管理-点击未发布进入考试信息tab页的发布按钮也是这个按钮）
     */
    @PutMapping("/editPub")
    public AjaxResult editPub(@RequestBody SchoolArtExamVo exam) {
        if (StringUtils.isNull(exam.getId())) {
            throw new ServiceException("id为空,请检查");
        }
        SchoolArtExam entity = new SchoolArtExam();
        BeanUtils.copyProperties(exam,entity);
        entity.setStatus(ArtExamConstant.INFOCHECK);
        //将测试项目ids,整成id之间用逗号隔开的字符串
        String projectIds = StringUtils.join(exam.getProjectIdList(),",");
        entity.setProjectIds(projectIds);
        entity.update();
        return toAjax(artExamService.updateById(entity));
    }

    /**
     * 考务管理-考试管理-单个删除
     * 删除考试与考生关系
     * 删除该考试对应的教育局信息
     */
    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        //删考试与考生关系
        LambdaQueryWrapper<SchoolArtRelation> relatonLqw = new LambdaQueryWrapper<>();
        relatonLqw.eq(SchoolArtRelation::getExamId, id);
        artRelationService.remove(relatonLqw);

        //删除该考试对应的教育局信息
        LambdaQueryWrapper<EduArtStudent> eduLqw = new LambdaQueryWrapper<>();
        eduLqw.eq(EduArtStudent::getExamId, id);
        eduArtStudentService.remove(eduLqw);
        return AjaxResult.success(artExamService.removeById(id));
    }


    /**
     * 考试管理-信息审核-列表
     */
    @GetMapping("/checkList/{examId}")
    public TableDataInfo checkList(@PathVariable Long examId, ArtEduStudentVo vo) {
        vo.setExamId(examId);
        return getDataTable(artStudentService.getInfoCheck(vo));
    }

    /**
     * 考试管理-信息审核-通过
     * 所有信息都匹配才能将审核状态改为通过
     */
    @PutMapping(value = {"/pass/{examId}/{studentIds}","/pass/{examId}/"})
    public AjaxResult pass(@PathVariable Long examId, @PathVariable(value = "studentIds", required = false) List<Long> studentIds) {
        if (StringUtils.isNull(studentIds) || studentIds.size() == 0) {
            throw new ServiceException("所选数据都为未报名数据，无法通过");
        }
        return AjaxResult.success(artStudentService.pass(examId, studentIds));
    }

    /**
     * 考试管理-信息审核-单个通过
     * 所有信息都匹配才能将审核状态改为通过
     */
    @PutMapping("/passOne/{examId}/{studentId}")
    public AjaxResult passOne(@PathVariable Long examId, @PathVariable Long studentId) {
        return toAjax(artStudentService.passOne(examId, studentId));
    }

    /**
     * 考试管理-信息审核-退回修改
     * 只有待审核状态擦可以退回修改
     */
    @PutMapping(value = {"/back/{examId}/{studentIds}","/back/{examId}/"})
    public AjaxResult back(@PathVariable Long examId, @PathVariable(value = "studentIds", required = false) List<Long> studentIds) {
        if (StringUtils.isNull(studentIds) || studentIds.size() == 0) {
            throw new ServiceException("所选数据都为未报名数据，无法退回修改");
        }
        return AjaxResult.success(artStudentService.back(examId, studentIds));
    }

    /**
     * 考试管理-信息审核-单个退回修改
     * 只有待审核状态擦可以退回修改
     */
    @PutMapping("/backOne/{examId}/{studentId}")
    public AjaxResult backOne(@PathVariable Long examId, @PathVariable Long studentId) {
        return toAjax(artStudentService.backOne(examId, studentId));
    }

    /**
     * 考试管理-信息审核-驳回
     * 只有待审核状态才能驳回
     */
    @PutMapping(value = {"/reject/{examId}/{studentIds}","/reject/{examId}/"})
    public AjaxResult reject(@PathVariable Long examId, @PathVariable(value = "studentIds", required = false) List<Long> studentIds) {
        if (StringUtils.isNull(studentIds) || studentIds.size() == 0) {
            throw new ServiceException("所选数据都为未报名数据，无法驳回");
        }
        return AjaxResult.success(artStudentService.reject(examId, studentIds));
    }

    /**
     * 考试管理-信息审核-单个驳回
     * 只有待审核状态才能驳回
     */
    @PutMapping("/rejectOne/{examId}/{studentId}")
    public AjaxResult reject(@PathVariable Long examId, @PathVariable Long studentId) {
        return toAjax(artStudentService.rejectOne(examId, studentId));
    }

    /**
     * 考试管理-信息审核-结束
     * 没有到报名截止时间，这里不能结束
     */
    @PutMapping("/checkEnd/{examId}")
    public AjaxResult checkEnd(@PathVariable Long examId) {
        SchoolArtExam exam = artExamService.getById(examId);
        if (DateUtils.getNowDate().before(exam.getDeadline())) {
            //未到报名截止时间
            throw new ServiceException("没有到报名截止时间，不能结束此环节");
        }
        exam.setStatus(ArtExamConstant.ADDRESS);
        return toAjax(artExamService.updateById(exam));
    }

    /**
     * 考试管理-考场分配-列表
     */
    @GetMapping("/addressList/{examId}")
    public TableDataInfo addressList(@PathVariable Long examId, ArtExamAddressVo vo) {
        vo.setExamId(examId);
        vo.setAuditStatus(ArtExamConstant.PASS);
        return getDataTable(artRelationService.getAddressList(vo));
    }

    /**
     * 考试管理-考场分配-导出
     */
    @PostMapping("/exportAddress/{examId}")
    public void exportAddress(HttpServletResponse response, ArtExamAddressVo vo, @PathVariable Long examId) {
        vo.setExamId(examId);
        vo.setAuditStatus(ArtExamConstant.PASS);
        List<ArtExamAddressVo> list = artRelationService.getAddressList(vo);
        int i = 1;
        for(ArtExamAddressVo addressVo : list){
            addressVo.setXh(i);
            i++;
        }
        ExcelUtil<ArtExamAddressVo> util = new ExcelUtil<>(ArtExamAddressVo.class);
        util.exportExcel(response, list, "考场分配表");
    }

    /**
     * 考试管理-考场分配-导入
     */
    @PostMapping("/importAddressData/{examId}")
    public AjaxResult importAddressData(@PathVariable Long examId, MultipartFile file) throws Exception {
        ExcelUtil<ArtExamAddressVo> util = new ExcelUtil<>(ArtExamAddressVo.class);
        List<ArtExamAddressVo> list = util.importExcel(file.getInputStream());

        //校验数据
        artRelationService.checkImportAddress(list);
        //数据导入
        return AjaxResult.success(artRelationService.importDataAddress(list,examId));
    }

    /**
     * 考试管理-考场分配-结束
     * 有考场分配信息为空的要进行提示
     */
    @PutMapping("/addressEnd/{examId}")
    public AjaxResult addressEnd(@PathVariable Long examId) {
        return toAjax(artRelationService.addressEnd(examId));
    }


    /**
     * 考试管理-成绩管理-列表
     */
    @GetMapping("/scoreList/{examId}")
    public TableDataInfo scoreList(@PathVariable Long examId, ArtExamScoreVo vo) {
        vo.setExamId(examId);
        vo.setAuditStatus(ArtExamConstant.PASS);
        return getDataTable(artRelationService.getScoreList(vo));
    }

    /**
     * 考试管理-成绩发布-导出
     */
    @PostMapping("/exportScore/{examId}")
    public void exportScore(HttpServletResponse response, ArtExamScoreVo vo, @PathVariable Long examId) {
        vo.setExamId(examId);
        vo.setAuditStatus(ArtExamConstant.PASS);
        List<ArtExamScoreVo> list = artRelationService.getScoreList(vo);
        int i = 1;
        for(ArtExamScoreVo scoreVo : list){
            scoreVo.setXh(i);
            i++;
        }
        ExcelUtil<ArtExamScoreVo> util = new ExcelUtil<>(ArtExamScoreVo.class);
        util.exportExcel(response, list, "成绩发布信息表");
    }

    /**
     * 考试管理-成绩发布-导入
     */
    @PostMapping("/importScoreData/{examId}")
    public AjaxResult importScoreData(@PathVariable Long examId, MultipartFile file) throws Exception {
        ExcelUtil<ArtExamScoreVo> util = new ExcelUtil<>(ArtExamScoreVo.class);
        List<ArtExamScoreVo> list = util.importExcel(file.getInputStream());

        //校验数据
        artRelationService.checkImportScore(list);
        //数据导入
        return AjaxResult.success(artRelationService.importDataScore(list,examId));
    }

    /**
     * 考试管理-成绩发布-结束
     * 有成绩信息为空的要进行提示
     */
    @PutMapping("/scoreEnd/{examId}")
    public AjaxResult scoreEnd(@PathVariable Long examId) {
        return toAjax(artRelationService.scoreEnd(examId));
    }
}
