package yangtz.cs.liu.webpage.controller;

import com.core.utils.UploadToServer;
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.model.WebLoginBody;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import yangtz.cs.liu.campus.constant.RecruitExamConstant;
import yangtz.cs.liu.campus.domain.examination.*;
import yangtz.cs.liu.campus.domain.recruit.*;
import yangtz.cs.liu.campus.service.examination.IJuniorHighSchoolService;
import yangtz.cs.liu.campus.service.recruit.*;
import yangtz.cs.liu.webpage.domain.WebRegisterBody;
import yangtz.cs.liu.webpage.vo.RecruitAdmissionTicketVo;
import yangtz.cs.liu.webpage.vo.QueryScoreVo;
import yangtz.cs.liu.webpage.vo.WebSchoolRecruitStudentVo;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

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

    @Autowired
    private ISchoolRecruitStudentService recruitStudentService;

    @Autowired
    private WebTokenService webTokenService;

    @Autowired
    WebStudentInfoUtil studentInfoUtil;

    @Autowired
    private ISchoolRecruitExamService recruitExamService;

    @Autowired
    private ISchoolRecruitRelationService recruitRelationService;

    @Autowired
    private ISchoolRecruitProjectService 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 = recruitStudentService.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 = recruitStudentService.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();
        SchoolRecruitStudent student = recruitStudentService.getById(loginBody.getId());
        //获取PC所在服务器端的图片资源
        if(StringUtils.isNotNull(student.getPhoto()) && !"".equals(student.getPhoto())){
            loginBody.setPhoto(student.getPhoto());
            loginBody.setPhotoData(UploadToServer.getPicFromServer(serverAddress,student.getPhoto()));
        }
        //SchoolRecruitStudent student = recruitStudentService.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(recruitExamService.getRecruitExam(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",recruitStudentService.enterBtn(studentId,testId));
    }

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

    /**
     * 网页进入按钮点击后的界面-点击考前须知
     * examId 当前考试id
     * 返回：所处节点node；返回数据data
     * */
    @GetMapping("/enterPreExam/{examId}")
    public AjaxResult enterPreExam(@PathVariable Long examId)
    {
        AjaxResult result = AjaxResult.success();
        SchoolRecruitExam exam = recruitExamService.getById(examId);
        result.put("node",RecruitExamConstant.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();
        //获取考生与考试关系
        SchoolRecruitRelation relation = recruitRelationService.getRelationByIds(examId,studentId);
        WebSchoolRecruitStudentVo student = recruitStudentService.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",RecruitExamConstant.SIGN);
            result.put("view",RecruitExamConstant.SUBMIT);
            result.put("data",student);
            return result;
        }else {
            //有关联关系,判断关系提交状态是否提交
            //若未提交，则进入报名阶段，返回学生信息
            if(RecruitExamConstant.NOSUBMIT.equals(relation.getSubmit())){
                result.put("node",RecruitExamConstant.SIGN);
                result.put("view",RecruitExamConstant.SUBMIT);
                result.put("data",student);
                return result;
            }else {
                result.put("node",RecruitExamConstant.AUDIT);
                result.put("view",RecruitExamConstant.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();
        //获取考生与考试关系
        SchoolRecruitRelation relation = recruitRelationService.getRelationByIds(examId,studentId);
        //未报名的
        if(StringUtils.isNull(relation)){
            result.put("node",RecruitExamConstant.TICKET);
            result.put("view",RecruitExamConstant.NOSUBMIT);
            result.put("data",new RecruitAdmissionTicketVo());
            return result;
        }else {
            //有关联关系,判断关系提交状态是否提交
            //若未提交，不能显示该页面的信息
            if(RecruitExamConstant.NOSUBMIT.equals(relation.getSubmit())){
                result.put("node",RecruitExamConstant.TICKET);
                result.put("view",RecruitExamConstant.NOSUBMIT);
                result.put("data",new RecruitAdmissionTicketVo());
                return result;
            }else {
                //已提交，判断审核状态，审核状态为通过的才能显示本界面，
                // 审核状态为通过的，要判断当前考试状态是否是成绩发布，只有是此状态才可以返回数据data，
                // 不然则data为空，前端应显示准卡证打印时间未开放
                if(RecruitExamConstant.PASS.equals(relation.getAuditStatus())){
                    SchoolRecruitExam exam = recruitExamService.getById(examId);
                    //审核状态为通过，且考试状态为成绩发布阶段，返回
                    if (RecruitExamConstant.SCORE.equals(exam.getStatus())) {
                        result.put("node",RecruitExamConstant.TICKET);
                        result.put("view",RecruitExamConstant.SUBMIT);
                        RecruitAdmissionTicketVo ticketVo = recruitStudentService.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",RecruitExamConstant.TICKET);
                        result.put("view",RecruitExamConstant.SUBMIT);
                        result.put("data",null);
                        return result;
                    }
                }else{
                    //审核状态不为通过的，则不要展示本页面
                    result.put("node",RecruitExamConstant.TICKET);
                    result.put("view",RecruitExamConstant.NOSUBMIT);
                    result.put("data",new RecruitAdmissionTicketVo());
                    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();
        //获取考生与考试关系
        SchoolRecruitRelation relation = recruitRelationService.getRelationByIds(examId,studentId);
        //未报名的,此页面不展示
        if(StringUtils.isNull(relation)){
            result.put("node",RecruitExamConstant.SEARCH);
            result.put("view",RecruitExamConstant.NOSUBMIT);
            result.put("data",new QueryScoreVo());
            return result;
        }else {
            //有关联关系,判断关系提交状态是否提交
            //若未提交，不能显示该页面的信息
            if(RecruitExamConstant.NOSUBMIT.equals(relation.getSubmit())){
                result.put("node",RecruitExamConstant.SEARCH);
                result.put("view",RecruitExamConstant.NOSUBMIT);
                result.put("data",new QueryScoreVo());
                return result;
            }else {
                //已提交，判断审核状态，审核状态为通过的才能显示本界面，
                // 审核状态为通过的，要判断当前考试状态是否是结束，只有是此状态才可以返回数据data，
                // 不然则data为空，前端应显示成绩暂未发布
                if(RecruitExamConstant.PASS.equals(relation.getAuditStatus())){
                    SchoolRecruitExam exam = recruitExamService.getById(examId);
                    //审核状态为通过，且考试状态为成绩发布阶段，返回
                    if (RecruitExamConstant.END.equals(exam.getStatus())) {
                        result.put("node",RecruitExamConstant.SEARCH);
                        result.put("view",RecruitExamConstant.SUBMIT);
                        result.put("data",recruitStudentService.getScore(studentId,examId));
                        return result;
                    }else{
                        result.put("node",RecruitExamConstant.SEARCH);
                        result.put("view",RecruitExamConstant.SUBMIT);
                        result.put("data",null);
                        return result;
                    }
                }else{
                    //审核状态不为通过的，则不要展示本页面
                    result.put("node",RecruitExamConstant.SEARCH);
                    result.put("view",RecruitExamConstant.NOSUBMIT);
                    result.put("data",new QueryScoreVo());
                    return result;
                }
            }
        }
    }
    /******------------以下是网页端各tab页涉及的接口----------------***********/

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

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


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

    /**
     * 查询初中学校列表
     */
    @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("上传图片异常，请联系管理员");
    }
}

