package wsc

import (
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
)

// 对于微盟来说，只有一个展示商品的商家，但有多个拣货的商家
// 订单中的
// VendorStoreID表示在微盟上的商家编码
// JxStoreID表示的是展示商品的商家
// StoreID才是实际派单的商家

var (
	curPurchaseHandler *PurchaseHandler
)

type PurchaseHandler struct {
	partner.BasePurchasePlatform
}

func init() {
	if api.WeimobAPI != nil {
		curPurchaseHandler = new(PurchaseHandler)
		// partner.RegisterPurchasePlatform(curPurchaseHandler)
	}
}

func (c *PurchaseHandler) GetVendorID() int {
	return model.VendorIDWSC
}

func (p *PurchaseHandler) GetVendorCategories(ctx *jxcontext.Context) (vendorCats []*model.SkuVendorCategory, err error) {
	rootCats, err := api.WeimobAPI.QueryCategoryTree()
	catList := rootCats
	if err != nil {
		return nil, err
	}
	for _, v := range rootCats {
		cats, err := api.WeimobAPI.QueryChildrenCategory(v.CategoryID)
		if err != nil {
			return nil, err
		}
		catList = append(catList, cats...)
	}
	vendorCats = make([]*model.SkuVendorCategory, len(catList))
	for k, v := range catList {
		vendorCats[k] = &model.SkuVendorCategory{
			VendorCategoryID: vendorCategoryID2String(v.CategoryID),
			VendorID:         model.VendorIDWSC,
			Name:             v.Title,
			IsLeaf:           int8(v.Level - 1),
			Level:            v.Level,
			ParentID:         vendorCategoryID2String(v.ParentID),
		}
	}
	return vendorCats, nil
}

func vendorCategoryID2String(catID int64) string {
	if catID > 0 {
		return utils.Int64ToStr(catID)
	}
	return ""
}

func (p *PurchaseHandler) UploadImg(ctx *jxcontext.Context, vendorOrgCode, imgURL string, imgData []byte, imgName string, imgType int) (imgHint string, err error) {
	if globals.EnableWscStoreWrite {
		imgHint, err = api.WeimobAPI.UploadImg(imgData, imgName)
	}
	return imgHint, err
}
