package controller

import (
	"log"
	"strings"
	"time"

	"github.com/gofiber/fiber/v3"
)

var sixunFilePath = "/Users/panjunjie/work/fafa_library/sixun/"

// SyncSiXunGoodsData 处理思迅爬取的数据，上传到小发同城图片库
func (c *Controller) SyncSiXunGoodsData(ctx fiber.Ctx) error {
	start := time.Now()
	// 直接解析请求参数（Fiber v3自动处理JSON/表单）
	var params struct {
		Folders []string `json:"folders" form:"folders"` // 图片源目录路径
	}

	if err := ctx.Bind().JSON(&params); err != nil {
		return ctx.Status(fiber.StatusBadRequest).JSON(Error(fiber.StatusBadRequest, "无效的请求参数"))
	}
	if len(params.Folders) == 0 {
		return ctx.Status(fiber.StatusBadRequest).JSON(Error(fiber.StatusBadRequest, "请提供图片源目录路径"))
	}

	successCnt := 0
	totalSrcDataCnt := int64(0)
	totalFilteredDataCnt := int64(0)
	totalSavedDataCnt := int64(0)
	totalFilteredImgCnt := int64(0)

	if !strings.HasSuffix(sixunFilePath, "/") {
		sixunFilePath += "/"
	}

	for _, folder := range params.Folders {
		path := sixunFilePath + folder

		// 处理思迅商品数据
		srcDataCnt, filteredDataCnt, savedDataCnt, filteredImgCnt := sxGoodsService.ProcessSiXunGoodsData(path)

		// 累计统计数据
		totalSrcDataCnt += srcDataCnt
		totalFilteredDataCnt += filteredDataCnt
		totalSavedDataCnt += savedDataCnt
		totalFilteredImgCnt += filteredImgCnt

		// 如果成功保存了数据，则增加成功计数
		if savedDataCnt > 0 {
			successCnt++
		}

		// 记录每个文件夹的处理日志
		log.Printf("文件夹 %s 处理完成: 源数据%d条，过滤后数据%d条，保存成功%d条，有效图片%d张",
			folder, srcDataCnt, filteredDataCnt, savedDataCnt, filteredImgCnt)
	}

	elapsed := time.Since(start)

	// 记录总体处理日志
	log.Printf("思迅商品数据同步完成: 处理%d个文件夹，源数据%d条，过滤后数据%d条，保存成功%d条，有效图片%d张，耗时%s",
		len(params.Folders), totalSrcDataCnt, totalFilteredDataCnt, totalSavedDataCnt, totalFilteredImgCnt, elapsed.String())

	return ctx.JSON(Success(fiber.Map{
		"success_count":       successCnt,
		"folder_count":        len(params.Folders),
		"elapsed_time":        elapsed.String(),
		"total_src_data":      totalSrcDataCnt,
		"total_filtered_data": totalFilteredDataCnt,
		"total_saved_data":    totalSavedDataCnt,
		"total_filtered_img":  totalFilteredImgCnt,
	}))
}
