package yangtz.cs.liu.webpage.controller;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.word.WordExportUtil;
import com.core.utils.UploadToServer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.ImageUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.util.WebStudentInfoUtil;
import com.ruoyi.framework.web.service.WebTokenService;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
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.*;
import yangtz.cs.liu.campus.service.examination.*;
import com.ruoyi.common.core.domain.model.WebLoginBody;
import yangtz.cs.liu.campus.util.TemplateExcelUtils;
import yangtz.cs.liu.webpage.domain.WebRegisterBody;
import yangtz.cs.liu.webpage.vo.ArtAdmissionTicketVo;
import yangtz.cs.liu.webpage.vo.QueryScoreVo;
import yangtz.cs.liu.webpage.vo.WebSchoolArtStudentVo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xuten
 */
@RestController
@RequestMapping("/web/artStudent")
public class WebSchoolArtStudentController extends BaseController {

    @Autowired
    private ISchoolArtStudentService artStudentService;

    @Autowired
    private WebTokenService webTokenService;

    @Autowired
    WebStudentInfoUtil studentInfoUtil;

    @Autowired
    private ISchoolArtExamService artExamService;

    @Autowired
    private ISchoolArtRelationService artRelationService;

    @Autowired
    private ISchoolTestProjectService projectService;

    @Autowired
    private IJuniorHighSchoolService schoolService;

    @Value("${ruoyi.profile}")
    private String profile;

    @Value("${ruoyi.serverAddress}")
    private String serverAddress;

    /******------------以下是网页端登录注册等接口----------------***********/

    @PostMapping("/register")
    public AjaxResult register(@RequestBody WebRegisterBody webRegisterBody)
    {
        String msg = artStudentService.register(webRegisterBody);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }

    /**
     * 登录方法
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody WebRegisterBody registerBody)
    {
        if(StringUtils.isEmpty(registerBody.getPhoneNumber())){
            throw new ServiceException("手机号不能为空");
        }
        if(StringUtils.isEmpty(registerBody.getIdCard())){
            throw new ServiceException("身份证号不能为空");
        }
        if(StringUtils.isEmpty(registerBody.getPassword())){
            throw new ServiceException("密码不能为空");
        }
        WebLoginBody loginBody = artStudentService.login(registerBody);
        if (StringUtils.isNull(loginBody)) {
            return AjaxResult.error("login error");
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getStudentName(),Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        String token = webTokenService.createToken(loginBody);
        return AjaxResult.success().put(Constants.TOKEN,token);
    }

    /**
    *获取当前登录考生信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() throws UnsupportedEncodingException {
        WebLoginBody loginBody = studentInfoUtil.getLoginBody();
        SchoolArtStudent student = artStudentService.getById(loginBody.getId());
        //获取PC所在服务器端的图片资源
        if(StringUtils.isNotNull(student.getPhoto()) && !"".equals(student.getPhoto())){
            loginBody.setPhoto(student.getPhoto());
            loginBody.setPhotoData(UploadToServer.getPicFromServer(serverAddress,student.getPhoto()));
        }
        //SchoolArtStudent student = artStudentService.getById(loginBody.getId());
        return AjaxResult.success().put("info",loginBody);
    }

    /**
     * 自定义退出逻辑
     */
    @GetMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        String webToken = webTokenService.getToken(request);
        WebLoginBody loginUser = webTokenService.getWebLoginBody(webToken);
        if (StringUtils.isNotNull(loginUser))
        {
            String userName = loginUser.getStudentName();
            // 删除用户缓存记录
            webTokenService.delWebLoginBody(loginUser.getWebToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
        }
        return AjaxResult.success("退出成功");
    }

    /******------------以下是网页端考生可看考试列表以及考试进入后的各tab页面等接口----------------***********/

    /**
     * 网页版-考试报名页面list
     * studentId 为网页登录的艺考生的id
     * 显示在报名阶段的，和已报名的考试
     * */
    @GetMapping("/list/{studentId}")
    public TableDataInfo list(@PathVariable Long studentId)
    {
        startPage();
        return getDataTable(artExamService.getArtExam(studentId));
    }

    /**
     * 判断能不能点进去进入按钮
     * 1能 0不能
     *
     * 当前状态（0=报名，1=待审核，2=通过，3=驳回，4=信息修改，5=准考证打印，6=成绩查询，7=审核）
     * */
    @GetMapping("/enterBtn/{testId}/{studentId}")
    public AjaxResult enterBtn(@PathVariable Long studentId,@PathVariable Long testId)
    {
        return AjaxResult.success().put("data",artStudentService.enterBtn(studentId,testId));
    }

