package checkUtil

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/xuri/excelize/v2"
)

func CheckValuesInExcel(filename, sheetName string, values map[string]int32) (map[string]bool, error) {
	result := make(map[string]bool)

	start := time.Now()
	f, err := excelize.OpenFile(filename)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	logElapsed := func() {
		// record elapsed for this helper
		fmt.Printf("CheckValuesInExcel elapsed=%v\n", time.Since(start))
	}

	// 初始化结果map
	for key := range values {
		result[key] = false
	}

	// 获取所有行
	rows, err := f.GetRows(sheetName)
	if err != nil {
		return nil, err
	}

	// 遍历所有行检查每个值
	for rowNum := 1; rowNum <= len(rows); rowNum++ {
		for col, targetValue := range values {
			// 如果该列已经找到匹配值，跳过检查
			if result[col] {
				continue
			}

			cellAddress := fmt.Sprintf("%s%d", col, rowNum)
			cellValue, err := f.GetCellValue(sheetName, cellAddress)
			if err != nil {
				return nil, err
			}

			// 数值比较
			cellInt, err := strconv.ParseInt(cellValue, 10, 32)
			if int32(cellInt) == targetValue {
				result[col] = true
			}
		}
	}

	logElapsed()
	return result, nil
}

func CheckValuesInTxt(path string) (map[string]string, error) {
	start := time.Now()
	file, err := os.Open(path)
	if err != nil {
		fmt.Printf("无法打开文件: %v", err)
		return nil, err
	}
	defer file.Close()

	categoryMap := make(map[string]string)

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()

		// 跳过空行
		if strings.TrimSpace(line) == "" {
			continue
		}

		// 按冒号分割
		parts := strings.Split(line, "：")

		// 确保分割后有两个部分
		if len(parts) == 2 {
			key := strings.TrimSpace(parts[0])
			value := strings.TrimSpace(parts[1])
			categoryMap[key] = value
		} else {
			fmt.Printf("警告: 无法解析行: %s\n", line)
		}
	}

	// 检查扫描错误
	if err := scanner.Err(); err != nil {
		fmt.Printf("读取文件失败: %v\n", err)
		return nil, err
	}

	// log elapsed (use fmt to avoid importing extra log package here)
	fmt.Printf("CheckValuesInTxt elapsed=%v\n", time.Since(start))
	return categoryMap, nil
}
