package ebaiapi

import (
	"encoding/base64"

	"git.rosy.net.cn/baseapi/utils"
)

type VendorCategoryInfo struct {
	CatID    string `json:"cat_id"`
	CatName  string `json:"cat_name"`
	Depth    int    `json:"depth"`
	ParentID string `json:"parent_id"`
}

type BrandInfo struct {
	BrandID   int64  `json:"brand_id"`
	BrandName string `json:"brand_name"`
}

func (a *API) SkuCategoryList(keyword string, depth int, parentID int64) (cats []*VendorCategoryInfo, err error) {
	result, err := a.AccessAPI("sku.category.list", map[string]interface{}{
		"keyword":   keyword,
		"depth":     depth,
		"parent_id": parentID,
	})
	if err == nil {
		if err = utils.Map2StructByJson(result.Data, &cats, true); err == nil {
			return cats, nil
		}
	}
	return nil, err
}

// pageNo页，从1开始，keyword不能为空，否则不会返回任何信息
func (a *API) SkuBrandList(keyword string, pageNo int) (brands []*BrandInfo, err error) {
	result, err := a.AccessAPI("sku.brand.list", map[string]interface{}{
		"keyword": keyword,
		"page":    pageNo,
	})
	if err == nil {
		// baseapi.SugarLogger.Debug(utils.Format4Output(result, false))
		brs := result.Data.(map[string]interface{})
		detail := brs["detail"].([]interface{})
		brands = make([]*BrandInfo, len(detail))
		for k, v := range detail {
			brandMap := v.(map[string]interface{})
			brands[k] = &BrandInfo{
				BrandID:   utils.Str2Int64(utils.Interface2String(brandMap["brand_id"])),
				BrandName: utils.Interface2String(brandMap["brand_name"]),
			}
		}
		return brands, nil
	}
	return nil, err
}

func (a *API) PictureUpload(imgURL string, imgData []byte) (ebaiImgURL string, err error) {
	params := map[string]interface{}{}
	if imgURL != "" {
		params["url"] = imgURL
	} else {
		params["data"] = base64.StdEncoding.EncodeToString(imgData)
	}
	result, err := a.AccessAPI("picture.upload", params)
	if err == nil {
		return utils.Interface2String(result.Data.(map[string]interface{})["url"]), nil
	}
	return "", err
}
