package flexCdn

import (
	"context"
	"encoding/json"
	"fmt"
	v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
	"github.com/go-nunu/nunu-layout-advanced/api/v1/cdn"
	"github.com/go-nunu/nunu-layout-advanced/internal/repository/api/flexCdn"
	"github.com/go-nunu/nunu-layout-advanced/internal/service"

	"github.com/spf13/viper"
	"strings"
)

type CdnService interface {
	// GetToken 获取token
	GetToken(ctx context.Context) (string, error)
	// AddUser 注册用户
	AddUser(ctx context.Context, req v1.User) (int64, error)
	CreateGroup(ctx context.Context, req v1.Group) (int64, error)
	BindPlan(ctx context.Context, req v1.Plan) (int64, error)
	// 续费套餐
	RenewPlan(ctx context.Context, req v1.RenewalPlan) error
	CreateWebsite(ctx context.Context, req v1.WebsiteSend) (int64, error)
	EditServerType(ctx context.Context, req v1.EditWebsite, apiType string) error
	EditProtocol(ctx context.Context, req v1.ProxyJson, action string) error
	CreateOrigin(ctx context.Context, req v1.Origin) (int64, error)
	EditOrigin(ctx context.Context, req v1.Origin) error
	AddServerOrigin(ctx context.Context, serverId int64, originId int64) error
	EditOriginIsOn(ctx context.Context, originId int64, isOn bool) error
	// 修改网站基本信息
	EditServerBasic(ctx context.Context, serverId int64, name string,nodeId int64) error
	// 从网站中删除某个源站
	DelServerOrigin(ctx context.Context, serverId int64, originId int64) error
	// 删除网站
	DelServer(ctx context.Context, serverId int64) error
	// 添加ssl证书
	AddSSLCert(ctx context.Context, req v1.SSlCert) (int64, error)
	// 修改网站域名
	EditServerName(ctx context.Context, req v1.EditServerNames) error
	// 添加ssl策略
	AddSSLPolicy(ctx context.Context, req v1.AddSSLPolicy) (int64, error)
	DelSSLCert(ctx context.Context, sslCertId int64) error
	EditSSLCert(ctx context.Context, req v1.SSlCert) error
	EditSSLPolicy(ctx context.Context, req v1.SSLPolicy) error
	// 修改反向代理
	EditProxy(ctx context.Context, req v1.Proxy) error
	// 修改日志
	EditWebLog(ctx context.Context,webId int64, req v1.WebLog) error
	// 修改CC配置
	EditCcConfig(ctx context.Context,webId int64, req v1.CcConfig) error
	// 添加webSocket
	AddWebSockets(ctx context.Context, req v1.WebSocket) (int64,error)
	// 修改webSocket
	EditWebSockets(ctx context.Context, req v1.WebSocket) error
	// 启用webSocket
	EditHTTPWebWebsocket(ctx context.Context,websocketId int64,websocketJSON []byte) error
	// 启用/禁用网站
	EditWebIsOn(ctx context.Context,serverId int64,isOn bool) error
	// 删除已购套餐
	DelUserPlan(ctx context.Context,planId int64) error
	// 删除网站分组
	DelServerGroup(ctx context.Context,serverId int64) error
	// 删除IP
	DelIpItem(ctx context.Context,ipitemId int64,value string,ipFrom string,ipTo string,ipListId int64) error
	// 创建空防火墙策略
	AddWafPolicy(ctx context.Context,req v1.AddWafPolicy) (int64, error)
	// 更改防火墙设置
	EditHTTPWebFirewal(ctx context.Context,httpWebId int64,FirewallJSON v1.Firewall) error
	// 创建IP列表
	AddIPList(ctx context.Context, req v1.IPListRequest) (int64, error)
	// 添加IP
	AddIpItem(ctx context.Context, req v1.AddIpItem) error
	// 修改IP
	EditIpItem(ctx context.Context, req v1.AddIpItem) error
	// 获取访问日志
	GetAccessLog(ctx context.Context, req cdn.Request) (cdn.Data, error)
}

