package cn.hmsoft.frame.data.dao;

import java.time.LocalDateTime;

import org.springframework.stereotype.Repository;

import cn.hmsoft.frame.constants.FrameThreadStatus;
import cn.hmsoft.frame.data.model.FrameThread;
import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.jdbc.core.PlatformDaoSupport;
import cn.hmsoft.jdbc.entity.DataRecord;
import cn.hmsoft.jdbc.entity.Pager;
import cn.hmsoft.jdbc.entity.QueryOrder;

@Repository
public class FrameThreadDao extends PlatformDaoSupport<FrameThread> {

	private final static String TOTAL_THREAD = "select count(1) i01,sum(case when create_optr_id=? then 1 else 0 end) i02 from frame_thread where thread_status=?";

	public DataRecord totalThread(Integer optr_id) {
		return this.findBySql(DataRecord.class, TOTAL_THREAD, optr_id, FrameThreadStatus.Running.toString());
	}

	private final static String FIND_THREAD = "select * from frame_thread where create_optr_id=? and thread_name=? and  thread_status=?";

	/*****************
	 * 根据线程名称和操作员，查找线程
	 * 
	 * @param thread_name
	 * @param optr_id
	 * @return
	 */
	public FrameThread findThread(String thread_name, int optr_id) {
		return this.findBySql(FIND_THREAD,  optr_id,thread_name, FrameThreadStatus.Running.toString());
	}

	public void initThread() {
		String sql = "delete from frame_thread where thread_status='Running' ";
		this.updateBySql(sql);
	}
	
	public void clearThread(LocalDateTime time) {
		String sql = "delete from frame_thread where thread_status!='Running' and thread_status_time<?";
		this.updateBySql(sql,time);
	}
	
	public Pager pageThread(Integer start, Integer limit, String query, QueryOrder order) {
		String sql = "select * from frame_thread where 1=1 ";
		if (StringHelper.isEmpty(query)) {
			return this.pageMapBySql(order, start, limit, sql);
		} else {
			sql += "and (thread_name like ? or  thread_notice like ?)";
			String value = this.generateLikeParamter(query);
			return this.pageMapBySql(order, start, limit, sql, value, value);
		}

	}
	
	/**
	 * 重启清空 未完成的线程
	 */
	public void clearRunnningThread() {
		String sql = "delete from frame_thread where thread_status= 'Running' ";
		this.updateBySql(sql);
	}
	
	
}