package controller

import (
	"encoding/json"
	"fmt"
	_type "xianyv/type"
	"xianyv/utils/requestUtil"
)

type ExpressListResponse struct {
	Code int          `json:"code"`
	Msg  string       `json:"msg"`
	Data *ExpressData `json:"data"`
}

type ExpressData struct {
	List []ExpressCompany `json:"list"`
}

type ExpressCompany struct {
	Code         string `json:"code"`          // 快递公司代码
	ExpressAlias string `json:"express_alias"` // 快递别名（可能为空）
	ExpressName  string `json:"express_name"`  // 快递公司全名
	IsHot        bool   `json:"is_hot"`        // 是否热门
}

func XyOrderSynchronization(body _type.GetOrderShip) ([]byte, error) {
	companiesPath := "/api/open/express/companies"
	var by _type.GetShopList
	by.AppId = body.AppId
	by.AppSecret = body.AppSecret
	companiesResponse, err := requestUtil.MakeAPIRequest(body.AppId, body.AppSecret, "https://open.goofish.pro", companiesPath, by)
	var expressListResponse ExpressListResponse
	if err := json.Unmarshal(companiesResponse, &expressListResponse); err != nil {
		return nil, fmt.Errorf("解析 errorWrapper 失败: %v", err)
	}
	for _, list := range expressListResponse.Data.List {
		if body.ExpressName == list.ExpressName {
			body.ExpressCode = list.Code
		}
	}
	shipPath := "/api/open/order/ship"
	shipResponse, err := requestUtil.MakeAPIRequest(body.AppId, body.AppSecret, "https://open.goofish.pro", shipPath, body)
	return shipResponse, err
}