func NewCdnService(
	service *service.Service,
	conf *viper.Viper,
	request service.RequestService,
	cdnRepository flexCdn.CdnRepository,
) CdnService {
	return &cdnService{
		Service:           service,
		Url:               conf.GetString("flexCdn.Url"),
		AccessKeyID:       conf.GetString("flexCdn.AccessKeyID"),
		AccessKeySecret:   conf.GetString("flexCdn.AccessKeySecret"),
		request:           request,
		cdnRepository:     cdnRepository,
		maxRetryCount:     3, // 可以配置最大重试次数
		retryDelaySeconds: 2, // 可以配置重试间隔
	}
}

type cdnService struct {
	*service.Service
	Url             string
	AccessKeyID       string
	AccessKeySecret string
	request       service.RequestService
	cdnRepository flexCdn.CdnRepository
	maxRetryCount int
	retryDelaySeconds int
}

// SendData 是一个通用的请求发送方法，它封装了 token 过期重试的逻辑
func (s *cdnService) sendDataWithTokenRetry(ctx context.Context, formData map[string]interface{}, apiUrl string) ([]byte, error) {
	var resBody []byte

	for i := 0; i < s.maxRetryCount; i++ {
		token, err := s.Token(ctx) // 确保使用最新的 token
		if err != nil {
			return nil, fmt.Errorf("获取或刷新 token 失败: %w", err)
		}

		resBody, err = s.request.Request(ctx, formData, apiUrl, "X-Cloud-Access-Token", token)
		if err != nil {
			// 检查错误是否是由于 token 无效引起的
			if s.isTokenInvalidError(resBody, err) { // 判断是否是 token 无效错误
				_, getTokenErr := s.GetToken(ctx)
				if getTokenErr != nil {
					return nil, fmt.Errorf("刷新 token 失败: %w", getTokenErr)
				}
				continue // 继续下一次循环，使用新的 token
			}
			return nil, fmt.Errorf("请求失败: %w", err)
		}

		// 成功获取到响应，处理响应体
		var generalResponse v1.GeneralResponse[any]
		if err := json.Unmarshal(resBody, &generalResponse); err != nil {
			return nil, fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
		}

		// 检查 API 返回的 code 和 message
		if generalResponse.Code == 400 && generalResponse.Message == "invalid access token" {
			fmt.Printf("尝试 %d/%d：API 返回无效 token 错误，准备刷新并重试...\n", i+1, s.maxRetryCount)
			_, getTokenErr := s.GetToken(ctx)
			if getTokenErr != nil {
				return nil, fmt.Errorf("刷新 token 失败: %w", getTokenErr)
			}
			continue // 继续下一次循环，使用新的 token
		}

		// 成功处理，返回结果
		return resBody, nil
	}

	// 如果循环结束仍未成功，则返回最终错误
	return nil, fmt.Errorf("达到最大重试次数后请求仍然失败")
}

// isTokenInvalidError 是一个辅助函数，用于判断错误是否是由于 token 无效引起的。
// 你需要根据你的 request.Request 实现来具体实现这个函数。
// 例如，你可以检查 resBody 是否包含特定的错误信息。
func (s *cdnService) isTokenInvalidError(resBody []byte, err error) bool {
	// 示例：如果请求本身就返回了非 200 的错误，并且响应体中有特定信息
	if err != nil {
		// 尝试从 resBody 中解析出错误信息，判断是否是 token 无效
		var generalResponse v1.GeneralResponse[any]
		if parseErr := json.Unmarshal(resBody, &generalResponse); parseErr == nil {
			if generalResponse.Code == 400 && generalResponse.Message == "invalid access token" {
				return true
			}
		}
		// 或者检查 err 本身是否有相关的错误信息
		// if strings.Contains(err.Error(), "invalid access token") {
		// 	return true
		// }
	}
	return false
}

