package itao

import (
	"context"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/frame/g"
)

type logistics struct {
}

var Logistics = logistics{}

type LogisticsTraceRes struct {
	Result struct {
		Result []struct {
			DetailList []struct {
				Action       string `json:"action"`
				GmtCreate    string `json:"gmtCreate"`
				StanderdDesc string `json:"standerdDesc"`
				Status       string `json:"status"`
				Time         string `json:"time"`
				MailNo       string `json:"mailNo,omitempty"`
				TpName       string `json:"tpName,omitempty"`
			} `json:"detailList"`
			GoodsList []interface{} `json:"goodsList"`
			MailNo    string        `json:"mailNo"`
			Receiver  struct {
				Adr          string `json:"adr"`
				CityName     string `json:"cityName"`
				DistrictName string `json:"districtName"`
				Name         string `json:"name"`
				ProvinceName string `json:"provinceName"`
				Telphone     string `json:"telphone"`
			} `json:"receiver"`
			Status struct {
				StatusCode string `json:"statusCode"`
				StatusDesc string `json:"statusDesc"`
			} `json:"status"`
		} `json:"result"`
		Success bool   `json:"success"`
		ErrMsg  string `json:"errMsg"`
		ErrCode string `json:"errCode"`
	} `json:"result"`
}

//Trace 物流轨迹
func (logistics) Trace(ctx context.Context, req string) (res *LogisticsTraceRes, err error) {
	method := "tt.logistics.detail"

	result, err := server.Post(ctx, method, g.Map{
		"request": g.Map{
			"tradeId": req,
		},
	})
	_ = gjson.New(result).Scan(&res)
	return
}

type LogisticsCompanyRes struct {
	Result  []LogisticsCompanyItem `json:"result"`
	Success bool                   `json:"success"`
}

type LogisticsCompanyItem struct {
	Code string `json:"code"`
	Name string `json:"name"`
	Id   int64  `json:"id"`
	Type int    `json:"type"`
}

type LogisticsCompany struct {
	Result  map[string][]interface{} `json:"result"`
	Success bool                     `json:"success"`
}

//Company 物流公司
func (logistics) Company(ctx context.Context, req string) (res *LogisticsCompanyRes, err error) {
	method := "tt.refund.queryLogisticList"

	result, err := server.Post(ctx, method, g.Map{
		"request": g.Map{
			"bizOrderId": req,
		},
	})
	var data *LogisticsCompany
	_ = gjson.New(result).Scan(&data)
	res = new(LogisticsCompanyRes)
	res.Success = data.Success
	for _, item := range data.Result {
		for _, val := range item {
			var value []LogisticsCompanyItem
			_ = gjson.New(val).Scan(&value)
			res.Result = append(res.Result, value...)
		}
	}
	return
}