package cn.hmsoft.skill.data.dao.std;

import java.time.LocalDateTime;

import org.springframework.stereotype.Repository;

import cn.hmsoft.skill.data.model.std.StdRes;
import cn.hmsoft.skill.data.model.std.StdResLog;
import cn.hmsoft.jdbc.core.PlatformDaoSupport;

@Repository
public class EnrolStdResDao extends PlatformDaoSupport<StdRes> {

	private final static String FIND_RES_BY_STD = "select * from std_res where std_id=? and res_type=? ";

	private final static String FIND_RES_BY_WEIXIN = "select * from std_res where weixin_id=? and res_type=? ";

	/*********************
	 * 根据材料类型查找记录
	 * 
	 */
	public StdRes findRes(int std_id, String materail_type) {
		return this.findBySql(FIND_RES_BY_STD, std_id, materail_type);
	}

	private final static String UPDATE_RES_BY_STD = "update std_res set res_number=?,res_date=? where std_id=? and res_type=? ";

	private final static String UPDATE_RES_BY_WEIXIN = "update std_res set res_number=?,res_date=? where weixin_id=? and res_type=? ";

	public StdRes findRes(String weixin_id, String res_type) {
		return this.findBySql(FIND_RES_BY_WEIXIN, weixin_id, res_type);
	}

	/**********************
	 * 记录用户资源使用次数
	 */
	public void updateRecord(StdRes res) {
		StdRes std = null;
		if (res.getStd_id() != null)
			std = this.findRes(res.getStd_id(), res.getRes_type());
		else
			std = this.findRes(res.getWeixin_id(), res.getRes_type());
		if (std == null)
			this.insert(res);
		else {
			if (res.getStd_id() != null) {
				this.updateBySql(UPDATE_RES_BY_STD, res.getRes_number(), res.getRes_date(), std.getStd_id(),
						res.getRes_type());
				
			} else {
				this.updateBySql(UPDATE_RES_BY_WEIXIN, res.getRes_number(), res.getRes_date(), std.getWeixin_id(),
						res.getRes_type());

			}
		}
	}

	/************************
	 * 记录使用资源历史
	 */
	public void logRes(String weixin_id, String res_type, String res_result, String res_desc) {
		StdResLog log = new StdResLog();
		log.setWeixin_id(weixin_id);
		log.setRes_type(res_type);
		log.setRes_result(res_result);
		log.setRes_desc(res_desc);
		log.setRes_time(LocalDateTime.now());
		this.insert(log);
	}

	/************************
	 * 记录使用资源历史
	 */
	public void logRes(StdResLog log) {
		if (log.getRes_time() == null)
			log.setRes_time(LocalDateTime.now());
		this.insert(log);
	}
}
