package login

import (
	"context"
	"git.listensoft.net/tool/jspkit/common"
	"git.listensoft.net/tool/jspkit/common/lxrod"
	"git.listensoft.net/tool/jspkit/common/models"
	"git.listensoft.net/tool/jspkit/taxerr"
	"github.com/go-rod/rod"
	"strings"
)

func Login(ctx context.Context, lr *lxrod.Lxrod, info *models.CompanyInfo) (p *rod.Page, err error) {
	defer func() {
		if err != nil && p != nil && p.GetContext().Err() == nil {
			lr.LoginErrImg = common.SaveErrImg(p, *info)
		}
	}()
	if info.Dlfs == "新版登录" || info.Dlfs == "代理登录" {
		_, p, err = lr.NewLowBrowser2(ctx)
		err = CheckSessionAndLogin(ctx, p, GetBaseUri(info.Area), *info)
		if err != nil {
			if info.Dlfs == "新版登录" && RetryErr(err) {
				err = qrLogin(p, info, lr)
			}
			if err != nil {
				return
			}
		}
		if strings.Contains(p.MustInfo().URL, "loginb") { //todo ctx中传递参数决定是否
			C, _ := lxrod.PageToClient(p, GetBaseUri(info.Area))
			err = AfterLogin(C, p, lr, *info, GetBaseUri(info.Area))
		}
	} else {
		err = taxerr.NonsupportLogin(info.Dlfs)
	}
	return
}

func RetryErr(err error) bool {
	if strings.Contains(err.Error(), "卡顿") ||
		strings.Contains(err.Error(), "失效") ||
		strings.Contains(err.Error(), "cookie失效") ||
		strings.Contains(err.Error(), "网络超时，请稍后再试") ||
		strings.Contains(err.Error(), "character") ||
		strings.Contains(err.Error(), "局网络请求异常") ||
		strings.Contains(err.Error(), "税局服务异常,请稍后重试") ||
		strings.Contains(err.Error(), "登陆失败, 网络请求异常") ||
		strings.Contains(err.Error(), "登陆失败, 请重新登录后继续办理业务") ||
		strings.Contains(err.Error(), "登陆失败, 授权失败") ||
		strings.Contains(err.Error(), "登录失败: 内部服务错误") ||
		strings.Contains(err.Error(), "登陆失败,网络请求异常") {
		return true
	}
	return false
}
