package cn.hmsoft.skill.enrol.control;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hmsoft.application.web.Ajax;
import cn.hmsoft.application.web.AjaxControl;
import cn.hmsoft.application.web.BrowserAgent;
import cn.hmsoft.frame.util.FrameAgentUtil;
import cn.hmsoft.frame.util.FrameAssertUtil;
import cn.hmsoft.frame.util.FrameIdCardUtil;
import cn.hmsoft.frame.util.FrameRandomCodeUtil;
import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.skill.constants.SkillLoginError;
import cn.hmsoft.skill.constants.StdMateialType;
import cn.hmsoft.skill.data.dao.school.SchoolRegDao;
import cn.hmsoft.skill.data.dao.std.StdRegDao;
import cn.hmsoft.skill.data.model.school.SchoolReg;
import cn.hmsoft.skill.data.model.std.StdReg;
import cn.hmsoft.skill.enrol.service.EnrolStdLoginService;
import cn.hmsoft.skill.enrol.service.EnrolStdRegService;
import cn.hmsoft.skill.helper.SkillParamHelper;

/*********************
 * 考生登录和登出
 * 
 * @author zxq
 * @create 2018-10-30 08:24:16
 * @version 5.0.0
 * @email: revisit@126.com
 * @Company: www.hmsoft.cn
 */
@RestController
public class EnrolStdLoginControl extends AjaxControl {
	@Autowired
	private EnrolStdLoginService stdLoginService;
	@Autowired
	private EnrolStdRegService stdRegService;
	@Autowired
	private SchoolRegDao daoSchool;
	@Autowired
	private StdRegDao stdRegDao;

	@RequestMapping("/enrol/code/generate")
	public void generate(String valid_code) {
		FrameRandomCodeUtil.generateRandomCode(this.getRequest(), this.getResponse(), 4);
	}

	@RequestMapping("/enrol/code/valid")
	public Ajax valid(String valid_code) {
		return new Ajax(FrameRandomCodeUtil.validRandomCode(this.getRequest(), valid_code, false));
	}

	/******************************
	 * 高考报名号登陆 考生登陆，通过success判断是否登录成功，如果不成功,判断errorCode
	 */
	@RequestMapping("/enrol/std/loginByExamId")
	public Ajax loginByExamId(String cert_id, String exam_id, Integer school_id, String valid_code) {
		FrameAssertUtil.checkParam(cert_id, exam_id, school_id);
		Ajax ajax = new Ajax();
		ajax.setSuccess(false);

		// 验证码
		if (!FrameIdCardUtil.validateIdCard18(cert_id)) {
			ajax.setErrorCode(SkillLoginError.CartIdNotVaild);
			ajax.setErrorMsg("身份证号码验证失败，请重试！");
			return ajax;
		}
		BrowserAgent agent = FrameAgentUtil.getBrowserAgent(this.getRequest());

		// 判断是否开启验登录验证
		if (SkillParamHelper.StdLoginWithVaildCode && !SkillParamHelper.AppDebug) {
			// 为了后续注册，这里不要清除验证码信息
			boolean flag = FrameRandomCodeUtil.validRandomCode(this.getRequest(), valid_code, false);
			if (!flag) {
				ajax.setErrorCode(SkillLoginError.CodeNotVaild);
				return ajax;
			}
		}

		// 判断是否在非正常时间登录
		String timeString = this.stdLoginService.checkLoginTime(agent);
		if (!StringHelper.isEmpty(timeString)) {
			ajax.setErrorCode(SkillLoginError.NotBusinessTime);
			ajax.setErrorMsg(timeString);
			return ajax;
		}

		SchoolReg school = this.daoSchool.find(school_id);
		FrameAssertUtil.isNotNull(school, "未找到指定的报考学校！");
		school.setSocket_param(null);

		cert_id = cert_id.trim().toUpperCase();

		// StdReg std = this.daoSchool.find(StdReg.class, "cert_id", cert_id);
		StdReg std = stdRegDao.findByCert(cert_id, school_id);

		// 判断考生是否不存在
		if (std == null) {
			ajax.setErrorCode(SkillLoginError.CertIdNotExist);
			return ajax;
		}

		// 判断高考报名号（考生号）是否一致
		exam_id = exam_id.trim().toUpperCase();
		if (!exam_id.equals(std.getExam_id())) {
			ajax.setErrorCode(SkillLoginError.ExamIdNotVaild);
			return ajax;
		}

		// 登录逻辑处理
		this.stdLoginService.login(school, std, agent);
		this.stdRegService.transStdInfo(std);

		// 删除所有session
		this.getRequest().getSession().invalidate();

		// 保存考生信息进session信息
		this.getSession().setAttribute(SkillParamHelper.SessionName_StdReg, std);
		this.getSession().setAttribute(SkillParamHelper.SessionName_SchoolReg, school);
		if (std.getStd_image() != null)
			std.setStd_image(
					SkillParamHelper.MateialWebPath + "/" + StdMateialType.StdUpload + "/" + std.getStd_image());
		return new Ajax(std);
	}

