package cn.hmsoft.skill.school.service;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.hmsoft.frame.util.FrameAssertUtil;
import cn.hmsoft.helper.LocalDateHelper;
import cn.hmsoft.skill.constants.SkillLogType;
import cn.hmsoft.skill.data.dao.school.SchoolLogDao;
import cn.hmsoft.skill.data.dao.school.SchoolRegDao;
import cn.hmsoft.skill.data.model.school.SchoolReg;

@Service
public class SchoolInfoService {

	@Autowired
	private SchoolRegDao daoSchool;

	@Autowired
	private SchoolLogDao daoLog;

	public void save(SchoolReg school) {
		school.setSocket_param(null);
		school.setLogin_pass(null);
		school.setSchool_code(null);

		StringBuilder sb = new StringBuilder();

		SchoolReg ag = this.daoSchool.find(school.getSchool_id());
		sb.append(checkValues("enrol_start", ag.getEnrol_start_time(), school.getEnrol_start_time()));
		sb.append(checkValues("enrol_end", ag.getEnrol_end_time(), school.getEnrol_end_time()));
		sb.append(checkValues("ticket_start", ag.getTicket_start_time(), school.getTicket_start_time()));
		sb.append(checkValues("ticket_end", ag.getTicket_end_time(), school.getTicket_end_time()));

		if (sb.length() > 0) {
			this.daoLog.log(ag.getSchool_id(), SkillLogType.SchoolInfo.toString(), sb.toString());
		}
		this.daoSchool.update(school);

	}

	public void pass(int school_id, String old_pass, String new_pass) {
		SchoolReg s = this.daoSchool.find(school_id);
		FrameAssertUtil.isEqual(old_pass, s.getLogin_pass(), "输入的旧密码不正确！");
		this.daoLog.log(school_id, SkillLogType.Password.toString(), new_pass, s.getLogin_pass(), LocalDateTime.now());
		SchoolReg sc = new SchoolReg();
		sc.setSchool_id(school_id);
		sc.setLogin_pass(new_pass);
		this.daoSchool.update(sc);
	}

	private String checkValues(String type, LocalDateTime o, LocalDateTime n) {
		if (o == null && n == null)
			return "";
		String o1 = o == null ? "" : LocalDateHelper.format(o);
		String n1 = n == null ? "" : LocalDateHelper.format(n);
		if (o1.equals(n1))
			return "";
		return type + "：" + o1 + " ->  " + n1 + System.lineSeparator();

	}
}
