package test

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"testing"
	"time"
	"voucher/internal/biz/bo"
	"voucher/internal/biz/businesserr"
	"voucher/internal/pkg/helper"
	"voucher/internal/pkg/supplier/qixing"
	"voucher/internal/pkg/wechat/utils"
)

func Test_MarketingSend(t *testing.T) {
	tests := []struct {
		name string
	}{
		{
			name: "给指定用户报名多笔立减活动",
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			MarketingSend()
		})
	}
}

func Test_MarketingQuery(t *testing.T) {

	appId := "wx619991cc795028f5"
	openId := "oSNb4fixFZ4uRvcP6F25_FySgUE0"
	couponId := "147079366189"

	tests := []struct {
		name                    string
		appId, openId, couponId string
	}{
		{
			name:     "查询绑定多笔立减活动的代金券详情", // 查询的商户非创建方商户 查询商户要为创建方商户
			appId:    appId,
			openId:   openId,
			couponId: couponId,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			resp, err := MarketingQuery(tt.appId, tt.openId, tt.couponId)
			if err != nil {

				var e *utils.ApiException
				if errors.As(err, &e) {
					// 格式：{"code":"INVALID_REQUEST","message":"对应单号已超出重试期;请查单确认后决定是否换单请求"}
					var beer *businesserr.BusinessErr
					if err = json.Unmarshal(e.Body(), &beer); err != nil {
						t.Errorf("微信错误返回body解析报错,body:%s,err:%s", string(e.Body()), err.Error())
					}
					t.Logf("MarketingQuery error,body:%s,err:%s", string(e.Body()), e.ErrCode)
				} else {
					t.Errorf("MarketingQuery() error = %v", err)
				}

				return
			}
			t.Logf("MarketingQuery() = %v", resp)
		})
	}

	// 合单订单就是没有核销回调通知的
	// {"code":"APPID_MCHID_NOT_MATCH","message":"商户号与AppID不匹配"}
	// APPID_MCHID_NOT_MATCH 商户号与AppID不匹配 调用接口的商户号需与接口传入的AppID有绑定关系

	//openid不是自己的appid下的喔，这也能查询到吗”
	//不行的，需要是在自己appid下的才能查到
}