    /**
     * 点击进入，进入考试须知等主页面，返回值：当前所处节点，及页面的值
     * */
    @GetMapping("/enter/all/{testId}/{studentId}")
    public AjaxResult enterAll(@PathVariable Long studentId,@PathVariable Long testId) throws UnsupportedEncodingException {
        AjaxResult result = AjaxResult.success();
        //获取考生与考试关系
        SchoolArtRelation relation = artRelationService.getRelationByIds(testId,studentId);
        if(StringUtils.isNull(relation)){
            //暂无关系，则应默认展示  考前须知模块，，，返回考试安排和考试注意事项
            SchoolArtExam exam = artExamService.getById(testId);
            result.put("node",ArtExamConstant.PREEXAM);
            result.put("data",exam);
            return result;
        }else {
            //有关联关系,判断关系提交状态是否提交
            WebSchoolArtStudentVo student = artStudentService.getStuInfo(studentId,testId);
            //获取PC所在服务器端的图片资源
            if(StringUtils.isNotNull(student.getPhoto()) && !"".equals(student.getPhoto())){
                student.setPhotoData(UploadToServer.getPicFromServer(serverAddress,student.getPhoto()));
            }
            //若未提交，则进入报名阶段，返回学生信息
            if(ArtExamConstant.NOSUBMIT.equals(relation.getSubmit())){
                result.put("node",ArtExamConstant.SIGN);
                result.put("data",student);
                return result;
            }else {
                //已提交，
                //判断考试在什么阶段
                SchoolArtExam exam = artExamService.getById(testId);
                if(ArtExamConstant.INFOCHECK.equals(exam.getStatus()) || ArtExamConstant.ADDRESS.equals(exam.getStatus())){
                    //在信息审核阶段或考场分配阶段
                    //返回值节点为  审核  节点 ，返回学生信息
                    result.put("node",ArtExamConstant.AUDIT);
                    result.put("data",student);
                    return result;
                } else if (ArtExamConstant.SCORE.equals(exam.getStatus())) {
                    //考试状态为成绩发布，判断考生有没有通过审核，通过的进入打印准考证节点，审核状态不为通过的，则返回审核节点，及学生信息
                    if(ArtExamConstant.PASS.equals(relation.getAuditStatus())){
                        //此时返回   打印准考证  节点 ，准考证有关信息
                        //获取准考证信息
                        result.put("node",ArtExamConstant.TICKET);
                        ArtAdmissionTicketVo ticketVo = artStudentService.getTicket(studentId,testId);
                        //获取PC所在服务器端的图片资源
                        if(StringUtils.isNotNull(ticketVo.getPhoto()) && !"".equals(ticketVo.getPhoto())){
                            ticketVo.setPhotoData(UploadToServer.getPicFromServer(serverAddress,ticketVo.getPhoto()));
                        }
                        result.put("data",ticketVo);
                        return result;
                    }else{
                        //审核状态不为通过的，则返回审核节点，及学生信息
                        result.put("node",ArtExamConstant.AUDIT);
                        result.put("data",student);
                        return result;
                    }
                }else {
                    //考试状态为结束 判断考生有没有通过审核，通过的进入成绩查询节点，审核状态不为通过的，则返回审核节点，及学生信息
                    if(ArtExamConstant.PASS.equals(relation.getAuditStatus())){
                        //此时返回   成绩查询  节点 ，考试成绩有关信息
                        //获取考试成绩有关信息
                        result.put("node",ArtExamConstant.SEARCH);
                        result.put("data",artStudentService.getScore(studentId,testId));
                        return result;
                    }else{
                        //审核状态不为通过的，则返回审核节点，及学生信息
                        result.put("node",ArtExamConstant.AUDIT);
                        result.put("data",student);
                        return result;
                    }
                }
            }
        }
    }

    /**
     * 网页进入按钮点击后的界面-点击考前须知
     * examId 当前考试id
     * 返回：所处节点node；返回数据data
     * */
    @GetMapping("/enterPreExam/{examId}")
    public AjaxResult enterPreExam(@PathVariable Long examId)
    {
        AjaxResult result = AjaxResult.success();
        SchoolArtExam exam = artExamService.getById(examId);
        result.put("node",ArtExamConstant.PREEXAM);
        result.put("data",exam);
        return result;
    }


