package com.ruoyi.aicall.utils;

import com.ruoyi.aicall.domain.CcCallPhone;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.apache.shiro.util.JdbcUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * sql异步执行队列
 */
public class ProcessSQLQueue {
	private static  final Logger log = LoggerFactory.getLogger(ProcessSQLQueue.class);

	private static Object addSQLQueueLocker  = new Object();

	private static List<String> sqlList = new ArrayList<>(300);

	static {
		new Thread(
				new Runnable() {
					@Override
					public void run() {
						ProcessSQLQueue();
					}
				} , "processSQLQueue").start();
	}

	/**
	 *
	 * @param sql
	 */
	public static void addSql(String sql) {
		synchronized (addSQLQueueLocker) {
			sqlList.add(sql);
		}
	}

	private static void ProcessSQLQueue(){

		while (true) {
			List<String> toExec = null;

			/* 1. 把当前队列一次性整体“搬走” */
			synchronized (addSQLQueueLocker) {
				if (!sqlList.isEmpty()) {
					toExec = new ArrayList<>(sqlList);
					sqlList.clear();
				}
			}

			/* 2. 真正执行 SQL */
			if (toExec != null && !toExec.isEmpty()) {
				Connection conn = null;
				Statement stmt = null;
				try {
					conn = DataSourceUtils.getConnection(SpringUtils.getBean(DataSource.class));
					conn.setAutoCommit(false);          // 手动事务
					stmt = conn.createStatement();
					for (String sql : toExec) {
						stmt.addBatch(sql);
					}
					stmt.executeBatch();
					conn.commit();                      // 全部成功再提交
					log.info("成功批量执行 {} 条计费 SQL", toExec.size());
				} catch (Exception e) {
					if (conn != null) {
						try { conn.rollback(); } catch (SQLException r) { /* ignore */ }
					}
					log.error("执行 sql 异常：{}", ExceptionUtil.getExceptionMessage(e));
				} finally {
					JdbcUtils.closeStatement(stmt);
					DataSourceUtils.releaseConnection(conn, SpringUtils.getBean(DataSource.class));
				}
			}

			/* 3. 歇 10 秒 */
			try {
				Thread.sleep(10_000L);
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
				break;
			}
		}
	}
}