func (s *cdnService) GetToken(ctx context.Context) (string, error) {
	formData := map[string]interface{}{
		"type":        "admin",
		"accessKeyId": s.AccessKeyID,
		"accessKey":   s.AccessKeySecret,
	}
	apiUrl := s.Url + "APIAccessTokenService/getAPIAccessToken"

	resBody, err := s.request.Request(ctx, formData, apiUrl, "X-Cloud-Access-Token", "")
	if err != nil {
		return "", err
	}

	var res v1.GeneralResponse[v1.FlexCdnTokenResponse]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return "", fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}

	if res.Code != 200 {
		return "", fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}

	err = s.cdnRepository.PutToken(ctx, res.Data.Token)
	if err != nil {
		return "", err
	}
	return res.Data.Token, nil
}

func (s *cdnService) Token(ctx context.Context) (string, error) {
	token, err := s.cdnRepository.GetToken(ctx)
	if err != nil {
		return "", err
	}
	if token == "" {
		token, err = s.GetToken(ctx)
		if err != nil {
			return "", err
		}
	}
	return token, nil
}

// 注册用户
func (s *cdnService) AddUser(ctx context.Context, req v1.User) (int64, error) {
	formData := map[string]interface{}{
		"id":            req.ID,
		"username":      req.Username,
		"password":      "a7fKiKujgAzzsJ6", // 这个密码应该被妥善管理，而不是硬编码
		"fullname":      req.Fullname,
		"mobile":        req.Mobile,
		"tel":           req.Tel,
		"email":         req.Email,
		"remark":        req.Remark,
		"source":        req.Source,
		"nodeClusterId": 2,
	}
	apiUrl := s.Url + "UserService/createUser"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return 0, err
	}
	type DataStr struct {
		UserId int64 `json:"userId" form:"userId"`
	}
	var res v1.GeneralResponse[DataStr]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return 0, fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}

	if res.Code != 200 {
		return 0, fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	if res.Data.UserId == 0 {
		return 0, fmt.Errorf("添加用户失败")
	}
	return res.Data.UserId, nil
}

// 创建规则分组
func (s *cdnService) CreateGroup(ctx context.Context, req v1.Group) (int64, error) {
	formData := map[string]interface{}{
		"name": req.Name,
	}
	apiUrl := s.Url + "ServerGroupService/createServerGroup"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl) // 使用封装后的方法
	if err != nil {
		return 0, err
	}
	type DataStr struct {
		ServerGroupId int64 `json:"serverGroupId" form:"serverGroupId"`
	}
	var res v1.GeneralResponse[DataStr]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return 0, fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return 0, fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	if res.Data.ServerGroupId == 0 {
		return 0, fmt.Errorf("创建规则分组失败")
	}
	return res.Data.ServerGroupId, nil
}

// 分配套餐
func (s *cdnService) BindPlan(ctx context.Context, req v1.Plan) (int64, error) {
	formData := map[string]interface{}{
		"userId":      req.UserId,
		"planId":      req.PlanId,
		"dayTo":       req.DayTo,
		"period":      req.Period,
		"countPeriod": req.CountPeriod,
		"name":        req.Name,
		"isFree":      req.IsFree,
		"periodDayTo": req.PeriodDayTo,
	}
	apiUrl := s.Url + "UserPlanService/buyUserPlan"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl) // 使用封装后的方法
	if err != nil {
		return 0, err
	}
	type DataStr struct {
		UserPlanId int64 `json:"userPlanId" form:"userPlanId"`
	}
	var res v1.GeneralResponse[DataStr]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return 0, fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return 0, fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	if res.Data.UserPlanId == 0 {
		return 0, fmt.Errorf("分配套餐失败")
	}
	return res.Data.UserPlanId, nil
}

