package main

import (
	"context"
	"fileproto"
	"fmt"
	"github.com/golang/protobuf/proto"
	"google.golang.org/grpc"
	qu "qfw/util"
	server "server"
	"time"
	. "util"
)

var FileTextClient server.CallerClient

//初始化客户端
func InitFileTextGrpcClient() {
	defer qu.Catch()
	// 连接服务器
	t1 := time.Now()
	conn, err := grpc.Dial(OcrServerAddr, grpc.WithInsecure())
	if err != nil {
		fmt.Printf("连接服务端失败: %s", err)
		return
	} else {
		fmt.Println("连接服务端OK")
	}
	fmt.Println("连接GRPC耗时：", time.Since(t1))
	// 新建一个客户端
	FileTextClient = server.NewCallerClient(conn)
}

func GetFileText(fileName, fileUrl, fileType string, fileBytes []byte) *fileproto.FileResponse {
	defer qu.Catch()
	params := &fileproto.Request{
		FileName:    fileName,
		FileUrl:     fileUrl,
		FileType:    fileType,
		FileBytes:   fileBytes,
		ReturnType:  0, //正式环境改为0
		ExtractType: 1,
	}
	aa := &fileproto.FileRequest{
		Message: []*fileproto.Request{
			params,
		},
	}
	bs, _ := proto.Marshal(aa)
	resp, err := FileTextClient.Call(context.Background(), &server.Request{
		Topic:   "file2txt",
		Timeout: 300,
		Data:    bs,
	})
	if err != nil {
		fmt.Println("调用服务端代码失败: ", err.Error())
		return nil
	}
	respData := new(fileproto.FileResponse)
	err = proto.Unmarshal(resp.GetData(), respData)
	if err != nil {
		fmt.Println("结果解析失败...")
	}
	return respData
}
