package cn.hmsoft.frame.thread;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.time.LocalDateTime;

import cn.hmsoft.frame.constants.FrameThreadStatus;
import cn.hmsoft.frame.data.model.FrameThread;
import cn.hmsoft.helper.LocalDateHelper;

/***************
 * 线程测试类
 * 
 * @author zxq
 * @create 2019-06-29 10:56:08
 * @version 2.0.0
 * @email: revisit@126.com
 * @Company: www.hmsoft.cn
 */
public class FrameThreadTest implements Runnable {

	/*******************
	 * 线程总时长
	 */
	private int total_seconds;
	/******************
	 * 线程更新时间间隔
	 */
	private int interval_seconds;

	private File file;

	FrameThread thread;

	public FrameThreadTest(FrameThread thread, Integer total_seconds, Integer interval_seconds, File file) {
		this.total_seconds = total_seconds == null ? 30 : total_seconds;
		this.interval_seconds = interval_seconds == null ? 5 : interval_seconds;
		this.file = file;
		this.thread = thread;
	}

	@Override
	public void run() {
		int v = 0, runs = 0;
		try {
			file.delete();
		} catch (Exception e) {

		}
		while (v < total_seconds) {
			runs++;
			v = v + interval_seconds;
			try {
				Thread.sleep(this.interval_seconds * 1000);
			} catch (Exception e) {

			}
			try {
				PrintWriter out = new PrintWriter(new FileOutputStream(file, true));
				out.println(LocalDateHelper.format(LocalDateTime.now()) + "：线程运行中：已经运行了【" + runs + "】次，耗时【" + v + "】秒");
				out.close();
			} catch (Exception e) {

			}
			if (runs > 3) {
				// 第三次的时候，随机发生错误
				if (Math.random() > 0.8) {
					FrameThreadHelper.updateThread(thread, 100, "线程异常结束：共运行了【" + runs + "】次，耗时【" + v + "】秒",
							FrameThreadStatus.Error);
					return;
				}
			}
			FrameThreadHelper.updateThread(thread, v * 100 / total_seconds, "线程运行中：已经运行了【" + runs + "】次，耗时【" + v + "】秒",
					FrameThreadStatus.Running);

		}

		FrameThreadHelper.updateThread(thread, 100, "线程正常结束：共运行了【" + runs + "】次，耗时【" + v + "】秒",
				FrameThreadStatus.Complete);

		try {
			Thread.sleep(interval_seconds * 1000);
		} catch (Exception e) {

		}
	}

}