// 续费套餐
func (s *cdnService) RenewPlan(ctx context.Context, req v1.RenewalPlan) error {
	formData := map[string]interface{}{
		"userPlanId":  req.UserPlanId,
		"dayTo":       req.DayTo,
		"period":      req.Period,
		"countPeriod": req.CountPeriod,
		"isFree":      req.IsFree,
		"periodDayTo": req.PeriodDayTo,
	}
	apiUrl := s.Url + "UserPlanService/renewUserPlan"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl) // 使用封装后的方法
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// 创建网站
func (s *cdnService) CreateWebsite(ctx context.Context, req v1.WebsiteSend) (int64, error) {
	formData := map[string]interface{}{
		"userId":           req.UserId,
		"type":             req.Type,
		"name":             req.Name,
		"description":      req.Description,
		"serverNamesJSON":  req.ServerNamesJSON,
		"httpJSON":         req.HttpJSON,
		"httpsJSON":        req.HttpsJSON,
		"tcpJSON":          req.TcpJSON,
		"tlsJSON":          req.TlsJSON,
		"udpJSON":          req.UdpJSON,
		"webId":            req.WebId,
		"reverseProxyJSON": req.ReverseProxyJSON,
		"serverGroupIds":   req.ServerGroupIds,
		"userPlanId":       req.UserPlanId,
		"nodeClusterId":    req.NodeClusterId,
	}
	apiUrl := s.Url + "ServerService/createServer"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl) // 使用封装后的方法
	if err != nil {
		return 0, err
	}
	type DataStr struct {
		ServerId int64 `json:"serverId" form:"serverId"`
	}
	var res v1.GeneralResponse[DataStr]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return 0, fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return 0, fmt.Errorf("创建网站API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	if res.Data.ServerId == 0 {
		return 0, fmt.Errorf("创建网站失败")
	}
	return res.Data.ServerId, nil
}

func (s *cdnService) EditProtocol(ctx context.Context, req v1.ProxyJson, action string) error {
	formData := map[string]interface{}{
		"serverId": req.ServerId,
	}
	var apiUrl string
	switch action {
	case "tcp":
		formData["tcpJSON"] = req.JSON
		apiUrl = s.Url + "ServerService/updateServerTCP"
	case "tls":
		formData["tlsJSON"] = req.JSON
		apiUrl = s.Url + "ServerService/updateServerTLS"
	case "udp":
		formData["udpJSON"] = req.JSON
		apiUrl = s.Url + "ServerService/updateServerUDP"
	case "http":
		formData["httpJSON"] = req.JSON
		apiUrl = s.Url + "ServerService/updateServerHTTP"
	case "https":
		formData["httpsJSON"] = req.JSON
		apiUrl = s.Url + "ServerService/updateServerHTTPS"
	default:
		return fmt.Errorf("不支持的协议类型")
	}
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl) // 使用封装后的方法
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

func (s *cdnService) CreateOrigin(ctx context.Context, req v1.Origin) (int64, error) {
	formData := map[string]interface{}{
		"name":                  req.Name,
		"addr":                  req.Addr,
		"ossJSON":               req.OssJSON,
		"description":           req.Description,
		"weight":                req.Weight,
		"isOn":                  req.IsOn,
		"domains":               req.Domains,
		"certRefJSON":           req.CertRefJSON,
		"host":                  req.Host,
		"followPort":            req.FollowPort,
		"http2Enabled":          req.Http2Enabled,
		"tlsSecurityVerifyMode": req.TlsSecurityVerifyMode,
	}
	apiUrl := s.Url + "OriginService/createOrigin"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl) // 使用封装后的方法
	if err != nil {
		return 0, err
	}
	type DataStr struct {
		OriginId int64 `json:"originId" form:"originId"`
	}
	var res v1.GeneralResponse[DataStr]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return 0, fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return 0, fmt.Errorf("添加源站API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	if res.Data.OriginId == 0 {
		return 0, fmt.Errorf("创建源站失败")
	}
	return res.Data.OriginId, nil
}

func (s *cdnService) EditServerType(ctx context.Context, req v1.EditWebsite, apiType string) error {
	typeName := apiType + "JSON"
	formData := map[string]interface{}{
		"serverId": req.Id,
		typeName:   req.TypeJSON,
	}
	apiUrl := s.Url + "ServerService/updateServer" + strings.ToUpper(apiType)
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil

}

// EditOrigin 编辑源站

