package main

import (
	"bufio"
	"context"
	"encoding/base64"
	"fmt"
	"log"
	"os"
	"os/exec"
	"strings"
	"time"
	"regexp"
	"github.com/chromedp/chromedp"
	"github.com/chromedp/cdproto/network"
)

var (
	URL = "https://192.168.132.19:30080/login"
	//URL      = "https://baidu.com"
	Account  = "admin"
	Password = "zzpoE5ctcRfIr"
)

func fullScreenshot(urlstr string, quality int, res *[]byte) chromedp.Tasks {
	return chromedp.Tasks{
		chromedp.Navigate(urlstr),
		chromedp.FullScreenshot(res, quality),
	}
}

var jwt string
func main() {

	// chromdp依赖context上限传递参数
	ctx, _ := chromedp.NewExecAllocator(
		context.Background(),

		// 以默认配置的数组为基础,覆写headless参数
		// 当然也可以根据自己的需要进行修改,这个flag是浏览器的设置
		append(
			chromedp.DefaultExecAllocatorOptions[:],
			chromedp.Flag("headless", false),
			chromedp.Flag("ignore-certificate-errors", "1"),
		)...,
	)

	ctx, _ = context.WithTimeout(ctx, 50*time.Second)
	ctx, _ = chromedp.NewContext(ctx)
	var res string

	//listenForNetworkEvent(ctx)
	log.Println(strings.TrimSpace(res))

	chromedp.Run(ctx, chromedp.Tasks{
		chromedp.Navigate(URL),
		chromedp.SendKeys(`#username`, Account, chromedp.ByID),
		chromedp.SendKeys(`#password`, Password, chromedp.ByID),
		chromedp.Evaluate(`document.querySelector(".code___1wGtw").src`, &res),
	})




	chromedp.Run(ctx, chromedp.Tasks{
		chromedp.Click(`document.querySelector(".ant-btn.ant-btn-primary")`, chromedp.ByJSPath),
	})

	res = strings.Replace(res, "data:image/png;base64,", "", 1)
	//fmt.Println(res)

	filePath := "test.png"
	file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) //0666 在windos下无效
	if err != nil {
		fmt.Println("open file err:", err)
		return
	}
	//关闭文件
	defer file.Close()

	decodedString, err := base64.StdEncoding.DecodeString(res)
	if err != nil {
		fmt.Println("Error Found:", err)
		return
	}
	//带缓存写入文件
	writer := bufio.NewWriter(file)
	fmt.Println("save test.png")
	writer.WriteString(string(decodedString))

	writer.Flush()

	cmd := exec.Command("python3.8", "/home/ddddocr/test.py")
    	out, err := cmd.CombinedOutput()
        if err != nil {
           fmt.Printf("combined out:\n%s\n", string(out))
           log.Fatalf("cmd.Run() failed with %s\n", err)
        }
        //fmt.Printf("combined out:\n%s\n", string(out))
        
	regexp, _ := regexp.Compile("res=.*")
	cap := regexp.FindString(string(out))
	
	res = strings.Replace(string(cap), "res=", "", 1)
	fmt.Println("cap is :" + res)
	
	
	chromedp.Run(ctx, chromedp.Tasks{
		chromedp.SendKeys(`document.querySelector(".code_input___19LHi")`, string(res), chromedp.ByJSPath),
	})


	var buf []byte
	chromedp.Run(ctx, chromedp.Tasks{
		chromedp.FullScreenshot(&buf, 90),
	})

	if err := os.WriteFile("index.png", buf, 0o644); err != nil {
		log.Fatal(err)
	}
	
	
	chromedp.Run(ctx, chromedp.Tasks{
		chromedp.Click(`document.querySelector(".ant-btn.ant-btn-primary")`, chromedp.ByJSPath),
	})
	
	for true {
		time.Sleep(5*time.Second)
		
		if jwt == "" {
			chromedp.Run(ctx, chromedp.Tasks{
				chromedp.ActionFunc(func(ctx context.Context) error {
					cookies, err := network.GetCookies().Do(ctx)
					if err != nil {
						return err
					}
					for i, cookie := range cookies {
						if cookie.Name == "Ksp-Auth" {
							log.Printf("chrome cookie %d: %+v : %+v", i, cookie.Name, cookie.Value)
							jwt = cookie.Value
							return nil
						}
						
					}
					return nil
				}),
			})
		}
	}

}