package login

import (
	"encoding/json"
	"fmt"
	"git.listensoft.net/tool/jspkit/common"
	"git.listensoft.net/tool/jspkit/common/lxhttp"
	"git.listensoft.net/tool/jspkit/common/lxrod"
	"git.listensoft.net/tool/jspkit/common/models"
	"git.listensoft.net/tool/jspkit/logger"
	"git.listensoft.net/tool/jspkit/taxerr"
	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/input"
	"github.com/go-rod/rod/lib/proto"
	"github.com/go-rod/rod/lib/utils"
	"github.com/tidwall/gjson"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
)

func AfterLogin2(baseUrlNew string, page *rod.Page, info models.CompanyInfo) (e error) {
	taxNo := strings.TrimSpace(common.MustElementX(page, `(//div[@class='leftMain']//div[@class="leftTopItem clearfix"][2])/span[1]`).MustText())
	if info.TaxNo != taxNo {
		panic(taxerr.NewUserV3(`公司名称与税局帐号不匹配`, fmt.Sprintf(`税局为:%s 系统为:%s，请检查`, taxNo, info.TaxNo)))
	}
	logger.Info("afterLogin调试埋点2")
	for range "..." {
		common.WaitNavigation(page, baseUrlNew+`/szc/szzh/sbss/ssmx/tpass/ssoLogin`) //不能改
		//wait()
		time.Sleep(time.Second * 5)
		if strings.Contains(page.MustHTML(), "non null key required") {
			break
		}
		logger.Info("ssoLogin 重试:", page.MustInfo().URL)
	}
	//跳回首页
	logger.Info("afterLogin调试埋点3")
	common.WaitNavigation(page, baseUrlNew+"/loginb/")
	utils.Sleep(3)
	logger.Info("afterLogin调试埋点4")
	e = rod.Try(func() {
		if page.MustHasX(`//p[@title="税务数字账户"]`) {
			has := false
			for range "...." {
				w := page.MustWaitOpen()
				common.MustElementX(page, `//p[@title="税务数字账户"]`).MustClick()
				utils.Sleep(1)
				if page.MustHasR(`[class="t-message__list"]`, "未授权") {
					panic(taxerr.NewUserV3(`当前账户没有查询权限`, "请切换身份后重试"))
				}
				newp := w()
				utils.Sleep(2)
				newp.MustWaitLoad()
				newp.MustWaitDOMStable()
				for range "..." {
					if newp.MustHas(`[class="companyTitle"]`) {
						has = true
						break
					} else {
						utils.Sleep(1.5)
					}
				}
				logger.Info(newp.MustInfo().URL)
				newp.MustClose()
				if has {
					break
				}
			}
			if !has {
				path := common.GeneratePath("png")
				page.MustScreenshot(path)
				fmt.Println(path)
				panic(taxerr.New("当前企业账户查询进入失败, 请稍后重试"))
			}
			//
		} else {
			f := 0
		begin:
			//time.Sleep(time.Second)
			page.WaitDOMStable(time.Second*2, 0)
			wait := page.MustWaitOpen()
			// todo 暂时没判断搜索不到的情况
			page.Timeout(common.ClickTimeOut * 2).MustElement(`[placeholder="请输入关键词"]`).MustClick()
			r := page.MustWaitRequestIdle()
			page.Timeout(common.ClickTimeOut).MustElement(`[placeholder="请输入关键词"]`).MustSelectAllText().MustInput("账户查询")
			r()
			utils.Sleep(1)
			if page.MustHasR(`[class="popMain1"]`, "没有找到") {
				//panic(taxerr.NewUser("当前企业新版税局未授权账户查询模块权限")) 申报信息查询
				r = page.MustWaitRequestIdle()
				page.Timeout(common.ClickTimeOut * 2).MustElement(`[placeholder="请输入关键词"]`).MustClick()
				page.Timeout(common.ClickTimeOut).MustElement(`[placeholder="请输入关键词"]`).MustSelectAllText().MustType(input.Backspace).MustInput("申报信息查询")
				r()
				utils.Sleep(1)
				if page.MustHasR(`[class="popMain1"]`, "没有找到") {
					panic(taxerr.NewUser("当前企业新版税局未授权账户查询模块和申报信息查询权限"))
				}
				//if page.MustHasR(`[class="popMain1"]`, "没有找到") {
				//	panic(taxerr.NewUser("当前企业新版税局未授权账户查询模块权限"))
				//}
			}
			page.Keyboard.MustType(input.ArrowDown)
			utils.Sleep(0.5)
			page.Keyboard.MustType(input.Enter)
			var newPage *rod.Page
			e1 := rod.Try(func() {
				newPage = wait()
			})
			if e1 != nil {
				_ = newPage.Close()
				if f < 4 {
					f++
					goto begin
				}
			}
			defer func() {
				if newPage != nil {
					_ = newPage.Close()
				}
			}()
			common.Link(newPage)
			logger.Info("afterLogin调试埋点5")
			_ = rod.Try(func() {
				newPage.Timeout(common.ClickTimeOut * 6).MustWaitLoad()
			})
			_ = newPage.WaitDOMStable(time.Second*10, float64(50*time.Millisecond)) // 5s时间
			u := newPage.MustInfo().URL
			if !strings.Contains(u, "zhcx") || newPage.MustHas(`span.loginBtn > span > svg`) ||
				strings.Contains(u, "baseInfoEE") ||
				u == "https://etax.hebei.chinatax.gov.cn:8443/" ||
				u == "https://etax.hebei.chinatax.gov.cn:8443" {
				if f < 4 {
					logger.Info("账户查询页面错误：", u)
					_ = newPage.Close()
					utils.Sleep(2)
					_ = page.Reload()
					f++
					goto begin
				}
			}
			logger.Info("afterLogin调试埋点5.1")
			for i := 1; i < 5; i++ { // 第一次加载不出来刷新才可以
				time.Sleep(time.Second * 4)
				if newPage.MustHasX(`//p[text()='纳税人信息查询']`) {
					break
				} else {
					if i%2 == 0 {
						_ = newPage.WaitDOMStable(time.Second*5, float64(50*time.Millisecond)) // 5s时间
					}
				}
				if f < 4 && i == 4 {
					f++
					_ = newPage.Close()
					goto begin
				}
			}
			logger.Info(`//p[text()='纳税人信息查询']`, newPage.MustHasX(`//p[text()='纳税人信息查询']`))
			if !newPage.MustHasX(`//p[text()='纳税人信息查询']`) {
				logger.Info(newPage.MustInfo().URL)
				panic(taxerr.NewUserV3("当前企业账户查询进入失败", "请稍后重试"))
			}
			logger.Info("afterLogin调试埋点6")
			//common.WaitElementX(newPage, `//p[text()='纳税人信息查询']`, 0.5).MustClick()
			//common.WaitElementX(newPage, `//div[contains(@class,'title')]`, 0.5)
			//utils.Sleep(2)
			//logger.Info("afterLogin调试埋点7")
			_ = newPage.Close()
		}

	})
	logger.Info("afterLogin调试埋点9")

	return
}

