package service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strconv"
	"time"
	"ycc-server/app/main/api/internal/config"
	"ycc-server/pkg/lzkit/crypto"

	"github.com/pkg/errors"
)

type WestResp struct {
	Message   string `json:"message"`
	Code      string `json:"code"`
	Data      string `json:"data"`
	ID        string `json:"id"`
	ErrorCode *int   `json:"error_code"`
	Reason    string `json:"reason"`
}
type G05HZ01WestResp struct {
	Message   string          `json:"message"`
	Code      string          `json:"code"`
	Data      json.RawMessage `json:"data"`
	ID        string          `json:"id"`
	ErrorCode *int            `json:"error_code"`
	Reason    string          `json:"reason"`
}
type WestDexService struct {
	config config.WestConfig
}

// NewWestDexService 是一个构造函数，用于初始化 WestDexService
func NewWestDexService(c config.Config) *WestDexService {
	return &WestDexService{
		config: c.WestConfig,
	}
}

// CallAPI 调用西部数据的 API
func (w *WestDexService) CallAPI(code string, reqData map[string]interface{}) (resp []byte, err error) {
	// 生成当前的13位时间戳
	timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)

	// 构造请求URL
	reqUrl := fmt.Sprintf("%s/%s/%s?timestamp=%s", w.config.Url, w.config.SecretId, code, timestamp)

	jsonData, marshalErr := json.Marshal(reqData)
	if marshalErr != nil {
		return nil, marshalErr
	}

	// 创建HTTP POST请求
	req, newRequestErr := http.NewRequest("POST", reqUrl, bytes.NewBuffer(jsonData))
	if newRequestErr != nil {
		return nil, newRequestErr
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	httpResp, clientDoErr := client.Do(req)
	if clientDoErr != nil {
		return nil, clientDoErr
	}
	defer func(Body io.ReadCloser) {
		closeErr := Body.Close()
		if closeErr != nil {

		}
	}(httpResp.Body)

	// 检查请求是否成功
	if httpResp.StatusCode == 200 {
		// 读取响应体
		bodyBytes, ReadErr := io.ReadAll(httpResp.Body)
		if ReadErr != nil {
			return nil, ReadErr
		}

		// 手动调用 json.Unmarshal 触发自定义的 UnmarshalJSON 方法
		var westDexResp WestResp
		UnmarshalErr := json.Unmarshal(bodyBytes, &westDexResp)
		if UnmarshalErr != nil {
			return nil, UnmarshalErr
		}
		if westDexResp.Code != "00000" && westDexResp.Code != "0" {
			if westDexResp.Data == "" {
				return nil, errors.New(westDexResp.Message)
			}
			decryptedData, DecryptErr := crypto.WestDexDecrypt(westDexResp.Data, w.config.Key)
			if DecryptErr != nil {
				return nil, DecryptErr
			}
			return decryptedData, errors.New(westDexResp.Message)
		}
		if westDexResp.Data == "" {
			return nil, errors.New(westDexResp.Message)
		}
		decryptedData, DecryptErr := crypto.WestDexDecrypt(westDexResp.Data, w.config.Key)
		if DecryptErr != nil {
			return nil, DecryptErr
		}

		return decryptedData, nil
	}

	return nil, fmt.Errorf("西部请求失败Code: %d", httpResp.StatusCode)
}

// CallAPI 调用西部数据的 API
func (w *WestDexService) G05HZ01CallAPI(code string, reqData map[string]interface{}) (resp []byte, err error) {
	// 生成当前的13位时间戳
	timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)

	// 构造请求URL
	reqUrl := fmt.Sprintf("%s/%s/%s?timestamp=%s", w.config.Url, w.config.SecretSecondId, code, timestamp)

	jsonData, marshalErr := json.Marshal(reqData)
	if marshalErr != nil {
		return nil, marshalErr
	}

	// 创建HTTP POST请求
	req, newRequestErr := http.NewRequest("POST", reqUrl, bytes.NewBuffer(jsonData))
	if newRequestErr != nil {
		return nil, newRequestErr
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	httpResp, clientDoErr := client.Do(req)
	if clientDoErr != nil {
		return nil, clientDoErr
	}
	defer func(Body io.ReadCloser) {
		closeErr := Body.Close()
		if closeErr != nil {

		}
	}(httpResp.Body)

	// 检查请求是否成功
	if httpResp.StatusCode == 200 {
		// 读取响应体
		bodyBytes, ReadErr := io.ReadAll(httpResp.Body)
		if ReadErr != nil {
			return nil, ReadErr
		}

		// 手动调用 json.Unmarshal 触发自定义的 UnmarshalJSON 方法
		var westDexResp G05HZ01WestResp
		UnmarshalErr := json.Unmarshal(bodyBytes, &westDexResp)
		if UnmarshalErr != nil {
			return nil, UnmarshalErr
		}
		if westDexResp.Code != "0000" {
			if westDexResp.Data == nil {
				return nil, errors.New(westDexResp.Message)
			} else {
				return westDexResp.Data, errors.New(string(westDexResp.Data))
			}
		}
		if westDexResp.Data == nil {
			return nil, errors.New(westDexResp.Message)
		}
		return westDexResp.Data, nil
	}

	return nil, fmt.Errorf("西部请求失败Code: %d", httpResp.StatusCode)
}

func (w *WestDexService) Encrypt(data string) string {
	encryptedValue, err := crypto.WestDexEncrypt(data, w.config.Key)
	if err != nil {
		panic("WestDexEncrypt error: " + err.Error())
	}
	return encryptedValue
}

// GetDateRange 返回今天到明天的日期范围，格式为 "yyyyMMdd-yyyyMMdd"
func (w *WestDexService) GetDateRange() string {
	today := time.Now().Format("20060102")                        // 获取今天的日期
	tomorrow := time.Now().Add(24 * time.Hour).Format("20060102") // 获取明天的日期
	return fmt.Sprintf("%s-%s", today, tomorrow)                  // 拼接日期范围并返回
}
