package com.product.data.sync.util;

import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.util.CallBack;
import com.product.util.CallBackValue;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class ThreadSelectManager {

    private Map<Integer, CustomResultSet> pageResultSet = new HashMap<>();
    /**
     * 寮€濮嬫煡璇㈤〉鏁�
     */
    private int startPage;

    private ExecutorService executorService;

    private Connection sourceConnection;

    private CallBackValue<String> getQuerySql;

    private int totalPage = 0;

    private CallBack<Object> setColumnNames;

    private CallBackValue<String[]> getColumnNames;


    public ThreadSelectManager(BatchData batchData) {
        this.getQuerySql = (o) -> batchData.getQuerySql((int) o);
        this.setColumnNames = (o) -> {
            batchData.setColumnNames((String[]) o);
        };
        this.getColumnNames = (o) -> batchData.getColumnNames();
        this.sourceConnection = ConnectionManager.getConnection();
        this.totalPage = batchData.getTotalPage();
        this.currentResult = 1;
    }

    /**
     * 褰撳墠浠ヨ幏鍙栫鍑犻〉
     */
    private int currentResult = -1;

    private boolean openLog = true;

    /**
     * 寮€濮嬫煡璇�
     *
     * @return
     */
    public boolean startQuery() {
        //涓嶈兘閲嶅寮€濮嬫煡璇�
        if (this.pageResultSet.size() <= 0 && this.executorService == null) {
            this.executorService = Executors.newFixedThreadPool(1);
            this.queryData();
            return true;
        }
        return false;
    }

    /**
     * 鑾峰彇涓嬩竴椤垫暟鎹�
     *
     * @return
     */
    public CustomResultSet getNext() {
        if (this.currentResult == -1) {
            return null;
        }
        int page = this.currentResult;
        if (this.pageResultSet.get(page) != null) {
            this.currentResult++;
            return this.pageResultSet.get(page);
        } else {
            if (!this.executorService.isTerminated()) {
                try {
                    outPutLog("绛夊緟绾跨▼涓煡璇㈡暟鎹�....", 1);
                    Thread.currentThread().sleep(1500);
                    return this.getNext();
                } catch (Exception e) {
                    outPutLog("绛夊緟绾跨▼涓煡璇㈡暟鎹紝鍑洪敊....", 2);
                    SpringMVCContextHolder.getSystemLogger().error(e);
                    return null;
                }
            } else {
                this.currentResult++;
                outPutLog("鏌ヨ鏁版嵁绾跨▼宸茬粨鏉燂紝娌℃湁 " + page + " 鏁版嵁", 1);
                return null;
            }
        }
    }

    public static void main(String[] args) {
        int total = 3313;
        int i1 = total / 3;
        String[] ints = new String[3];
        for (int i = 1; i <= 3; i++) {
        }
    }

    /**
     * 鏌ヨ鏁版嵁
     */
    private void queryData() {
        outPutLog("寮€濮嬬嚎绋嬫煡璇㈡暟鎹紝闇€瑕佹煡璇細" + totalPage + " 椤垫暟鎹�", 1);
//        for (int i = 0; i < 3; i++) {
        this.executorService.execute(() -> {
            try {
                int currentPage = 1;
                while (totalPage > 0) {
                    outPutLog("寮€濮嬫煡璇㈤〉鏁帮細" + currentPage, 1);
                    String querySql = getQuerySql.method(currentPage);
                    outPutLog("鏌ヨsql锛歕n\t" + querySql, 1);
                    PreparedStatement pst = sourceConnection.prepareStatement(querySql);
                    ResultSet resultSet = pst.executeQuery();
                    if (resultSet != null) {
                        String[] columnNames = this.getColumnNames.method(null);
                        CustomResultSet customResultSet = new CustomResultSet(resultSet, columnNames);
                        if (columnNames == null || columnNames.length <= 0) {
                            this.setColumnNames.method(customResultSet.getColumnNames());
                        }
                        this.pageResultSet.put(currentPage, customResultSet);
                    }
                    currentPage++;
                    this.totalPage--;
                }
            } catch (Exception e) {
                e.printStackTrace();
                outPutLog("绾跨▼绾跨▼鏌ヨ鏁版嵁锛屽嚭閿�....", 2);
                SpringMVCContextHolder.getSystemLogger().error(e);
            }
        });
//        }
        this.executorService.shutdown();
    }

    /**
     * 杈撳嚭鏃ュ織
     *
     * @param msg  娑堟伅
     * @param type 绫诲瀷  1 info 2 error
     */
    private void outPutLog(String msg, int type) {
        if (this.openLog) {
            if (type == 1) {
                SpringMVCContextHolder.getSystemLogger().info(msg);
            } else if (type == 2) {
                SpringMVCContextHolder.getSystemLogger().error(msg);
            }
        }
    }


}