package originalJd

import (
	"context"
	"encoding/json"
	"errors"
	"sync"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/gclient"
)

type Client struct {
	Client *gclient.Client
}

var client *Client

func NewClient() *Client {
	sync.OnceFunc(func() {
		client = &Client{
			Client: g.Client(),
		}
	})()
	return client
}

// DeleteJDOrder 删除订单接口
func (c *Client) DeleteJDOrder(ctx context.Context, order *DeleteOrderReq) (*DeleteOrderResp, error) {
	response, err := c.Client.Post(ctx, "https://api.jd.com/routerjson", order)
	if err != nil {
		return nil, err
	}

	resp := &DeleteOrderResp{
		Status: false,
	}

	var clientResp DeleteClientResp
	err = json.Unmarshal(response.ReadAll(), &clientResp)
	if err != nil {
		return resp, err
	}
	if clientResp.Code != 2000 {
		return resp, errors.New(clientResp.Message)
	}
	resp.Status = true
	return resp, nil
}

// SmsLogin 短信登陆
func (c *Client) SmsLogin(ctx context.Context, input *SmsLoginReq) (*SmsLoginResp, error) {
	resp := &SmsLoginResp{
		Cookie: "",
	}

	response, err := c.Client.Post(ctx, "https://api.jd.com/routerjson", input)
	if err != nil {
		return resp, err
	}

	clientResp := &SmsLoginClientResp{}
	err = json.Unmarshal(response.ReadAll(), clientResp)
	if err != nil {
		return resp, err
	}

	if clientResp.Code != 2000 {
		return resp, errors.New(clientResp.Message)
	}

	resp.Cookie = clientResp.Data.Ck
	return resp, nil
}
