package spiderutil

import (
	"bytes"
	"encoding/json"
	"errors"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
	"os/exec"
	"strings"
)

const (
	EXEPATH = "tesseract.exe"
	RESULT  = "result"
)

//图像识别
func Ocr(path, name string) (out, result string) {
	c := exec.Command(EXEPATH, []string{path + name, path + RESULT, "-l", "chi_sim", "-psm", "7"}...)
	d, _ := c.CombinedOutput()
	out = string(d)
	fi, _ := os.Open(path + RESULT + ".txt")
	defer fi.Close()
	bs, _ := ioutil.ReadAll(fi)
	result = string(bs)
	result = strings.Replace(result, " ", "", -1)
	result = strings.Replace(result, "\n", "", -1)
	return
}

//图像识别
func OcrOnlyAssic(imagepath string) (out, result string) {
	c := exec.Command(EXEPATH, []string{imagepath, RESULT, "-psm", "7"}...)
	d, _ := c.CombinedOutput()
	out = string(d)
	fi, _ := os.Open(RESULT + ".txt")
	defer fi.Close()
	bs, _ := ioutil.ReadAll(fi)
	result = string(bs)
	result = strings.Replace(result, " ", "", -1)
	result = strings.Replace(result, "\n", "", -1)
	return
}

func Ocr4Web(src []byte) (string, error) {
	buf := new(bytes.Buffer)
	w := multipart.NewWriter(buf)
	fw, _ := w.CreateFormFile("file", "tmp.jpg")
	fw.Write(src)
	w.Close()
	req, _ := http.NewRequest("POST", Config.Tesseractadd+"/upload", buf)
	req.Header.Set("Content-Type", w.FormDataContentType())
	var client http.Client
	res, _ := client.Do(req)
	bs, _ := ioutil.ReadAll(res.Body)
	res.Body.Close()
	tmp := map[string]interface{}{}
	err := json.Unmarshal(bs, &tmp)
	if err != nil {
		return "", err
	}
	if v, ok := tmp["result"]; ok {
		return v.(string), nil
	}
	return "", errors.New("json error")
}
