package TaxSb

import (
	"git.listensoft.net/tool/jspkit/common"
	"git.listensoft.net/tool/jspkit/common/models"
	"git.listensoft.net/tool/jspkit/common/watermark"
	"git.listensoft.net/tool/jspkit/logger"
	"git.listensoft.net/tool/jspkit/taxerr"
	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/input"
	"os"
	"time"
)

func SaveErrImg(p *rod.Page, info models.CompanyInfo) string {
	var check_path string
	check_path = "./data/sbImg/" + info.TaxNo + "/"
	if !common.PathExists(check_path) {
		os.MkdirAll(check_path, os.ModePerm)
	}
	check_path = check_path + info.Period + "-" + time.Now().Format("2006-01-02-15-04-05") + ".png"
	p.Timeout(common.ClickTimeOut).MustScreenshot(check_path)
	watermark.Add(check_path)
	check_path2 := common.PostSbjt(info.TaxNo, info.Period, check_path)
	os.Remove(check_path)
	return check_path2
}

func MustElementX(page *rod.Page, xpath string) *rod.Element {
	return page.Timeout(common.ClickTimeOut).MustSearch(xpath)
}

func WaitElementXZcFz(page *rod.Page, xpath string, interval float64) *rod.Element {
	for i := 0; i < 60; i++ {
		for i := 0; i < 60; i++ {
			// page.Timeout(common.ClickTimeOut).MustElement("#frmFrame").MustFrame().MustElement(`#frmMain`).MustFrame().MustElement(`#frmSheet`).MustFrame()
			if page.MustHas("#frmFrame") && page.MustElement("#frmFrame").MustFrame().MustHas(`#frmMain`) && page.MustElement("#frmFrame").MustFrame().MustElement(`#frmMain`).MustFrame().MustHas(`#frmSheet`) {
				if has, el, _ := page.MustElement("#frmFrame").MustFrame().MustElement(`#frmMain`).MustFrame().MustElement(`#frmSheet`).MustFrame().HasX(xpath); has {
					return el
				}
			}
			time.Sleep(time.Duration(float64(time.Second) * interval))
		}
		time.Sleep(time.Duration(float64(time.Second) * interval))
	}
	logger.Info("页面加载失败元素未找到,请稍后再试", xpath)
	panic(taxerr.NewWebStuckTitle(common.InfoCscsts))
}

func inputStr(el *rod.Element, inputVal string) {
	_ = rod.Try(func() {
		if inputVal == "" {
			inputVal = "0"
		}
		_ = rod.Try(func() {
			el.Page().Keyboard.MustType(input.Backspace)
		})
		_ = rod.Try(func() {
			for _, v := range inputVal {
				_ = el.Page().Keyboard.Type(input.Key(v))
				time.Sleep(time.Millisecond * 10)
			}
		})
	})
}
