package test

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/services/cashcoupons"
	"io"
	"os"
	"path/filepath"
	"time"
	v1 "voucher/api/v1"
	"voucher/internal/biz/businesserr"
	"voucher/internal/biz/vo"
	"voucher/internal/conf"
	"voucher/internal/data"
)

var bc = &conf.Bootstrap{
	Wechat: &conf.Wechat{
		MchID:                      "1710953361",
		MchCertificateSerialNumber: "6006B8208815DB5EAC5BF2E783CB9D34082C3772",
		WechatPayPublicKeyID:       "PUB_KEY_ID_0117109533612025031800326400002563",
		Name:                       "蓝色兄弟-new",
	},
}

// bcFJXW Callback{NotifyUrl:https://nsall.86698.cn/wechatPay/coupon_notify/fjxingwang, Mchid:1652465541}
var bcFJXW = &conf.Bootstrap{
	Wechat: &conf.Wechat{
		MchID:                      "1652465541", // notifyUrl https://nsall.86698.cn/wechatPay/coupon_notify/fjxingwang
		MchCertificateSerialNumber: "1E3F2CE013203BA9C3DEFC5782FCD3329C3DAC1C",
		WechatPayPublicKeyID:       "PUB_KEY_ID_0116524655412025070900181741001803",
		Name:                       "福建兴旺",
	},
}

// bcFJLF Callback{NotifyUrl:https://gateway.dev.cdlsxd.cn/voucher/v1/notify/1100040695, Mchid:1100040695}
// /voucher/v1/notify/1100040695
var bcFJLF = &conf.Bootstrap{
	Wechat: &conf.Wechat{
		MchID:                      "1100040695",
		MchCertificateSerialNumber: "46712853869DB0EDAA9B4DF97DADEECD4CCDC85B",
		WechatPayPublicKeyID:       "PUB_KEY_ID_0111000406952026032500382251001000",
		Name:                       "福建峦峰",
	},
}

func SendCoupon() error {

	ctx := context.Background()

	dir, err := os.Getwd()
	if err != nil {
		return fmt.Errorf("os.Getwd() error = %v", err)
	}
	parentDir := filepath.Dir(dir)

	server := data.Server{
		MchID:                      bc.Wechat.MchID,
		MchCertificateSerialNumber: bc.Wechat.MchCertificateSerialNumber,
		WechatPayPublicKeyID:       bc.Wechat.WechatPayPublicKeyID,
		Dir:                        parentDir,
	}
	client, err := data.GetClient(ctx, server)
	if err != nil {
		return fmt.Errorf("data.GetClient(ctx, server) error = %v", err)
	}

	req := cashcoupons.SendCouponRequest{
		OutRequestNo: core.String("LQ2011991700944699394"), // {CouponId:129623470711}
		// 微信为发券方商户分配的公众账号ID，接口传入的所有appid应该为公众号的appid（在mp.weixin.qq.com申请的），不能为APP的appid（在open.weixin.qq.com申请的）。
		Appid:             core.String("wxd27e255810842ba8"),
		Openid:            core.String("o3dEt5b_1lFtKc-aAT3tiYjJIGwk"),
		StockId:           core.String("21502886"),
		StockCreatorMchid: core.String("16524655411111"),
	}
	fmt.Printf("\nreq:%+v", req)

	svc := cashcoupons.CouponApiService{Client: client}

	resp, result, err := svc.SendCoupon(ctx, req)

	if err != nil {

		bodyBytes, err := io.ReadAll(result.Response.Body)
		if err != nil {
			return fmt.Errorf("读取微信错误返回body报错:%s", err.Error())
		}
		fmt.Printf("\nbodyBytes:%s\n", string(bodyBytes))

		var beer *businesserr.BusinessErr
		if err = json.Unmarshal(bodyBytes, &beer); err != nil {
			return fmt.Errorf("微信错误返回body解析报错,body:%s,err:%s", string(bodyBytes), err.Error())
		}

		return beer
	}

	fmt.Printf("\nresp:%+v\n result:%+v", resp, result)
	return nil
}

func QueryCoupon(appId, openId, couponId string) {

	ctx := context.Background()

	dir, err := os.Getwd()
	if err != nil {
		fmt.Printf("os.Getwd() error = %v", err)
		return
	}
	parentDir := filepath.Dir(dir)

	server := data.Server{
		MchID:                      bc.Wechat.MchID,
		MchCertificateSerialNumber: bc.Wechat.MchCertificateSerialNumber,
		WechatPayPublicKeyID:       bc.Wechat.WechatPayPublicKeyID,
		Dir:                        parentDir,
	}
	client, err := data.GetClient(ctx, server)
	if err != nil {
		fmt.Println(err)
		return
	}

	req := cashcoupons.QueryCouponRequest{
		CouponId: core.String(couponId),
		Appid:    core.String(appId),
		Openid:   core.String(openId),
	}

	svc := cashcoupons.CouponApiService{Client: client}

	resp, result, err := svc.QueryCoupon(ctx, req)

	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("\nresp:%+v\n", resp)

	bodyBytes, err := io.ReadAll(result.Response.Body)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("\nresult:%s\n", bodyBytes)
	return
}

