package services

import (
	"crypto/tls"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"

	rhttp "github.com/rdlucklib/rdluck_tools/http"
)

const (
	AlAppKey    = "203889624"
	AlAppSecret = "voampGGl0yGNx5xA1sZdmZlV2EiBct2P"
	AlAppCode   = "22553c4ba74545568aba70ac6cfd441d"
)

type OcrItem struct {
	Image string `json:"image"`
}

type OcrResult struct {
	Addr    []string `json:"addr"`
	Company []string `json:"company"`
	Success bool     `json:"success"`
	TelCell []string `json:"tel_cell"`
}

///ocr_business_card.json
func AliyunBusinessCard(imgUrl string) (result *OcrResult, err error) {
	postUrl := `https://dm-57.data.aliyun.com/rest/160601/ocr/ocr_business_card.json`

	imgBody, err := rhttp.Get(imgUrl)
	if err != nil {
		return
	}
	imageBase64 := base64.StdEncoding.EncodeToString(imgBody)

	item := new(OcrItem)
	item.Image = imageBase64
	jsonBody, err := json.Marshal(item)
	if err != nil {
		fmt.Println("json.Marshal Err:" + err.Error())
		return
	}
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr}
	req, err := http.NewRequest("POST", postUrl, strings.NewReader(string(jsonBody)))
	if err != nil {
		fmt.Println("err:" + err.Error())
		return
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "APPCODE "+AlAppCode)
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("client.Do Err:" + err.Error())
		return
	}
	fmt.Println("resp")
	fmt.Println(resp)
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("err:" + err.Error())
		return
	}
	fmt.Println("body:", string(body))
	err = json.Unmarshal(body, &result)
	return
}