func AfterLogin(C *http.Client, page *rod.Page, lr *lxrod.Lxrod, info models.CompanyInfo, BaseUrlNew string) (err error) {
	logger.Info("接口AfterLogin埋点1")
	_ = rod.Try(func() {
		if page.MustHasX(`//*[contains(text(),"人脸识别")]`) {
			page.Timeout(time.Second).MustElementX(`//*[contains(text(),"人脸识别")]/../../../../../div[3]/div/button`).MustClick()
			page.MustWaitIdle()
			utils.Sleep(2)
			if page.MustHasX(`//div[contains(text(),'关于电子税务局“新办智能开业”的通知')]`) {
				panic(taxerr.NewUserV3("当前公司为新注册电子税局公司", "请先手动登录电子税局补充信息或签订文书后重试"))
			}
		}
	})
	if page.MustHasX(`//div[contains(text(),'关于电子税务局“新办智能开业”的通知')]`) && !page.MustHasX(`//div[@class='leftMain']//div[contains(@class,'title')]`) {
		return taxerr.NewUserV3("当前公司为新注册电子税局公司", "请先手动登录电子税局补充信息或签订文书后重试")
	}
	name := ""
	for i := 0; i < 5; i++ {
		name = *common.WaitElementX(page, `//div[@class='leftMain']//div[contains(@class,'title')]`, 0.5).MustAttribute("title")
		if name == "" {
			common.WaitNavigation(page, BaseUrlNew+`/loginb/`)
			logger.Info("新afterLogin等待公司名埋点0.1")
			utils.Sleep(4)
			name = *common.WaitElementX(page, `//div[@class='leftMain']//div[contains(@class,'title')]`, 0.5).MustAttribute("title")
			logger.Info("新afterLogin等待公司名埋点.2")
		} else {
			if common.Unbracket(info.ComName) != common.Unbracket(name) {
				return taxerr.CompanyNameError(name)
			}
			break
		}
	}
	logger.Info("接口AfterLogin埋点2")
	if name == "" {
		return common.NewWebStuckTitle()
	}
	// 不要传空的进来
	if C == nil {
		C = lxhttp.NewHttpClientForLocalProxy(lr.Proxy, lr.ProxyAuth)
	}
	{
		var C2 *http.Client
		logger.Info("接口AfterLogin埋点3")
		C2, err = RefreshCookieForAfterLoginRod(page, lr.Proxy, lr.ProxyAuth, info.Area, BaseUrlNew, true)
		logger.Info("接口AfterLogin埋点4")
		C.Jar = C2.Jar
		if err == nil {
			logger.Info("接口AfterLogin完成1")
			u, _ := url.Parse(BaseUrlNew)
			var rodCookies []*proto.NetworkCookieParam
			for _, v := range C.Jar.Cookies(u) {
				if strings.Contains(v.Name, "MM") {
					continue
				}
				rodCookies = append(rodCookies,
					&proto.NetworkCookieParam{
						Name:   v.Name,
						Value:  v.Value,
						Domain: ".chinatax.gov.cn",
						Path:   "/",
					},
				)
			}
			err = page.Browser().SetCookies(rodCookies)
			logger.Info("接口AfterLogin更新浏览器cookie完成")
			// 测试一下C
			{
				uri := fmt.Sprintf(`%s/szc/szzh/sjswszzh/zhcx/v1/DescribeSbmxcx2`, BaseUrlNew)
				year := strconv.Itoa(time.Now().Year() - 1)
				data := map[string]interface{}{"gzlx": []string{"1", "5"}, "pageNum": 1, "pageSize": 10, "sbrqq": "", "sbrqz": "", "skssqq": year + "-01-01", "skssqz": year + "-12-31", "zfbz": "N", "yzpzzlDm": "BDA0610857"}
				jsonR, _ := json.Marshal(data)
				headers := map[string]string{
					"Content-Type": "application/json",
					"User-Agent":   "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
					"accept":       "application/json;charset=UTF-8",
				}
				res, _ := lxhttp.PostByteReader(C, uri, jsonR, headers, nil)
				logger.Info(string(res))
				if gjson.GetBytes(res, "Response.Error").Type != gjson.Null || strings.Contains(string(res), "会话失效，请重新登录") {
					logger.Info("接口AfterLogin接口测试失败重新afterlogin")
				} else {
					logger.Info("接口AfterLogin完成")
					return err
				}
			}
		}
		err = nil
		AfterLogin1(BaseUrlNew, page, info)
		cookies := page.Browser().MustGetCookies()
		var cookiesArr []*http.Cookie
		for _, v := range cookies {
			if v.Name == "localStorage" {
				continue
			}
			var cookie http.Cookie
			cookie.Domain = v.Domain
			cookie.Name = v.Name
			cookie.Value = v.Value
			cookiesArr = append(cookiesArr, &cookie)
		}
		u, _ := url.Parse(BaseUrlNew)
		C.Jar.SetCookies(u, cookiesArr)
		return err
	}
}

// 页面跳转主要是为了获取各种cookie
func AfterLogin1(baseUrlNew string, page *rod.Page, info models.CompanyInfo) {
	common.WaitNavigation(page, baseUrlNew+`/szc/szzh/sbss/ssmx/tpass/ssoLogin`)
	time.Sleep(time.Second * 2)
	////跳回首页
	logger.Info("afterLogin调试埋点3")
	toPage(page, fmt.Sprintf("https://etax.%s.chinatax.gov.cn:8443/szzh/zhcx/", info.Area))
	common.WaitNavigation(page, baseUrlNew+"/loginb/")
	utils.Sleep(2)
	logger.Info("afterLogin调试埋点4")
}

func toPage(p *rod.Page, url string) error {
	return rod.Try(func() {
		w := p.Timeout(common.ClickTimeOut * 2).MustWaitNavigation()
		p.MustNavigate(url)
		w()
		utils.Sleep(2)
	})
}
