package test

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"testing"
	"time"
	v1 "voucher/api/v1"
	"voucher/internal/biz/vo"
	"voucher/internal/pkg/cmb"
	"voucher/internal/pkg/helper"
	"voucher/internal/pkg/request"
)

func Test_CMBRequest(t *testing.T) {

	bizParma := &v1.CmbNotifyRequest{
		Ticket:        "190662195271022592015",                                            // 优惠券券码，codeNo
		Status:        "0",                                                                // 更新后串码状态，0：可使用，1：已使用
		TransDate:     "",                                                                 //  验码日期，格式yyyy-mm-dd hh:mm:ss.sss
		OrgNo:         "LANSEXIONGDI",                                                     // 固定值
		Ext:           "",                                                                 // 扩展字段
		Attach:        "bFUWzuzvJfBshobjcQPFTvpqcH1AvGqHJtiV44mdsWEQKCPXgydk8ft/b227S3TM", // 扩展字段
		TransactionId: "2000000000001422730",                                              // 招行唯一流水号
	}

	bizParmaJsonBytes, err := json.Marshal(bizParma)
	if err != nil {
		t.Error(err)
		return
	}

	encryptBody, err := cmb.EncryptBody(&cmb.Encrypts{SoaPubKey: "0416445bc16cbf42e47002ad9fe7c7af67d902b48be1eb69b98f6a006b0918630e1127f5f2fff83b2ecb30fc7fd72c34c33f37c7c355dffde3589f66800f0036ca", JsonParam: string(bizParmaJsonBytes)})
	if err != nil {
		t.Error(err)
		return
	}

	req := &v1.CmbRequest{
		Mid:         "d6fdd78b6fd13a808818286b9cad9687",
		Aid:         "5efaa21263b94f669a1c90ed0279df20",
		Date:        time.Now().Format("20060102150405"),
		Random:      string(cmb.RandomBytes(16)),
		KeyAlias:    "CO_PUB_KEY_SM2",
		CmbKeyAlias: "SM2_CMBLIFE",
		EncryptBody: encryptBody,
		Sign:        "",
	}

	str := fmt.Sprintf("%s?%s", vo.CmbNotifyFuncName, cmb.SortStructStr(req))

	sign, err := cmb.SignBody(str, "8d39ff3d2559258c163f4510f082727f51531e1953ab203d5ab1ea4a6d94fd73")
	if err != nil {
		t.Error(err)
		return
	}

	req.Sign = sign

	kvRows := helper.SortStructFieldsByKey(req)

	uv := url.Values{}

	for _, kv := range kvRows {
		uv.Set(kv.Key, fmt.Sprintf("%v", kv.Value))
	}

	h := http.Header{
		"Content-Type": []string{"application/x-www-form-urlencoded"},
	}

	uri := "https://sandbox.cdcc.cmbchina.com/AccessGateway/transIn/updateCodeStatus.json"
	r := uri + "?" + uv.Encode()

	respHeader, bodyBytes, err := request.Post(context.Background(), r, nil, request.WithHeaders(h), request.WithTimeout(time.Second*10))
	if err != nil {
		t.Error(err)
		return
	}

	t.Logf("请求地址:%s", uri)
	t.Logf("业务参数:%s", string(bizParmaJsonBytes))
	t.Logf("请求响应体:%s", string(bodyBytes))
	t.Logf("请求响应头:%+v", respHeader)
}

func Test_CmMultiRequest(t *testing.T) {

	bizParma := &v1.CmbMultiNotifyRequest{
		TransactionId: "2000000000001636670", // 招行唯一流水号
		ActivityId:    "11941580000000008",
		CouponId:      "118770338167",
		AcquiredDate:  "2025-08-25 14:56:54.123",
		Status:        "1",                       // 更新后串码状态，0：可使用，1：已使用
		CouponStatus:  "1",                       // String|M	整张券总状态0：可使用，1：已使用
		TransDate:     "2025-08-28 12:09:41.123", // 验码日期，格式yyyy-mm-dd hh:mm:ss.sss
		TransAmount:   "10",
		OrderId:       "4200002772202508280813272296",
		Ticket:        "195987259358664294429",                                            // 优惠券券码，codeNo
		OrgNo:         "LANSEXIONGDI",                                                     // 固定值
		Attach:        "bFUWzuzvJfBshobjcQPFTvpqcH1AvGqHJtiV44mdsWEQKCPXgydk8ft/b227S3TM", // 扩展字段
		Ext:           "",                                                                 // 扩展字段
	}

	bizParmaJsonBytes, err := json.Marshal(bizParma)
	if err != nil {
		t.Error(err)
		return
	}

	encryptBody, err := cmb.EncryptBody(&cmb.Encrypts{SoaPubKey: "0416445bc16cbf42e47002ad9fe7c7af67d902b48be1eb69b98f6a006b0918630e1127f5f2fff83b2ecb30fc7fd72c34c33f37c7c355dffde3589f66800f0036ca", JsonParam: string(bizParmaJsonBytes)})
	if err != nil {
		t.Error(err)
		return
	}

	req := &v1.CmbRequest{
		Mid:         "d6fdd78b6fd13a808818286b9cad9687",
		Aid:         "5efaa21263b94f669a1c90ed0279df20",
		Date:        time.Now().Format("20060102150405"),
		Random:      string(cmb.RandomBytes(16)),
		KeyAlias:    "CO_PUB_KEY_SM2",
		CmbKeyAlias: "SM2_CMBLIFE",
		EncryptBody: encryptBody,
		Sign:        "",
	}

	str := fmt.Sprintf("%s?%s", vo.CmbNotifyFuncNameUpdateCodeStatusForMulti, cmb.SortStructStr(req))

	sign, err := cmb.SignBody(str, "8d39ff3d2559258c163f4510f082727f51531e1953ab203d5ab1ea4a6d94fd73")
	if err != nil {
		t.Error(err)
		return
	}

	req.Sign = sign

	kvRows := helper.SortStructFieldsByKey(req)

	uv := url.Values{}

	for _, kv := range kvRows {
		uv.Set(kv.Key, fmt.Sprintf("%v", kv.Value))
	}

	h := http.Header{
		"Content-Type": []string{"application/x-www-form-urlencoded"},
	}

	uri := "https://sandbox.cdcc.cmbchina.com/AccessGateway/transIn/updateCodeStatusForMulti.json"
	r := uri + "?" + uv.Encode()

	respHeader, bodyBytes, err := request.Post(context.Background(), r, nil, request.WithHeaders(h), request.WithTimeout(time.Second*10))
	if err != nil {
		t.Error(err)
		return
	}

	t.Logf("请求地址:%s", uri)
	t.Logf("业务参数:%s", string(bizParmaJsonBytes))
	t.Logf("请求响应体:%s", string(bodyBytes))
	t.Logf("请求响应头:%+v", respHeader)
}