func QueryProduct() {

	ctx := context.Background()

	dir, err := os.Getwd()
	if err != nil {
		fmt.Printf("os.Getwd() error = %v", err)
		return
	}
	parentDir := filepath.Dir(dir)

	server := data.Server{
		MchID:                      bc.Wechat.MchID,
		MchCertificateSerialNumber: bc.Wechat.MchCertificateSerialNumber,
		WechatPayPublicKeyID:       bc.Wechat.WechatPayPublicKeyID,
		Dir:                        parentDir,
	}
	client, err := data.GetClient(ctx, server)
	if err != nil {
		fmt.Println(err)
		return
	}

	req := cashcoupons.QueryStockRequest{
		StockId:           core.String("21928191"),
		StockCreatorMchid: core.String("1100040695"),
	}

	svc := cashcoupons.StockApiService{Client: client}
	resp, _, err := svc.QueryStock(ctx, req)
	if err != nil {
		fmt.Println(err)
		return
	}

	originData, _ := json.Marshal(resp)
	fmt.Printf("\nOriginData:%s\n", string(originData))

	availableStock := *resp.StockUseRule.MaxCoupons - *resp.DistributedCoupons
	couponAmount := *resp.StockUseRule.FixedNormalCoupon.CouponAmount / 100

	fmt.Printf("\n批次号:%s", *req.StockId)
	fmt.Printf("\n面额:%d", couponAmount)
	fmt.Printf("\n总预算:%d", *resp.StockUseRule.MaxAmount/100)
	fmt.Printf("\n总库存:%d", *resp.StockUseRule.MaxCoupons)
	fmt.Printf("\n已发券数:%d", *resp.DistributedCoupons)
	fmt.Printf("\n已发券金额:%d", *resp.DistributedCoupons*couponAmount)
	fmt.Printf("\n剩余库存:%d", availableStock)
	fmt.Printf("\n剩余预算:%d", availableStock*couponAmount)

	WxResp(resp)

	return
}

func WxResp(wxResp *cashcoupons.Stock) {

	xx := &v1.CmbQueryProductReply{
		RespCode:       vo.CmbResponseStatusSuccess.GetValue(),
		RespMsg:        "成功",
		ActivityName:   *wxResp.StockName,
		ActivityId:     "CMB" + *wxResp.StockId,
		Amount:         "",
		MinAmount:      "",
		AvailableType:  "",
		AvailableDays:  "", // 动态有效期天数
		StartTime:      "",
		EndTime:        "",
		AvailableStock: "",
		Detail:         *wxResp.Description,
	}

	inputFormat := time.RFC3339

	if wxResp.AvailableBeginTime != nil {

		availableBeginTime, _ := time.Parse(inputFormat, *wxResp.AvailableBeginTime)
		xx.StartTime = availableBeginTime.Format("2006-01-02 15:04:05.000")
		xx.SaleStartTime = xx.StartTime
	}

	if wxResp.AvailableEndTime != nil {
		availableEndTime, _ := time.Parse(inputFormat, *wxResp.AvailableEndTime)
		xx.EndTime = availableEndTime.Format("2006-01-02 15:04:05.000")
		xx.SaleEndTime = xx.EndTime
	}

	xx.Amount = fmt.Sprintf("%d", *wxResp.StockUseRule.FixedNormalCoupon.CouponAmount)
	xx.MinAmount = fmt.Sprintf("%d", *wxResp.StockUseRule.FixedNormalCoupon.TransactionMinimum)

	availableStock := *wxResp.StockUseRule.MaxCoupons - *wxResp.DistributedCoupons
	xx.AvailableStock = fmt.Sprintf("%d", availableStock)

	cmbData, _ := json.Marshal(xx)
	fmt.Printf("\nCMB[%s]", string(cmbData))
}

func QueryCallback(bc *conf.Bootstrap) {

	ctx := context.Background()

	dir, err := os.Getwd()
	if err != nil {
		fmt.Printf("os.Getwd() error = %v", err)
		return
	}
	parentDir := filepath.Dir(dir)

	server := data.Server{
		MchID:                      bc.Wechat.MchID,
		MchCertificateSerialNumber: bc.Wechat.MchCertificateSerialNumber,
		WechatPayPublicKeyID:       bc.Wechat.WechatPayPublicKeyID,
		Dir:                        parentDir,
	}
	client, err := data.GetClient(ctx, server)
	if err != nil {
		fmt.Println(err)
		return
	}

	svc := cashcoupons.CallBackUrlApiService{Client: client}

	response, _, err := svc.QueryCallback(ctx, cashcoupons.QueryCallbackRequest{
		Mchid: core.String(bc.Wechat.MchID),
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("\nresp:%+v\n", response)
	return
}

func SetCallback(bc *conf.Bootstrap) {

	ctx := context.Background()

	dir, err := os.Getwd()
	if err != nil {
		fmt.Printf("os.Getwd() error = %v", err)
		return
	}
	parentDir := filepath.Dir(dir)

	server := data.Server{
		MchID:                      bc.Wechat.MchID,
		MchCertificateSerialNumber: bc.Wechat.MchCertificateSerialNumber,
		WechatPayPublicKeyID:       bc.Wechat.WechatPayPublicKeyID,
		Dir:                        parentDir,
	}
	client, err := data.GetClient(ctx, server)
	if err != nil {
		fmt.Println(err)
		return
	}

	svc := cashcoupons.CallBackUrlApiService{Client: client}

	response, _, err := svc.SetCallback(ctx, cashcoupons.SetCallbackRequest{
		Mchid: core.String(bc.Wechat.MchID),
		//NotifyUrl: core.String("https://gateway.dev.cdlsxd.cn/voucher/v1/notify/" + bc.Wechat.MchID),
		NotifyUrl: core.String("https://voucher.86698.cn/voucher/v1/notify/" + bc.Wechat.MchID),
		Switch:    core.Bool(true),
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("\nresp:%+v\n", response)
	return
}
