package main

import (
	"fmt"
	"strconv"
	"sync"
	"testing"
	dbutil "tiloader/pkg/dbutil"
	fileutil "tiloader/pkg/fileutil"
	log "tiloader/pkg/logutil"
)

func TestGenSqlInPool(t *testing.T) {
	log.InitLog("tiloader.log", "tiloader_err.log")
	var wg sync.WaitGroup
	//rowDataChan := make(chan fileuitl.RowData, 10)
	readChan := make(chan string, 10)
	sqlChan := make(chan dbutil.SqlInfo, 10)

	const DATA_COUNT = 10
	const BATCH_SIZE = 1000
	go func() {
		for i := 0; i < DATA_COUNT; i++ {
			//time.Sleep(time.Second)
			readChan <- "20210901ZYZYG00000000001ZYKFG1020210901131532JYZHZYG00000001  ZYG      00000001000000000000000100000000022            10000QZYG00000001           156ZYG                              202109011000000020210901                    20210901                    00000                 0000000000                              0000000000000000                                                                  00000000000000000                   20210901                                                                                   00                                                          00000 0000000000000000    00000                       00000000000000000000000000"
			fmt.Printf("========")
			fmt.Println(len(readChan))
		}
		close(readChan)
	}()

	col1Info := fileutil.ColInfo{"col_1", 1, 24}
	col2Info := fileutil.ColInfo{"col_2", 25, 30}
	col3Info := fileutil.ColInfo{"col_3", 31, 31}

	mycols := [...]fileutil.ColInfo{col1Info, col2Info, col3Info}

	descFile := fileutil.DescFile{
		DataFileName: "",
		TableName:    "Test",
		Method:       0,
		Cols:         mycols[:],
	}

	wg.Add(1)

	cfg := fileutil.ConfigFile{}
	cfg.User = "root"
	cfg.Password = "xxx"
	cfg.Host = "172.16.4.8"
	cfg.Port = 5000
	cfg.Schema = "wuchao_db"
	cfg.WorkerNum = 100

	genSqlInPool(readChan, descFile, sqlChan, &wg, cfg)

	sqlCount := 0

	for sql := range sqlChan {
		sqlCount++
		t.Logf("=============:" + sql.SqlHalf1 + sql.SqlHalf2)
	}
	wg.Wait()
	fmt.Println("sql count:" + strconv.Itoa(sqlCount))
	if (DATA_COUNT/BATCH_SIZE + 1) != sqlCount {
		t.Fatalf("TestGenSqlInPool fail, data size error.")
	}
	t.Logf("TestGenSqlInPool success")

}

func TestExecSqlInPool(t *testing.T) {
	sqlChan := make(chan dbutil.SqlInfo, 10)
	var wg sync.WaitGroup
	const DATA_COUNT = 10
	wg.Add(1)
	go func() {
		for i := 0; i < DATA_COUNT; i++ {
			curval := i
			sql := dbutil.SqlInfo{}
			sql.SqlHalf1 = "insert into test(col_1, col_2,col_3)values"
			sql.SqlHalf2 = "(?,?,?)"
			sql.Param = []string{"tt" + strconv.Itoa(curval), "t" + strconv.Itoa(curval), "t"}
			sqlChan <- sql
		}
		close(sqlChan)
		wg.Done()
	}()

	wg.Add(1)

	cfg := fileutil.ConfigFile{}
	cfg.User = "root"
	cfg.Password = "xxx"
	cfg.Host = "172.16.4.8"
	cfg.Port = 5000
	cfg.Schema = "wuchao_db"
	cfg.WorkerNum = 100

	descFile := fileutil.DescFile{
		DataFileName: "",
		TableName:    "Test",
		Method:       0,
	}

	execSqlInPool(sqlChan, cfg, &wg, descFile)
	wg.Wait()
	t.Logf("TestExecSqlInPool success")

}
