package weixinapi

import (
	"encoding/json"
	"fmt"
	"strings"
)

// SNSSendGoodsOrder 小程序订单发货 https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/order-shipping/order-shipping.html#%E4%B8%80%E3%80%81%E5%8F%91%E8%B4%A7%E4%BF%A1%E6%81%AF%E5%BD%95%E5%85%A5%E6%8E%A5%E5%8F%A3
func (a *API) SNSSendGoodsOrder(param *SNSSendOrderParameter) error {
	body, _ := json.Marshal(param)
	if a.CBGetToken() == "" {
		a.CBRetrieveToken()
	}
	_, err := a.AccessAPI("wxa/sec/order/upload_shipping_info", nil, string(body))
	if err != nil && strings.Contains(err.Error(), "access_token is invalid") {
		a.CBRetrieveToken()
		return a.SNSSendGoodsOrder(param)
	}
	return err
}

// SNSSendOrderParameter 小程序订单发货
type SNSSendOrderParameter struct {
	OrderKey struct {
		OrderNumberType int    `json:"order_number_type"`
		TransactionId   string `json:"transaction_id"`
		Mchid           string `json:"mchid"`
		OutTradeNo      string `json:"out_trade_no"`
	} `json:"order_key"`
	LogisticsType  int            `json:"logistics_type"`
	DeliveryMode   int            `json:"delivery_mode"`
	IsAllDelivered bool           `json:"is_all_delivered"`
	ShippingList   []ShippingList `json:"shipping_list"`
	UploadTime     string         `json:"upload_time"`
	Payer          struct {
		Openid string `json:"openid"`
	} `json:"payer"`
}
type ShippingList struct {
	TrackingNo     string `json:"tracking_no"`
	ExpressCompany string `json:"express_company"`
	ItemDesc       string `json:"item_desc"`
	Contact        struct {
		ConsignorContact string `json:"consignor_contact"`
		ReceiverContact  string `json:"receiver_contact"`
	} `json:"contact"`
}

// SNSDeliveryGoodsOrder 订单送达推送
func (a *API) SNSDeliveryGoodsOrder(param *DeliveryOrder) error {
	body, _ := json.Marshal(param)
	if a.CBGetToken() == "" {
		a.CBRetrieveToken()
	}
	result, err := a.AccessAPI("wxa/sec/order/notify_confirm_receive", nil, string(body))
	fmt.Println(result)
	return err
}

type DeliveryOrder struct {
	TransactionId   string `json:"transaction_id"`    // 原支付交易对应的微信订单号
	MerchantId      string `json:"merchant_id"`       // 支付下单商户的商户号，由微信支付生成并下发
	MerchantTradeNo string `json:"merchant_trade_no"` // 商户系统内部订单号
	SubMerchantId   string `json:"sub_merchant_id"`   // 二级商户号
	ReceivedTime    int64  `json:"received_time"`     // 10快递签收时间，时间戳形式。
}