func (s *cdnService) EditOrigin(ctx context.Context, req v1.Origin) error {
	formData := map[string]interface{}{
		"originId":              req.OriginId,
		"name":                  req.Name,
		"addr":                  req.Addr,
		"ossJSON":               req.OssJSON,
		"description":           req.Description,
		"weight":                req.Weight,
		"isOn":                  req.IsOn,
		"domains":               req.Domains,
		"certRefJSON":           req.CertRefJSON,
		"host":                  req.Host,
		"followPort":            req.FollowPort,
		"http2Enabled":          req.Http2Enabled,
		"tlsSecurityVerifyMode": req.TlsSecurityVerifyMode,
	}
	apiUrl := s.Url + "OriginService/updateOrigin"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl) // 使用封装后的方法
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// AddServerOrigin 网站绑定源站
func (s *cdnService) AddServerOrigin(ctx context.Context, serverId int64, originId int64) error {
	formData := map[string]interface{}{
		"serverId":  serverId,
		"originId":  originId,
		"isPrimary": true,
	}
	apiUrl := s.Url + "ServerService/addServerOrigin"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// EditOriginIsOn 编辑源站是否开启
func (s *cdnService) EditOriginIsOn(ctx context.Context, originId int64, isOn bool) error {
	formData := map[string]interface{}{
		"originId": originId,
		"isOn":     isOn,
	}
	apiUrl := s.Url + "OriginService/updateOriginIsOn"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// EditServerBasic 修改网站基本信息
func (s *cdnService) EditServerBasic(ctx context.Context, serverId int64, name string,nodeId int64) error {
	formData := map[string]interface{}{
		"serverId":      serverId,
		"name":          name,
		"nodeClusterId": nodeId,
		"isOn":          true,
	}
	apiUrl := s.Url + "ServerService/updateServerBasic"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// DelServerOrigin 从网站中删除某个源站
func (s *cdnService) DelServerOrigin(ctx context.Context, serverId int64, originId int64) error {
	formData := map[string]interface{}{
		"serverId": serverId,
		"originId": originId,
	}
	apiUrl := s.Url + "ServerService/deleteServerOrigin"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

func (s *cdnService) DelServer(ctx context.Context, serverId int64) error {
	formData := map[string]interface{}{
		"serverId": serverId,
	}
	apiUrl := s.Url + "ServerService/deleteServer"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// AddSSLCert 添加证书
func (s *cdnService) AddSSLCert(ctx context.Context, req v1.SSlCert) (int64, error) {
	formData := map[string]interface{}{
		"isOn":         req.IsOn,
		"userId":       req.UserId,
		"name":         req.Name,
		"serverName":   req.ServerName,
		"description":  req.Description,
		"isCA":         req.IsCA,
		"certData":     req.CertData,
		"keyData":      req.KeyData,
		"timeBeginAt":  req.TimeBeginAt,
		"timeEndAt":    req.TimeEndAt,
		"dnsNames":     req.DnsNames,
		"commonNames":  req.CommonNames,
		"isSelfSigned": req.IsSelfSigned,
	}
	apiUrl := s.Url + "SSLCertService/createSSLCert"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return 0, err
	}
	type DataStr struct {
		SslCertId int64 `json:"sslCertId" form:"sslCertId"`
	}
	var res v1.GeneralResponse[DataStr]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return 0, fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return 0, fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return res.Data.SslCertId, nil
}

// 修改网站域名
func (s *cdnService) EditServerName(ctx context.Context, req v1.EditServerNames) error {
	formData := map[string]interface{}{
		"serverId":        req.ServerId,
		"serverNamesJSON": req.ServerNamesJSON,
	}
	apiUrl := s.Url + "ServerService/updateServerNames"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// 添加ssl策略
func (s *cdnService) AddSSLPolicy(ctx context.Context, req v1.AddSSLPolicy) (int64, error) {
	formData := map[string]interface{}{
		"http2Enabled":     req.Http2Enabled,
		"http3Enabled":     req.Http3Enabled,
		"minVersion":       req.MinVersion,
		"sslCertsJSON":     req.SslCertsJSON,
		"hstsJSON":         req.HstsJSON,
		"clientAuthType":   req.ClientAuthType,
		"cipherSuites":     req.CipherSuites,
		"cipherSuitesIsOn": req.CipherSuitesIsOn,
		"ocspIsOn":         req.OcspIsOn,
	}
	apiUrl := s.Url + "SSLPolicyService/createSSLPolicy"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return 0, err
	}
	type DataStr struct {
		SslPolicyId int64 `json:"sslPolicyId" form:"sslPolicyId"`
	}
	var res v1.GeneralResponse[DataStr]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return 0, fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return 0, fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return res.Data.SslPolicyId, nil
}

func (s *cdnService) DelSSLCert(ctx context.Context, sslCertId int64) error {
	formData := map[string]interface{}{
		"sslCertId": sslCertId,
	}
	apiUrl := s.Url + "SSLCertService/deleteSSLCert"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil

}

func (s *cdnService) GetSSLPolicy(ctx context.Context, sslPolicyId int64) (v1.SSLPolicy, error) {
	formData := map[string]interface{}{
		"sslPolicyId": sslPolicyId,
		"ignoreData":  true,
	}
	apiUrl := s.Url + "SSLPolicyService/findEnabledSSLPolicyConfig"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return v1.SSLPolicy{}, err
	}
	var res v1.GeneralResponse[v1.SSLPolicy]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return v1.SSLPolicy{}, fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return v1.SSLPolicy{}, fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return res.Data, nil
}

func (s *cdnService) EditSSLCert(ctx context.Context, req v1.SSlCert) error {
	formData := map[string]interface{}{
		"sslCertId":    req.SslCertId,
		"userId":       req.UserId,
		"isOn":         req.IsOn,
		"name":         req.Name,
		"description":  req.Description,
		"isCA":         req.IsCA,
		"certData":     req.CertData,
		"keyData":      req.KeyData,
		"timeBeginAt":  req.TimeBeginAt,
		"timeEndAt":    req.TimeEndAt,
		"dnsNames":     req.DnsNames,
		"commonNames":  req.CommonNames,
		"isSelfSigned": req.IsSelfSigned,
	}
	apiUrl := s.Url + "SSLCertService/updateSSLCert"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil

}

func (s *cdnService) EditSSLPolicy(ctx context.Context, req v1.SSLPolicy) error {
	formData := map[string]interface{}{
		"sslPolicyId":      req.SslPolicyId,
		"http2Enabled":     req.Http2Enabled,
		"http3Enabled":     req.Http3Enabled,
		"minVersion":       req.MinVersion,
		"sslCertsJSON":     req.SslCertsJSON,
		"hstsJSON":         req.HstsJSON,
		"clientAuthType":   req.ClientAuthType,
		"cipherSuites":     req.CipherSuites,
		"cipherSuitesIsOn": req.CipherSuitesIsOn,
	}
	apiUrl := s.Url + "SSLPolicyService/updateSSLPolicy"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil

}

// 修改反向代理
func (s *cdnService) EditProxy(ctx context.Context, req v1.Proxy) error {
	formData := map[string]interface{}{
		"reverseProxyId"   : req.ReverseProxyId,
		"requestHostType"  : req.RequestHostType,
		"requestHost"      : req.RequestHost,
		"requestHostExcludingPort" : req.RequestHostExcludingPort,
		"requestURI"       : req.RequestURI,
		"stripPrefix"      : req.StripPrefix,
		"autoFlush"        : req.AutoFlush,
		"addHeaders"       : req.AddHeaders,
		"proxyProtocolJSON": req.ProxyProtocolJSON,
		"followRedirects"  : req.FollowRedirects,
		"retry50X"         : req.Retry50X,
		"retry40X"         : req.Retry40X,
	}
	apiUrl := s.Url + "ReverseProxyService/updateReverseProxy"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// 修改网站日志配置
func (s *cdnService) EditWebLog(ctx context.Context,webId int64, req v1.WebLog) error {
	reqJson, err := json.Marshal(req)
	if err != nil {
		return err
	}
	formData := map[string]interface{}{
		"httpWebId": webId,
		"accessLogJSON":   reqJson,
	}
	apiUrl := s.Url + "HTTPWebService/updateHTTPWebAccessLog"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// 修改网站CC配置
func (s *cdnService) EditCcConfig(ctx context.Context,webId int64, req v1.CcConfig) error {
	reqJson, err := json.Marshal(req)
	if err != nil {
		return err
	}
	formData := map[string]interface{}{
		"httpWebId":            webId,
		"ccJSON": 				reqJson,
	}
	apiUrl := s.Url + "HTTPWebService/updateHTTPWebCC"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}


// 创建websockets配置
func (s *cdnService) AddWebSockets(ctx context.Context, req v1.WebSocket) (int64,error) {
	formData := map[string]interface{}{
		"handshakeTimeoutJSON": req.HandshakeTimeoutJSON,
		"allowAllOrigins"      : req.AllowAllOrigins,
		"allowedOrigins"       : req.AllowedOrigins,
		"requestSameOrigin"    : req.RequestSameOrigin,
		"requestOrigin"        : req.RequestOrigin,
	}
	apiUrl := s.Url + "HTTPWebsocketService/createHTTPWebsocket"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return 0,err
	}
	type WebSocket struct {
		WebSocketId int64 `json:"websocketId"`
	}
	var res v1.GeneralResponse[WebSocket]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return 0,fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return 0,fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return res.Data.WebSocketId,nil
}

func (s *cdnService) EditWebSockets(ctx context.Context,req v1.WebSocket) error {
	formData := map[string]interface{}{
		"websocketId"          : req.WebsocketId,
		"handshakeTimeoutJSON": req.HandshakeTimeoutJSON,
		"allowAllOrigins"      : req.AllowAllOrigins,
		"allowedOrigins"       : req.AllowedOrigins,
		"requestSameOrigin"    : req.RequestSameOrigin,
		"requestOrigin"        : req.RequestOrigin,
	}
	apiUrl := s.Url + "HTTPWebsocketService/updateHTTPWebsocket"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// 启用/禁用websockets
func (s *cdnService) EditHTTPWebWebsocket(ctx context.Context,websocketId int64,websocketJSON []byte) error {
	formData := map[string]interface{}{
		"httpWebId"          : websocketId,
		"websocketJSON":       websocketJSON,
	}
	apiUrl := s.Url + "HTTPWebService/updateHTTPWebWebsocket"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// 启用/禁用网站
func (s *cdnService) EditWebIsOn(ctx context.Context,serverId int64,isOn bool) error {
	formData := map[string]interface{}{
		"serverId": serverId,
		"isOn":     isOn,
	}
	apiUrl := s.Url + "ServerService/updateServerIsOn"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// 删除已购套餐
func (s *cdnService) DelUserPlan(ctx context.Context,planId int64) error {
	formData := map[string]interface{}{
		"userPlanId": planId,
	}
	apiUrl := s.Url + "UserPlanService/deleteUserPlan"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// 删除网站分组
func (s *cdnService) DelServerGroup(ctx context.Context,serverId int64) error {
	formData := map[string]interface{}{
		"serverId": serverId,
	}
	apiUrl := s.Url + "ServerService/deleteServer"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// 删除IP
func (s *cdnService) DelIpItem(ctx context.Context,ipitemId int64,value string,ipFrom string,ipTo string,ipListId int64) error {
	formData := map[string]interface{}{
		"ipitemId": ipitemId,
		"value":    value,
		"ipFrom":   ipFrom,
		"ipTo":     ipTo,
		"ipListId": ipListId,
	}
	apiUrl := s.Url + "IPItemService/deleteIPItem"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// 创建空防火墙策略
func (s *cdnService) AddWafPolicy(ctx context.Context,req v1.AddWafPolicy) (int64, error) {
	formData := map[string]interface{}{
		"isOn":     req.IsOn,
		"name"     : req.Name,
		"description" : req.Description,
		"serverId" : req.ServerId,
		"serverGroupId" : req.ServerGroupId,
	}
	apiUrl := s.Url + "HTTPFirewallPolicyService/createEmptyHTTPFirewallPolicy"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return 0, err
	}
	var res v1.GeneralResponse[map[string]int64]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return 0, fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return 0, fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	if res.Data["httpFirewallPolicyId"] == 0 {
		return 0, fmt.Errorf("创建空防火墙策略失败")
	}
	return res.Data["httpFirewallPolicyId"], nil
}

// 更改防火墙设置
func (s *cdnService) EditHTTPWebFirewal(ctx context.Context,httpWebId int64,FirewallJSON v1.Firewall) error {

	frireWallJson,err := json.Marshal(FirewallJSON)
	if err != nil {
		return err
	}

	formData := map[string]interface{}{
		"httpWebId" : httpWebId,
		"firewallJSON" : frireWallJson,
	}

	apiUrl := s.Url + "HTTPWebService/updateHTTPWebFirewall"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil

}


// 创建IP列表
func (s *cdnService) AddIPList(ctx context.Context, req v1.IPListRequest) (int64, error) {
	formData := map[string]interface{}{
		"type": req.Type,
		"name": req.Name,
		"code": req.Code,
		"timeoutJSON": req.TimeoutJSON,
		"isPublic": req.IsPublic,
		"description": req.Description,
		"isGlobal": req.IsGlobal,
		"serverId": req.ServerId,
	}
	apiUrl := s.Url + "IPListService/createIPList"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return 0, err
	}
	var res v1.GeneralResponse[int64]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return 0, fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return 0, fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return res.Data, nil
}

// 创建IP
func (s *cdnService) AddIpItem(ctx context.Context, req v1.AddIpItem) error {
	formData := map[string]interface{}{
		"ipListId": req.IpListId,
		"value":    req.Value,
		"ipFrom":   req.IpFrom,
		"ipTo":     req.IpTo,
		"expiredAt": req.ExpiredAt,
		"reason":   req.Reason,
		"type":     req.Type,
		"eventLevel": req.EventLevel,
		"nodeId": req.NodeId,
		"serverId": req.ServerId,
		"sourceNodeId": req.SourceNodeId,
		"sourceServerId": req.SourceServerId,
		"sourceHTTPFirewallPolicyId": req.SourceHTTPFirewallPolicyId,
		"sourceHTTPFirewallRuleGroupId": req.SourceHTTPFirewallRuleGroupId,
		"sourceHTTPFirewallRuleSetId": req.SourceHTTPFirewallRuleSetId,
		"sourceURL": req.SourceURL,
		"sourceUserAgent": req.SourceUserAgent,
		"sourceCategory": req.SourceCategory,
	}
	apiUrl := s.Url + "IPItemService/createIPItem"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// 修改IP
func (s *cdnService) EditIpItem(ctx context.Context, req v1.AddIpItem) error {
	formData := map[string]interface{}{
		"ipItemId": req.IpItemId,
		"value":    req.Value,
		"reason"   : req.Reason,
		"type"     : req.Type,
		"eventLevel" : req.EventLevel,
	}
	apiUrl := s.Url + "IPItemService/updateIPItem"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return err
	}
	var res v1.GeneralResponse[any]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return nil
}

// 获取访问日志
func (s *cdnService) GetAccessLog(ctx context.Context, req cdn.Request) (cdn.Data, error) {
	formData := map[string]interface{}{
		"serverId": req.ServerID,
		"size":     req.Size,
		"day" :     req.Day,
		"ip":       req.Ip,
		"domain":   req.Domain,
		"hasError": &req.HasError,
		"hourFrom": req.HourFrom,
		"hourTo":   req.HourTo,
		"reverse" : req.Reverse,
		"requestId": req.RequestId,
		"keyword" : req.Keyword,
	}
	apiUrl := s.Url + "HTTPAccessLogService/listHTTPAccessLogs"
	resBody, err := s.sendDataWithTokenRetry(ctx, formData, apiUrl)
	if err != nil {
		return cdn.Data{}, err
	}
	var res v1.GeneralResponse[cdn.Data]
	if err := json.Unmarshal(resBody, &res); err != nil {
		return cdn.Data{}, fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
	}
	if res.Code != 200 {
		return cdn.Data{}, fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Message)
	}
	return res.Data, nil
}