package services

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/http"
	"hongze/hz_crm_api/utils"
	"net/url"
)

/*
//名片识别
func init() {
	fmt.Println("start")
	services.GetBusinessCard()
	fmt.Println("end")
}
*/

type BdAccessToken struct {
	AccessToken string `json:"access_token"`
	Error       string
}

func GetAccessToken() (accessTokenStr string, err error) {
	baiduApiKey := "nMfRuZ0qBCsVWfGGKekaoMqh"
	baiduBdSecretKey := "N6xcrUizYijMf47iTDDyPBm3lTOrvVSF"
	getUrl := `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=` + baiduApiKey + `&client_secret=` + baiduBdSecretKey + `&`
	body, err := http.Post(getUrl, "")
	var accessToken BdAccessToken
	err = json.Unmarshal(body, &accessToken)
	if err != nil {
		fmt.Println("err:" + err.Error())
		return
	}
	if accessToken.Error != "" {
		err = errors.New("获取token失败，Err:" + accessToken.Error)
		return
	}
	accessTokenStr = accessToken.AccessToken
	return
}

type BdBussinessCard struct {
	Errno          int    `json:"error_code"`
	ErrorMsg       string `json:"error_msg"`
	Logid          string
	WordsResultNum int
	WordsResult    struct {
		ADDR    []string `json:"ADDR"`
		FAX     []string `json:"FAX"`
		MOBILE  []string `json:"MOBILE"`
		NAME    []string `json:"NAME"`
		PC      []string `json:"PC"`
		URL     []string `json:"URL"`
		TEL     []string `json:"TEL"`
		COMPANY []string `json:"COMPANY"`
		TITLE   []string `TITLE`
		EMAIL   []string `EMAIL`
	} `json:"words_result"`
	//{"log_id":1332206693559304192,"error_msg":"target detect error","error_code":282102}
}

func GetBusinessCard(imgUrl string) (item *BdBussinessCard, err error) {
	imgBody, err := http.Get(imgUrl)
	if err != nil {
		return
	}
	//rnStr := utils.GetRandStringNoSpecialChar(5)
	//savePath := time.Now().Format(utils.FormatDateTimeUnSpace) + rnStr + ".jpg"
	//err = file.SaveFile(imgBody, savePath)
	//if err != nil {
	//	return
	//}
	//defer func() {
	//	os.Remove(savePath)
	//}()
	accessToken, err := GetAccessToken()
	fmt.Println("accessToken")
	fmt.Println(accessToken)
	if err != nil {
		fmt.Print("GetAccessToken Err:" + err.Error())
	}
	bussinessCardUrl := `https://aip.baidubce.com/rest/2.0/ocr/v1/business_card?access_token=` + accessToken
	//ff, _ := os.Open(savePath)
	//defer ff.Close()
	//sourcebuffer := make([]byte, 500000)
	//n, _ := ff.Read(sourcebuffer)
	//sourcestring := base64.StdEncoding.EncodeToString(sourcebuffer[:n])
	imageBase64 := base64.StdEncoding.EncodeToString(imgBody)
	imgData := imageBase64
	param := url.Values{}
	param.Set("image", imgData)
	cardBody, err := http.Post(bussinessCardUrl, param.Encode())
	fmt.Println("body：", string(cardBody))
	//fmt.Println(string(cardBody))
	//utils.FileLog.Info("cardBody:%s" + string(cardBody))
	utils.FileLog.Info(fmt.Sprintf("baidu card;imgUrl:%s; Body:%s", imgUrl, string(cardBody)))
	if err != nil {
		fmt.Println("err:", err.Error())
		return
	}
	err = json.Unmarshal(cardBody, &item)
	if err != nil {
		fmt.Println("line err:", err.Error())
	}
	return
}

type CardAccurate struct {
	WordsResultNum int `json:"words_result_num"`
	WordsResult    []struct {
		Words string `json:"words"`
	} `json:"words_result"`
	ErrorCode int    `json:"error_code"`
	ErrorMsg  string `json:"error_msg"`
}

// 通用文字(高精度)
func GetBusinessCardByAccurate(imgUrl string) (item *CardAccurate, err error) {
	imgBody, err := http.Get(imgUrl)
	if err != nil {
		return
	}
	//rnStr := utils.GetRandStringNoSpecialChar(5)
	//savePath := time.Now().Format(utils.FormatDateTimeUnSpace) + rnStr + ".jpg"
	//err = file.SaveFile(imgBody, savePath)
	//if err != nil {
	//	return
	//}
	//defer func() {
	//	os.Remove(savePath)
	//}()
	//
	//nowStr:=time.Now().Format(utils.FormatDateTimeUnSpace)
	//outPath := "./"+nowStr+".jpg"
	//缩放

	//file, err := os.Open(savePath)
	//if err != nil {
	//	fmt.Println("file err:" + err.Error())
	//	return
	//}
	//
	//// decode jpeg into image.Image
	//img, err := jpeg.Decode(file)
	//if err != nil {
	//	fmt.Println("jpeg Decode:" + err.Error())
	//	return
	//}
	//width:=img.Bounds().Dx()
	//height:=img.Bounds().Dy()
	//fmt.Println(width,height)
	//
	//if width>=4096 {
	//	width=4000
	//}
	//
	//if height>=4096 {
	//	height=4000
	//}
	//
	//file.Close()
	//
	//fmt.Println(width,height)
	//
	//m := resize.Resize(uint(width),uint(height), img, resize.Lanczos3)
	//
	//out, err := os.Create(outPath)
	//if err != nil {
	//	fmt.Println("Create:" + err.Error())
	//	return
	//}
	//defer out.Close()
	//
	//jpeg.Encode(out, m, nil)

	accessToken, err := GetAccessToken()
	fmt.Println("accessToken")
	fmt.Println(accessToken)
	if err != nil {
		fmt.Print("GetAccessToken Err:" + err.Error())
	}
	bussinessCardUrl := `https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=` + accessToken
	//ff, _ := os.Open(outPath)
	//defer ff.Close()
	//sourcebuffer := make([]byte, 500000)
	//n, _ := ff.Read(sourcebuffer)
	//sourcestring := base64.StdEncoding.EncodeToString(sourcebuffer[:n])
	//imgData := sourcestring

	imageBase64 := base64.StdEncoding.EncodeToString(imgBody)

	param := url.Values{}
	param.Set("image", imageBase64)
	cardBody, err := http.Post(bussinessCardUrl, param.Encode())
	utils.FileLog.Info("GetBusinessCardByAccurate:%s" + string(cardBody))
	if err != nil {
		fmt.Println("err:", err.Error())
		return
	}
	err = json.Unmarshal(cardBody, &item)
	return
}

// 通用文字(高精度)
func GetBdGeneralBasic(imgUrl string) (item *CardAccurate, err error) {
	imgBody, err := http.Get(imgUrl)
	if err != nil {
		return
	}

	accessToken, err := GetAccessToken()
	if err != nil {
		fmt.Print("GetAccessToken Err:" + err.Error())
	}
	bussinessCardUrl := `https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting?access_token=` + accessToken

	imageBase64 := base64.StdEncoding.EncodeToString(imgBody)

	param := url.Values{}
	param.Set("image", imageBase64)
	cardBody, err := http.Post(bussinessCardUrl, param.Encode())
	utils.FileLog.Info("GetBusinessCardByAccurate:%s" + string(cardBody))
	if err != nil {
		fmt.Println("err:", err.Error())
		return
	}
	err = json.Unmarshal(cardBody, &item)
	return
}
