package com.steering.pss.plnsaleord.processOrder;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.processOrder.base.ProducHelperBean;
import com.steering.pss.plnsaleord.processOrder.entity.PlnOrderJgxSEntity;
import com.steering.pss.plnsaleord.processOrder.entity.PlnOrderRclSEntity;

import CoreFS.SC01.CoreConstantData;

public class AutomaticModifyJGXPlanEndTime extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MyThread1 myThread1;

	public AutomaticModifyJGXPlanEndTime() {
	}

	public void init() {
		String str = null;
		if (str == null && myThread1 == null) {
			myThread1 = new MyThread1();
			myThread1.start(); // servlet 上下文初始化时启动 socket
		}
	}

	public void doGet(HttpServletRequest httpservletrequest,
			HttpServletResponse httpservletresponse) throws ServletException,
			IOException {
	}

	public void destory() {
		if (myThread1 != null && myThread1.isInterrupted()) {
			myThread1.interrupt();
		}
	}
}

/**
 * 自定义一个 Class 线程类继承自线程类，重写 run() 方法，用于从后台获取并处理数据
 * 
 * @author Champion.Wong
 * 
 */
class MyThread1 extends Thread {
	public void run() {
		while (!this.isInterrupted()) {// 线程未中断执行循环
			try {
				// 1小时执行一次
				Thread.sleep(1000 * 60 * 60 * 4);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			// ------------------ 开始执行 ---------------------------
			// 获取当前时间
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.HOUR_OF_DAY, 6); // 凌晨6点
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			Date date = calendar.getTime(); // 第一次执行定时任务的时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			System.out.println("设定时间:" + sdf.format(date));
			// 如果第一次执行定时任务的时间 小于当前的时间
			// 此时要在 第一次执行定时任务的时间加一天，以便此任务在下个时间点执行。如果不加一天，任务会立即执行。
			Date now = new Date();
			if (date.before(now)) {
				ModifyTime modifyTime = new ModifyTime();
				try {
					modifyTime.InitPlanTimeG(sdf.format(date));
					modifyTime.InitPlanTimeF(sdf.format(date));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

}

/**
 * 需要定时执行的方法
 * 
 * @author Administrator
 * 
 */
class ModifyTime extends DBCommon {
	/**
	 * 自动刷新加工时间
	 * 
	 * @param dateTime
	 * @throws Exception
	 */
	public void InitPlanTimeG(String dateTime) throws Exception {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String querySql = "SELECT * FROM PLN_ORDER_JGX_S T WHERE  t.EXE_STATUS='1' order by t.pline_code";
		String sql = "update PLN_ORDER_JGX_S t set t.PLAN_TIME_E=to_date(?,'YYYY-MM-DD HH24:MI:SS') where t.EXE_STATUS='1' AND  T.PLINE_CODE=?";
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			ps = con.prepareStatement(querySql);
			rs = ps.executeQuery();
			List<PlnOrderJgxSEntity> entitys = null;
			if (rs.next()) {
				entitys = EntityTool.getEntitysByRs(rs,
						PlnOrderJgxSEntity.class);
			}
			rs.close();
			ps.close();
			if (entitys == null || entitys.size() == 0) {
				return;
			}
			con.setAutoCommit(false);
			for (PlnOrderJgxSEntity entity : entitys) {
				if (ModifyTime.compareDate(entity.getPlanTimeE(), dateTime)) {
					ps = con.prepareStatement(sql);
					ps.setObject(1, dateTime);
					ps.setObject(2, entity.getPlineCode());
					ps.executeUpdate();
					ps.close();
					ProducHelperBean helperBean = new ProducHelperBean();
					helperBean.timeIncrease(con,
							Integer.parseInt(entity.getGxProSeq()),
							entity.getPlineCode(), dateTime, "G");
				}
			}
			con.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e) {
					System.out.println(e.toString());
				}
			}
		}
	}

	/**
	 * 自动刷新热处理时间
	 * 
	 * @param dateTime
	 * @throws Exception
	 */
	public void InitPlanTimeF(String dateTime) throws Exception {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String querySql = "SELECT * FROM PLN_ORDER_RCL_S T WHERE  t.EXE_STATUS='1' order by t.pline_code";
		String sql = "update PLN_ORDER_RCL_S t set t.PLAN_TIME_E=to_date(?,'YYYY-MM-DD HH24:MI:SS') where t.EXE_STATUS='1' AND  T.PLINE_CODE=?";
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			ps = con.prepareStatement(querySql);
			rs = ps.executeQuery();
			List<PlnOrderRclSEntity> entitys = null;
			if (rs.next()) {
				entitys = EntityTool.getEntitysByRs(rs,
						PlnOrderRclSEntity.class);
			}
			rs.close();
			ps.close();
			if (entitys == null || entitys.size() == 0) {
				return;
			}
			con.setAutoCommit(false);
			for (PlnOrderRclSEntity entity : entitys) {
				if (ModifyTime.compareDate(entity.getPlanTimeE(), dateTime)) {
					ps = con.prepareStatement(sql);
					ps.setObject(1, dateTime);
					ps.setObject(2, entity.getPlineCode());
					ps.executeUpdate();
					ps.close();
					ProducHelperBean helperBean = new ProducHelperBean();
					helperBean.timeIncrease(con,
							Integer.parseInt(entity.getGxProSeq()),
							entity.getPlineCode(), dateTime, "F");
				}
			}
			con.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e) {
					System.out.println(e.toString());
				}
			}
		}
	}

	public static boolean compareDate(String date1, String date2) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		try {
			Date dt1 = df.parse(date1);
			Date dt2 = df.parse(date2);
			if (dt1.getTime() > dt2.getTime()) {
				return false;
			} else if (dt1.getTime() < dt2.getTime()) {

				return true;
			} else {
				return true;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return false;
	}
}
