package ocr

import (
	"encoding/base64"
	"git.listensoft.net/tool/jspkit/logger"
	"net/http"
	"os"
	"time"

	"git.listensoft.net/tool/jspkit/common"
	"git.listensoft.net/tool/jspkit/common/lxhttp"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/tidwall/gjson"
)

func GetCaptchaCodeBeijing(imgPath string) string {
	var client = http.Client{}
	client.Timeout = time.Duration(time.Second * 15)
	tyURL := "https://public.listensoft.net/api/getCaptchaApi"
	res, err := common.PostFile(tyURL, map[string]string{"file": imgPath}, map[string]string{"type": "1002"})
	if err != nil {
		logger.Info(err.Error())
		return ""
	}
	logger.Info("北京图片验证码:" + string(res))
	return string(res)
}

func GetCaptchaCodeHebei(imgPath string) string {
	var client = http.Client{}
	client.Timeout = time.Duration(time.Second * 15)
	tyURL := "https://public.listensoft.net/api/getCaptchaApi"
	res, err := common.PostFile(tyURL, map[string]string{"file": imgPath}, map[string]string{"type": "1001"})
	if err != nil {
		logger.Info(err.Error())
		return ""
	}
	logger.Info("河北图片验证码:" + string(res))
	return string(res)
}

func GetX(captchaPathJpg, captchaPathPng string) float64 {
	u := "http://47.104.147.97:5000/getX"
	files := map[string]string{
		"target":   captchaPathJpg,
		"template": captchaPathPng,
	}
	bys, err := common.PostFile(u, files, map[string]string{})
	if err != nil {
		return 0
	}
	if gjson.Get(string(bys), "error").Int() != 0 {
		return 0
	}
	X := gjson.Get(string(bys), "msg").Float()
	return X
}

func GetXPython(captchaPathJpg, captchaPathPng string) float64 {
	var encodedJpg, encodedPng string
	{
		imgData, err := os.ReadFile(captchaPathJpg)
		if err != nil {
			log.Fatal(err)
		}

		// 将图片数据编码为 Base64
		encodedJpg = base64.StdEncoding.EncodeToString(imgData)
		imgData, err = os.ReadFile(captchaPathPng)
		if err != nil {
			log.Fatal(err)
		}

		// 将图片数据编码为 Base64
		encodedPng = base64.StdEncoding.EncodeToString(imgData)
	}

	u := "http://61.156.89.11:1234/api/capthk"
	files := map[string]string{
		"canvasSrc": encodedJpg,
		"blockSrc":  encodedPng,
	}
	h := map[string]string{
		"User-Agent":   "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
		"content-type": "application/json",
		"x-token":      "ab9296b031462c0cfc9d36e9a5d351af",
	}
	bys, err := lxhttp.POSTJson(http.DefaultClient, u, files, h)
	if err != nil {
		return 0
	}
	return gjson.GetBytes(bys, "distance").Float()
}