	/******************************
	 * 高考报名号登陆 考生登陆，通过success判断是否登录成功，如果不成功,判断errorCode
	 */
	@RequestMapping("/enrol/std/loginByPasswd")
	public Ajax loginByPasswd(String cert_id, String password, Integer school_id, String valid_code) {
		FrameAssertUtil.checkParam(cert_id, password, school_id);
		Ajax ajax = new Ajax();
		ajax.setSuccess(false);

		// 验证码
		if (!FrameIdCardUtil.validateIdCard18(cert_id)) {
			ajax.setErrorCode(SkillLoginError.CartIdNotVaild);
			ajax.setErrorMsg("身份证号码验证失败，请重试！");
			return ajax;
		}
		BrowserAgent agent = FrameAgentUtil.getBrowserAgent(this.getRequest());

		// 判断是否开启验登录验证
		if (SkillParamHelper.StdLoginWithVaildCode && !SkillParamHelper.AppDebug) {
			// 为了后续注册，这里不要清除验证码信息
			boolean flag = FrameRandomCodeUtil.validRandomCode(this.getRequest(), valid_code, false);
			if (!flag) {
				ajax.setErrorCode(SkillLoginError.CodeNotVaild);
				return ajax;
			}
		}

		// 判断是否在非正常时间登录
		String timeString = this.stdLoginService.checkLoginTime(agent);
		if (!StringHelper.isEmpty(timeString)) {
			ajax.setErrorCode(SkillLoginError.NotBusinessTime);
			ajax.setErrorMsg(timeString);
			return ajax;
		}

		SchoolReg school = this.daoSchool.find(school_id);
		FrameAssertUtil.isNotNull(school, "未找到指定的报考学校！");
		school.setSocket_param(null);

		cert_id = cert_id.trim().toUpperCase();
		StdReg std = this.stdRegDao.findByCertAndPasswd(cert_id, password, school_id);

		// 判断考生是否不存在
		if (std == null) {
			ajax.setErrorCode(SkillLoginError.CertIdNotExist);
			return ajax;
		}
		std.setConfirm_time(LocalDateTime.now());

		// 判断高考报名号（考生号）是否一致
		/*
		 * exam_id = exam_id.trim().toUpperCase(); if
		 * (!exam_id.equals(std.getExam_id())) {
		 * ajax.setErrorCode(SkillLoginError.ExamIdNotVaild); return ajax; }
		 */

		// 登录逻辑处理
		this.stdLoginService.login(school, std, agent);
		this.stdRegService.transStdInfo(std);

		// 删除所有session
		this.getRequest().getSession().invalidate();

		// 保存考生信息进session信息
		this.getSession().setAttribute(SkillParamHelper.SessionName_StdReg, std);
		this.getSession().setAttribute(SkillParamHelper.SessionName_SchoolReg, school);
		if (std.getStd_image() != null)
			std.setStd_image(
					SkillParamHelper.MateialWebPath + "/" + StdMateialType.StdUpload + "/" + std.getStd_image());
		return new Ajax(std);
	}

	/**
	 * 考生登出
	 */
	@RequestMapping("/enrol/std/logout")
	public void logout() {
		this.getRequest().getSession().invalidate();
	}

	/**
	 * 学校信息查询
	 */
	@RequestMapping("/enrol/std/school")
	public Ajax school(int school_id) {
		return new Ajax(this.daoSchool.find(SchoolReg.class, school_id));
	}

}
