package lxhttp

import (
	"git.listensoft.net/tool/jspkit/logger"
	"github.com/tidwall/gjson"
	"net/http"
	"net/url"
	"strings"
)

const XToken = `ab9296b031462c0cfc9d36e9a5d351af`
const RsServer = "http://rs.jsptax.com/api/rsvmp"
const RsvmpAddress = `qingdao`

var RsvmpUri = []string{
	"/szc/szzh/sjswszzh/zhcx/nsrxx/v1/DescribeNsrxxJcxx",
	"/szc/szzh/sjswszzh/zhcx/nsrxx/v1/DescribeNsrxxZcjyxx",
	"/szc/szzh/sjswszzh/zhcx/nsrxx/v1/DescribeNsrxxQyjyxx",
	"/szc/szzh/sjswszzh/zhcx/nsrxx/v1/DescribeNsrxxYzxx",
	"/szc/szzh/sjswszzh/zhcx/nsrxx/v1/DescribeZgxx",
	"/szc/szzh/sjswszzh/sy/v1/GetNsrzgxx",
	"/szc/szzh/sjswszzh/zhcx/nsrxx/v1/DescribeSfzrdxx",
	"/mhzx/api/mh/nsrjbxx/v1/query",
	"/szc/szzh/sjswszzh/gycxfw/v1/queryDataList/CX_SJSZZH_0001_DQDEHDXXCX",
	"/szc/szzh/sjswszzh/zhcx/v1/DescribeSbmxcx2",
	"/szc/szzh/sbss/ssmx/zlbs/v1/queryZlbscjb",
	"/szc/szzh/sbss/ssmx/sb/v1/getBbidList",
	"/szc/szzh/sbss/ssmx/preview/v1/previewPdfData",
	"/szc/szzh/sjswszzh/zhcx/v1/DescribeSbmxxqcx",
	"/szc/szzh/sjswszzh/zhcx/v1/exportSbmxxqcx",
	"/szc/szzh/sbss/ssmx/sb/v1/downloadPdf",
	"/mhzx/api/mh/wddb/v1/wddbquerybbsmxx",
}

func NeedRsvmpAPi(uri string) bool {
	for _, v := range RsvmpUri {
		if strings.Contains(uri, v) {
			return true
		}
	}
	return false
}

// NeedRsvmp 规定接口需要瑞书加密地区
func NeedRsvmp(BaseUrl string) bool {
	addressArr := strings.Split(RsvmpAddress, ",")
	for _, address := range addressArr {
		if strings.Contains(BaseUrl, address) {
			return true
		}
	}
	return false
}

// Rsvmp 瑞数加密服务
func Rsvmp(uri string) (cookies []*http.Cookie, Posturl string) {
	p := map[string]string{
		"url":    uri,
		"apiUrl": uri,
	}
	h := map[string]string{
		"x-token":      XToken,
		"Content-Type": "application/json",
	}
	var body []byte
	var err error
	for range "...." {
		body, err = POSTJson(http.DefaultClient, RsServer, p, h)
		if err != nil {
			continue
		}
		logger.Info(uri + "\n" + string(body))
		if gjson.GetBytes(body, "status").String() == "ok" {
			break
		}
	}
	Posturl = gjson.GetBytes(body, "result.rsurl").String()
	u1, _ := url.Parse(uri)
	u2, _ := url.Parse(Posturl)
	Posturl = u1.Scheme + "://" + u1.Host + u2.Path + "?" + u2.Query().Encode()
	gjson.GetBytes(body, "result.cookie").ForEach(func(key, value gjson.Result) bool {
		cookie := http.Cookie{
			Name:  key.String(),
			Value: value.String(),
		}
		cookies = append(cookies, &cookie)
		return true
	})
	return
}