func Test_QixingNotifyDataDecodeString(t *testing.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VudCI6MzAwLCJnb29kc19kZXRhaWwiOm51bGx9fSwicmVzb3VyY2VfdHlwZSI6ImVuY3J5cHQtcmVzb3VyY2UiLCJvcmlnaW5hbF90eXBlIjoiY291cG9uIiwiaWQiOiI4NzkxZTMyZS0zYjFiLTViNDktYTNiNi1mYzY0YTc5NTVlZjEifQ==`

	b, err := base64.StdEncoding.DecodeString(content)
	if err != nil {
		t.Errorf("base64.StdEncoding.DecodeString() error = %v", err)
		return
	}

	t.Log(string(b))
}

func Test_QixingNotifyData(t *testing.T) {

	//wxBody := `{"id":"4ab2699d-e91d-5460-9810-25fd6d4c69a5","create_time":"2025-12-08T17:54:24+08:00","resource_type":"encrypt-resource","event_type":"COUPON.USE","summary":"代金券核销通知","original_type":"coupon","associated_data":"coupon","plain_text":{"stock_creator_mchid":"1652465541","stock_id":"21386484","coupon_id":"142388354994","coupon_name":"银行卡多笔立减","description":"","status":"SENDED","create_time":"2025-12-08T17:50:48+08:00","coupon_type":"NORMAL","no_cash":false,"singleitem":false,"business_type":"","consume_information":{"consume_time":"2025-12-08T17:54:24+08:00","consume_mchid":"1274938601","transaction_id":"4200002996202512083063051834","consume_amount":16}}}`
	wxBody := `{"id":"4ab2699d-e91d-5460-9810-25fd6d4c69a6","create_time":"2025-12-08T17:54:24+08:00","resource_type":"encrypt-resource","event_type":"COUPON.USE","summary":"代金券核销通知","original_type":"coupon","associated_data":"coupon","plain_text":{"stock_creator_mchid":"1652465541","stock_id":"21386484","coupon_id":"118758145502","coupon_name":"银行卡多笔立减","description":"","status":"USED","create_time":"2025-12-08T17:50:48+08:00","coupon_type":"NORMAL","no_cash":false,"singleitem":false,"business_type":"","consume_information":{"consume_time":"2025-12-08T17:54:24+08:00","consume_mchid":"1274938601","transaction_id":"4200002996202512083063051834","consume_amount":16}}}`
	t.Log(len(wxBody))

	content := base64.StdEncoding.EncodeToString([]byte(wxBody))

	ciphertext := helper.Md5(content + "DrY1zLkOH01q0sN66vrmkdpbWsyb41ho")

	req := qixing.QiXingRequestBo{
		Content:    content,
		Timestamp:  time.Now().UnixMilli(),
		Ciphertext: ciphertext,
	}

	b, _ := json.Marshal(req)

	t.Log(string(b))
	// {"content":"base64(微信通知json对象数据)","timestamp":1765447477945,"ciphertext":"md5(base64(微信通知json对象数据)+key)"}
	//t.Logf(`{"content":"%s","timestamp":122345677890,"ciphertext":"%s"}`, content, ciphertext)
}

func Test_MarketingNotify(t *testing.T) {

	headerBytes := []byte(`{"Accept":["*/*"],"Cache-Control":["no-cache"],"Connection":["close"],"Content-Length":["1137"],"Content-Type":["application/json"],"Pragma":["no-cache"],"User-Agent":["Mozilla/4.0"],"Wechatpay-Nonce":["kHzkvdHwssdU0CRpFfgCpzdxtdzQGsIS"],"Wechatpay-Serial":["PUB_KEY_ID_0111000406952026032500382251001000"],"Wechatpay-Signature":["jt/2zYvqTlvOHAb9Lb1bfbLUDnqy59dc1JF87AiHVtagZAxzWNP5Jgsrr/jv9C3UVv+MHvbTxuaDQjJAfXx4CT7ihYUNEF6rQL/ilToSMuZpw23/pPjyAzXvBWBsj3AY3rxfa4OkaviRnG6vRA5HKnaHHG5wmDdrcwOoKBiLJ6cax8OYu9GV8Opr0uSzWj7ZxPoSxXy65MxEaampVXJcLnCm1iVp2mHZH6jafBxyjhDGIZ6uOJD0LdCUCJMfbDKvlthO7CrfLRsdosVrVmnL3lJU2ti5rjngmzAxHFi+J4JUsbTvkWnBEXZXaXZ4vNi4gkGnOGPJHs4ch+s0MV/ZFg=="],"Wechatpay-Signature-Type":["WECHATPAY2-SHA256-RSA2048"],"Wechatpay-Timestamp":["1774605950"],"X-Forwarded-For":["121.51.58.172, 172.17.0.1"]}`)
	bodyBytes := []byte(`{"id":"4a5e22d9-9018-5bfc-94ba-3c9957a62355","create_time":"2026-03-27T18:05:50+08:00","resource_type":"encrypt-resource","event_type":"COUPON.USE","summary":"代金券核销通知","resource":{"original_type":"coupon","algorithm":"AEAD_AES_256_GCM","ciphertext":"aTS2kVk7l/lzfIEUMUVfk5+6ouRSakspFTP/nR4sDPp0nvrj2VtEQBXkYqTgDDxs35V9CrJI90X31Mho2+adZm1ScPPH0HL6iUaUcypzgvHAhSaJBhugz8slqoQ3zaynBKa/HpyU6Jnfd3OTbhcrS2i27cBdWawd2UQ5HBgAemV8/k/gf+LPC04fJNFfrrttTxqtBDpXr3H/ob5pV825C57SJJhpXxgZtnX/e9avpWZlPIXhOSA3FSwYZtoW1BYoXrsLID6fGcP5IJuc8EE40Z7si95tQbQcM1eqH19OZbRAmXitV+sY1pOlo0Zehnc5vyH5RunVYa2lwdsirSGU1EI0PlDYwHoNxUEtSpKZ4MP8IReNdkjKlwpBQXtgZMGqMNdDU+/Db/ZUr/R8xaF7RoHfiiTHEHQaEK9xbCZji+F8YDiU0K8I8getKsyHiZwHZrU67p/6ql6zVzcWBjaDyL71tcl1k1ppkyOFdg9g0WqcJD56xa9qMhXaOyQoIU4hJsMMTvBWxyRelE4+o1Z79nUVUMswvg/hPZ4QEeIF8C+ezzk+/PhggYhZE4g4WnzqKRh/WASXRja0UsucBVIs9hViV+aDuQVEjxmy29S3UTrwL0Kr0+5hUz7q87gJUaAvehF6pIPtvliJvR0tnpdCrLHuIsc/LiSxoX2WSkGGZet58swdJ7wHYzdfNFKbhRS2IBj4JzI6wc+zRkGmLCijTRFSadZGnNZf5SPez1iEqr0fecCDjN6NUMv/YETfjeEqUxRvNVjMK9vCzEm+bdVJNNL+3i5RiJA9Bng1JtmTMsHatgn8dg==","associated_data":"coupon","nonce":"L3TIxaSQ12pD"}}`)

	httpHeaders := make(http.Header)
	if err := json.Unmarshal(headerBytes, &httpHeaders); err != nil {
		fmt.Printf("headers Unmarshal err: %+v\n", err)
		return
	}

	body, bizContent, err := marketingFJLF().Notify(context.Background(), &httpHeaders, bodyBytes)
	if err != nil {
		t.Errorf("notify err: %+v\n", err)
		return
	}

	var plainText bo.PlainText
	if err = json.Unmarshal([]byte(bizContent), &plainText); err != nil {
		t.Errorf("Unmarshal err: %+v\n", err)
		return
	}

	notifyBo := bo.WechatVoucherNotifyBo{
		ID:             body.Id,
		CreateTime:     body.CreateTime,
		ResourceType:   body.ResourceType,
		EventType:      body.EventType,
		Summary:        body.Summary,
		OriginalType:   body.Resource.OriginalType,
		AssociatedData: body.Resource.AssociatedData,
		PlainText:      plainText,
	}

	fmt.Printf("bizContent: %s\n", bizContent)
	fmt.Printf("notifyBo: %+v\n", notifyBo)
}
