package cn.hmsoft.skill.service.cf;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.hmsoft.frame.data.model.FrameOptr;
import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.frame.util.FrameAssertUtil;
import cn.hmsoft.helper.JsonHelper;
import cn.hmsoft.jdbc.entity.Pager;
import cn.hmsoft.jdbc.entity.QueryOrder;
import cn.hmsoft.skill.constants.SkillLogType;
import cn.hmsoft.skill.data.dao.school.SchoolRegDao;
import cn.hmsoft.skill.data.model.school.SchoolAspect;
import cn.hmsoft.skill.data.model.school.SchoolReg;
import cn.hmsoft.skill.service.SkillService;

@Service
public class SchoolRegService extends SkillService {

	@Autowired
	private SchoolRegDao schoolRegDao;
	
	Pager pageSchoolReg(Integer school_id, Integer start, Integer limit, String query, QueryOrder order) {
		return this.schoolRegDao.pageSchoolReg(school_id, start, limit, query, order);
	}
	
	private void validValues(SchoolReg agent) {
		FrameAssertUtil.isNotNull(agent.getSchool_code(), "考点编号不能为空");
		FrameAssertUtil.isNotNull(agent.getSchool_name(), "学校名称不能为空");
		FrameAssertUtil.isNotNull(agent.getEnrol_start_time(), "该考点开放了报名，报名开始时间不能为空");
		FrameAssertUtil.isNotNull(agent.getEnrol_end_time(), "该考点开放了报名，报名结束时间不能为空");
	}
	
	/************************
	 * 新增考点
	 */
	public void addSchoolReg(SchoolReg agent, FrameOptr optr) {
		this.validValues(agent);
		// 判断编号是否存在
		agent.setSchool_id(optr.getOrg_id());
		FrameAssertUtil.isNull(this.schoolRegDao.find(agent.getSchool_id()), "编号【" + agent.getSchool_id() + "】的考点已经存在，请修改");
		// 判断编号是否存在
		FrameAssertUtil.isNull(this.schoolRegDao.find("school_name", agent.getSchool_name()), "名称【" + agent.getSchool_name() + "】的考点已经存在，请修改");
		this.schoolRegDao.insert(agent);
		this.log(optr, SkillLogType.ConfAgent_Add.toString(), JsonHelper.fromObject(agent));
	}

	public void editSchoolReg(SchoolReg agent, FrameOptr optr) {
		this.validValues(agent);
		// 判断编号是否存在
		SchoolReg cg = this.schoolRegDao.find("school_name", agent.getSchool_name());
		if (cg != null && cg.getSchool_id() - agent.getSchool_id() != 0)
			throw new BusinessException("名称【" + agent.getSchool_name() + "】的考点已经存在，请修改");
		// 判断编号是否存在
		this.schoolRegDao.update(agent);
		this.log(optr, SkillLogType.ConfAgent_Edit.toString(), JsonHelper.fromObject(agent));
		
	}

	public void deleteSchoolReg(int agent_id, FrameOptr optr) {
		SchoolReg agent = this.schoolRegDao.find(agent_id);
		FrameAssertUtil.isNotNull(agent, "未找到该考点,数据同步错误，请重新登录");
		this.schoolRegDao.delete(SchoolAspect.class, "agent_id", agent_id);
		this.schoolRegDao.delete(SchoolReg.class, "agent_id", agent_id);
		this.log(optr, SkillLogType.ConfAgent_Delete.toString(), JsonHelper.fromObject(agent));
	}
}
