package analysiscode

import (
	"analysiscode/proto"
	"bytes"
	"context"
	"encoding/json"
	"log"
	"net"
	"net/http"
	"qfw/util"
	"spiderutil"
	"time"

	"github.com/imroc/req"
	"google.golang.org/grpc"
)

func init() {
	util.ReadConfig(&spiderutil.Config) //初始化参数
}

type CodeService struct {
	proto.GetCodeServer
}

//server
func main1() {
	util.Debug("port", spiderutil.Config.ServerPort)
	lis, err := net.Listen("tcp", spiderutil.Config.ServerPort)
	if err != nil {
		log.Println("failed to listen: ", err)
	}
	//create a server
	s := grpc.NewServer()
	//注册事件
	proto.RegisterGetCodeServer(s, &CodeService{})
	s.Serve(lis)
}

func (cs *CodeService) GetCodeByImgPath(ctx context.Context, req *proto.GetCodebyImgPathReq) (*proto.GetCodebyImgPathResp, error) {
	//根据图片地址解析出code
	util.Debug("Img Path:", req.Imgpath)
	code, headers, cookies := getCode(req.Imgpath, req.Stype, req.Head, req.Cookie)
	head, _ := json.Marshal(headers)
	cookie, _ := json.Marshal(cookies)
	return &proto.GetCodebyImgPathResp{
		Code:   code,
		Head:   string(head),
		Cookie: string(cookie),
	}, nil
}

func getCode(path, stype, head, cookie string) (code string, respheader http.Header, respcookie []*http.Cookie) {
	// log.Println("cookie---", cookie)
	// log.Println("stype---", stype)
	client := req.C().SetTimeout(spiderutil.Config.TimeOut * time.Second)
	headers := map[string]string{}
	if head != "" {
		json.Unmarshal([]byte(head), &headers)
	}
	cookies := []*http.Cookie{}
	if cookie != "" {
		json.Unmarshal([]byte(cookie), &cookies)
	}
	// log.Println("headers:", headers)
	// log.Println("cookies:", cookies)
	for times := 1; times <= 3; times++ { //重试三次
		request := client.R()
		if len(headers) > 0 {
			request.SetHeaders(headers)
		}
		if len(cookies) > 0 {
			request.SetCookies(cookies...)
		}
		//下载验证码
		getCodeResp, err := request.Get(path)
		if err != nil {
			log.Println("Get Code By Path Error: ", err)
			continue
		}
		//解析验证码
		data := map[string]string{
			"grant_type":     "",
			"username":       spiderutil.Config.UserName,
			"password":       spiderutil.Config.PassWord,
			"scope":          "",
			"client_id":      "",
			"client_secret ": "",
		}
		codeResp, err := client.R().
			SetHeader("accept", "application/json").
			SetFileReader("file", "1", bytes.NewReader(getCodeResp.Bytes())).
			SetFormData(data).
			Post(spiderutil.Config.ServerCodeAddress + stype)
			//SetFile("file", "C:/Users/topnet/Desktop/code.jpg").
			// Post(spiderutil.Config.ServerCodeAddress)
		if err != nil {
			log.Println("analysis code by path err: ", err)
			continue
		}
		codeResult := map[string]interface{}{}
		json.Unmarshal(codeResp.Bytes(), &codeResult)
		log.Println("codeResult:", codeResult)
		if yzm, ok := codeResult["r"].(map[string]interface{})["pic_str"].(string); ok && yzm != "" {
			code = yzm
			respheader = getCodeResp.Header
			respcookie = getCodeResp.Cookies()
			return
		}
	}
	return
}

//func main() {
//	log.Println(util.Config)
//	conn, err := grpc.Dial("127.0.0.1"+util.Config.Port, grpc.WithInsecure())
//	if err != nil {
//		log.Fatalf("did not connect: %v", err)
//	}
//	defer conn.Close()
//	client := proto.NewGetCodeServerClient(conn)
//	codeImgReq := &proto.GetCodebyImgPathReq{
//		Imgpath:
//	}
//	getCodeByImg(client, codeImgReq)
//
//}
//
