
package com.reyun.taskexecute;

import com.reyun.context.AppUtils;
import com.reyun.model.UserGroup;
import com.reyun.service.ReportService;
import com.reyun.util.Constant;
import com.reyun.util.DBUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserGroupThread extends Thread {
	protected static Logger logger = LoggerFactory.getLogger(UserGroupThread.class);

	private ReportService reportService = AppUtils.getApplicationContext().getBean(ReportService.class);


	private UserGroup userGroup;
	private Boolean isExist;

	public UserGroupThread(UserGroup userGroup, Boolean isExist) {
			super();
			this.userGroup = userGroup;
			this.isExist = isExist;
	}

	@Override
	public void run() {
		if (isExist) {
			String deleteSql = "ALTER TABLE " + Constant.usergroupTable + " DROP IF EXISTS PARTITION(id = '"
					+ userGroup.getId() + "')";
			Map<String, String> deleteCondition = new HashMap<String, String>();
			deleteCondition.put("sql", deleteSql);
			deleteCondition.put("dbtype", "hive");
			reportService.execute(deleteSql);
		}

		String querySql = userGroup.getQuerySql();
		String insertSql = "INSERT into " + Constant.usergroupTable + " select DISTINCT(xwho),'xwho','"
				+ userGroup.getId() + "' from (" + querySql + ") t;";
		//String deviceSql = insertSql.replace("xwho", "_deviceid");
		
		String sql = "SELECT count(objectid) as number from " + Constant.usergroupTable + " where id = '"
				+ userGroup.getId() + "' and objecttype='xwho'";
		//String query = insertSql + deviceSql + sql;
		String query = insertSql + sql;
		Map<String, String> conditions = new HashMap<String, String>();
		conditions.put("sql", query);
		conditions.put("dbtype", "presto");
		conditions.put("datatype", "list");

        Map<String, List> result = reportService.reportBySql(conditions);

		Long number = 0L;
		if (result.containsKey("val")) {
			List<Map<String, Object>> valList = result.get("val");
			for (int i = 0; i < valList.size(); i++) {
				Map<String, Object> ob = valList.get(i);
				number = Long.valueOf(ob.get("number").toString());
			}
		}

		try {
			updateNumber(number, userGroup.getId());
		} catch (SQLException e1) {
			try {
				updateStaus(2, userGroup.getId());
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
			}
			logger.error(e1.getMessage(), e1);
		}

		try {
			updateStaus(1, userGroup.getId());
		} catch (SQLException e) {
			logger.error(e.getMessage(), e);
		}
	}

	private static void updateStaus(int status, Long id) throws SQLException {
		String sql = "update user_group set status = " + status + " where id = " + id;
		Connection conn = DBUtil.newInstance().getConn();
		Statement statement = conn.createStatement();
		statement.executeUpdate(sql);
		if (statement != null) {
			statement.close();
		}
		if (conn != null) {
			conn.close();
		}
	}

	private static void updateNumber(Long number, Long id) throws SQLException {
		String sql = "update user_group set number = " + number + " where id = " + id;
		Connection conn = DBUtil.newInstance().getConn();
		Statement statement = conn.createStatement();
		statement.executeUpdate(sql);
		if (statement != null) {
			statement.close();
		}
		if (conn != null) {
			conn.close();
		}
	}
}