    /**
     * 网页进入按钮点击后的界面-点击考生报名或审核
     * examId 当前考试id,studentId考生id
     * 返回：所处节点node；能否展示view(1能 0不能),返回数据data
     * */
    @GetMapping("/enterEnroll/{examId}/{studentId}")
    public AjaxResult enterEnroll(@PathVariable Long examId,@PathVariable Long studentId) throws UnsupportedEncodingException {
        AjaxResult result = AjaxResult.success();
        //获取考生与考试关系
        SchoolArtRelation relation = artRelationService.getRelationByIds(examId,studentId);
        WebSchoolArtStudentVo student = artStudentService.getStuInfo(studentId,examId);
        //获取PC所在服务器端的图片资源
        if(StringUtils.isNotNull(student.getPhoto()) && !"".equals(student.getPhoto())){
            student.setPhotoData(UploadToServer.getPicFromServer(serverAddress,student.getPhoto()));
        }
        if(StringUtils.isNull(relation)){
            //throw new ServiceException("请先阅读考前须知");
            result.put("node",ArtExamConstant.SIGN);
            result.put("view",ArtExamConstant.SUBMIT);
            result.put("data",student);
            return result;
        }else {
            //有关联关系,判断关系提交状态是否提交
            //若未提交，则进入报名阶段，返回学生信息
            if(ArtExamConstant.NOSUBMIT.equals(relation.getSubmit())){
                result.put("node",ArtExamConstant.SIGN);
                result.put("view",ArtExamConstant.SUBMIT);
                result.put("data",student);
                return result;
            }else {
                result.put("node",ArtExamConstant.AUDIT);
                result.put("view",ArtExamConstant.SUBMIT);
                result.put("data",student);
                return result;
            }
        }
    }

    /**
     * 网页进入按钮点击后的界面-点击打印准考证
     * examId 当前考试id,studentId考生id
     * 返回：所处节点node；能否展示view(1能 0不能),返回数据data
     * */
    @GetMapping("/enterPrint/{examId}/{studentId}")
    public AjaxResult enterPrint(@PathVariable Long examId,@PathVariable Long studentId) throws UnsupportedEncodingException {
        AjaxResult result = AjaxResult.success();
        //获取考生与考试关系
        SchoolArtRelation relation = artRelationService.getRelationByIds(examId,studentId);
        //未报名的
        if(StringUtils.isNull(relation)){
            result.put("node",ArtExamConstant.TICKET);
            result.put("view",ArtExamConstant.NOSUBMIT);
            result.put("data",new ArtAdmissionTicketVo());
            return result;
        }else {
            //有关联关系,判断关系提交状态是否提交
            //若未提交，不能显示该页面的信息
            if(ArtExamConstant.NOSUBMIT.equals(relation.getSubmit())){
                result.put("node",ArtExamConstant.TICKET);
                result.put("view",ArtExamConstant.NOSUBMIT);
                result.put("data",new ArtAdmissionTicketVo());
                return result;
            }else {
                //已提交，判断审核状态，审核状态为通过的才能显示本界面，
                // 审核状态为通过的，要判断当前考试状态是否是成绩发布，只有是此状态才可以返回数据data，
                // 不然则data为空，前端应显示准卡证打印时间未开放
                if(ArtExamConstant.PASS.equals(relation.getAuditStatus())){
                    SchoolArtExam exam = artExamService.getById(examId);
                    //审核状态为通过，且考试状态为成绩发布阶段，返回
                    if (ArtExamConstant.SCORE.equals(exam.getStatus())) {
                        result.put("node",ArtExamConstant.TICKET);
                        result.put("view",ArtExamConstant.SUBMIT);
                        ArtAdmissionTicketVo ticketVo = artStudentService.getTicket(studentId,examId);
                        //获取PC所在服务器端的图片资源
                        if(StringUtils.isNotNull(ticketVo.getPhoto()) && !"".equals(ticketVo.getPhoto())){
                            ticketVo.setPhotoData(UploadToServer.getPicFromServer(serverAddress,ticketVo.getPhoto()));
                        }
                        result.put("data",ticketVo);
                        return result;
                    }else{
                        result.put("node",ArtExamConstant.TICKET);
                        result.put("view",ArtExamConstant.SUBMIT);
                        result.put("data",null);
                        return result;
                    }
                }else{
                    //审核状态不为通过的，则不要展示本页面
                    result.put("node",ArtExamConstant.TICKET);
                    result.put("view",ArtExamConstant.NOSUBMIT);
                    result.put("data",new ArtAdmissionTicketVo());
                    return result;
                }
            }
        }
    }

