package services

import (
	"encoding/json"
	"fmt"
	"hongze/hz_crm_api/models/cygx"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

var (
	AliyunAppCode = "22553c4ba74545568aba70ac6cfd441d" // AppCode
)

type AliOcrByImageToTextResp struct {
	RequestID string `json:"request_id"`
	Ret       []struct {
		Rect struct {
			Angle  int64 `json:"angle"`
			Height int64 `json:"height"`
			Left   int64 `json:"left"`
			Top    int64 `json:"top"`
			Width  int64 `json:"width"`
		} `json:"rect"`
		Word string `json:"word"`
	} `json:"ret"`
	Success bool `json:"success"`
}

//func init() {
//	AliOcrByImageToText("https://hzstatic.hzinsights.com/cygx/config/a2.jpg")
//}

// 阿里云OCR将图片转文字
func AliOcrByImageToText(imageurl string) (item *AliOcrByImageToTextResp, err error) {
	url := "https://tysbgpu.market.alicloudapi.com/api/predict/ocr_general"
	method := "POST"

	payload := strings.NewReader(`{
    "image":"` + imageurl + `"
}`)

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Println(err)
		return
	}
	req.Header.Add("Authorization", "APPCODE "+AlAppCode)
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return
	}

	err = json.Unmarshal(body, &item)
	if err != nil {
		fmt.Println(err)
		return
	}

	logItem := new(cygx.AliyunOcrLog)
	logItem.ImgUrl = imageurl
	logItem.Result = string(body)
	logItem.CreateTime = time.Now()
	err = cygx.AddAliyunOcrLog(logItem)
	return
}