    /**
     * 网页进入按钮点击后的界面-点击考试查询
     * examId 当前考试id,studentId考生id
     * 返回：所处节点node；能否展示view(1能 0不能),返回数据data
     * */
    @GetMapping("/enterScore/{examId}/{studentId}")
    public AjaxResult enterScore(@PathVariable Long examId,@PathVariable Long studentId)
    {
        AjaxResult result = AjaxResult.success();
        //获取考生与考试关系
        SchoolArtRelation relation = artRelationService.getRelationByIds(examId,studentId);
        //未报名的,此页面不展示
        if(StringUtils.isNull(relation)){
            result.put("node",ArtExamConstant.SEARCH);
            result.put("view",ArtExamConstant.NOSUBMIT);
            result.put("data",new QueryScoreVo());
            return result;
        }else {
            //有关联关系,判断关系提交状态是否提交
            //若未提交，不能显示该页面的信息
            if(ArtExamConstant.NOSUBMIT.equals(relation.getSubmit())){
                result.put("node",ArtExamConstant.SEARCH);
                result.put("view",ArtExamConstant.NOSUBMIT);
                result.put("data",new QueryScoreVo());
                return result;
            }else {
                //已提交，判断审核状态，审核状态为通过的才能显示本界面，
                // 审核状态为通过的，要判断当前考试状态是否是结束，只有是此状态才可以返回数据data，
                // 不然则data为空，前端应显示成绩暂未发布
                if(ArtExamConstant.PASS.equals(relation.getAuditStatus())){
                    SchoolArtExam exam = artExamService.getById(examId);
                    //审核状态为通过，且考试状态为成绩发布阶段，返回
                    if (ArtExamConstant.END.equals(exam.getStatus())) {
                        result.put("node",ArtExamConstant.SEARCH);
                        result.put("view",ArtExamConstant.SUBMIT);
                        result.put("data",artStudentService.getScore(studentId,examId));
                        return result;
                    }else{
                        result.put("node",ArtExamConstant.SEARCH);
                        result.put("view",ArtExamConstant.SUBMIT);
                        result.put("data",null);
                        return result;
                    }
                }else{
                    //审核状态不为通过的，则不要展示本页面
                    result.put("node",ArtExamConstant.SEARCH);
                    result.put("view",ArtExamConstant.NOSUBMIT);
                    result.put("data",new QueryScoreVo());
                    return result;
                }
            }
        }
    }
    /******------------以下是网页端各tab页涉及的接口----------------***********/

    /**
     * 考生报名-暂存
     * */
    @PutMapping("/webSave/{examId}")
    public AjaxResult webSave(@PathVariable Long examId,@RequestBody WebSchoolArtStudentVo student)
    {
        if(StringUtils.isNull(student.getId())){
            throw new ServiceException("id为空,请检查");
        }
        return toAjax(artStudentService.webSave(examId,student));
    }

    /**
     * 考生报名-提交
     * */
    @PutMapping("/webSubmit/{examId}")
    public AjaxResult webSubmit(@PathVariable Long examId,@RequestBody WebSchoolArtStudentVo student)
    {
        if(StringUtils.isNull(student.getId())){
            throw new ServiceException("id为空,请检查");
        }
        return toAjax(artStudentService.webSubmit(examId,student));
    }


    /**
     * 本次考试下所能选择的测试项目
     * */
    @GetMapping("/getProjectList/{examId}")
    public TableDataInfo getProjectList(@PathVariable Long examId, SchoolTestProject schoolTestProject)
    {
        return getDataTable(projectService.getProjectList(examId,schoolTestProject));
    }

    /**
     * 查询初中学校列表
     */
    @GetMapping("/schoolList")
    public TableDataInfo schoolList(JuniorHighSchool juniorHighSchool)
    {
        List<JuniorHighSchool> list = schoolService.selectJuniorHighSchoolList(juniorHighSchool);
        return getDataTable(list);
    }


    /**
     * 头像上传
     * 将图片上传至PC端所在服务器
     * */
    @PostMapping("/avatar")
    public AjaxResult avatar(MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            Map map = UploadToServer.uploadAvatar(serverAddress,file);
            String avatar = map.get("url").toString();
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", avatar);
            return ajax;
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }
}

