package ebai

import (
	"sync"
	"time"

	"git.rosy.net.cn/baseapi/platformapi/ebaiapi"
	"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/business/partner/putils"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
)

const (
	EbaiSupplierIDsc = "1921188187760"
	EbaiSupplierIDc4 = "22267134648"
	EbaiSupplierIDhc = "2233065879"
	EbaiSupplierIDgy = "2267230126"
)

var (
	EbaiSupplierIDMap = map[string]string{
		EbaiSupplierIDsc: "饿百商超",
		EbaiSupplierIDc4: "饿百菜市",
		EbaiSupplierIDhc: "饿百好菜",
		EbaiSupplierIDgy: "饿百果园",
	}
)

var (
	CurPurchaseHandler *PurchaseHandler
)

type PurchaseHandler struct {
	partner.BasePurchasePlatform
	putils.DefSingleStorePlatform

	shopList []*ebaiapi.ShopInfo
	locker   sync.RWMutex
}

func init() {
	if api.EbaiAPI != nil {
		CurPurchaseHandler = New()
		partner.RegisterPurchasePlatform(CurPurchaseHandler)
	}
}

func New() (obj *PurchaseHandler) {
	obj = new(PurchaseHandler)
	obj.ISingleStoreStoreSkuHandler = obj
	return obj
}

func EbaiBusStatus2JxStatus(ebaiStatus int) int {
	if ebaiStatus == ebaiapi.ShopBusStatusHaveRest {
		return model.StoreStatusClosed
	}
	if ebaiStatus == ebaiapi.ShopBusStatusSuspended {
		return model.StoreStatusDisabled
	}
	return model.StoreStatusOpened
}

func (p *PurchaseHandler) GetVendorID() int {
	return model.VendorIDEBAI
}

func (p *PurchaseHandler) UploadImg(ctx *jxcontext.Context, vendorOrgCode, imgURL string, imgData []byte, imgName string, imgType int) (imgHint string, err error) {
	if globals.EnableEbaiStoreWrite {
		if imgType == model.ImgTypeMain {
			imgHint, err = api.EbaiAPI.PictureUpload(imgURL, imgData)
		} else if imgType == model.ImgTypeDesc {
			imgHint, err = api.EbaiAPI.SkuUploadRTF(p.getShopID4UploadRTF(), ebaiapi.BuildRFTFromImgs(imgURL))
		}
	} else {
		imgHint = imgURL + ".ebai"
	}
	return imgHint, err
}

func getShopIDFromList(shopList []*ebaiapi.ShopInfo) (shopID string) {
	if len(shopList) > 0 {
		shopID = shopList[0].ShopID
	}
	return shopID
}

func (p *PurchaseHandler) getShopID4UploadRTF() (shopID string) {
	var shopList []*ebaiapi.ShopInfo
	p.locker.RLock()
	shopList = p.shopList
	p.locker.RUnlock()
	if len(shopList) > 0 {
		return getShopIDFromList(shopList)
	}

	p.locker.Lock()
	shopList = p.shopList
	if len(shopList) > 0 {
		p.locker.Unlock()
		return getShopIDFromList(shopList)
	}

	defer p.locker.Unlock()
	shopList, err := api.EbaiAPI.ShopList(ebaiapi.SysStatusAll)
	if err == nil {
		if len(shopList) > 0 {
			p.shopList = shopList
			shopID = getShopIDFromList(shopList)
		} else {
			// p.shopList = []*ebaiapi.ShopInfo{
			// 	&ebaiapi.ShopInfo{
			// 		ShopID: "",
			// 	},
			// }
		}
	}
	return shopID
}

func (p *PurchaseHandler) getVendorCategories(level int, pid int64) (vendorCats []*model.SkuVendorCategory, err error) {
	cats, err := api.EbaiAPI.SkuCategoryList("", level, pid)
	if err != nil {
		return nil, err
	}
	for _, v := range cats {
		cat := &model.SkuVendorCategory{
			VendorID:         model.VendorIDEBAI,
			Name:             v.CatName,
			Level:            level,
			VendorCategoryID: v.CatID,
		}
		if level > 1 {
			cat.ParentID = v.ParentID
			if level == 3 {
				cat.IsLeaf = 1
			}
		}
		vendorCats = append(vendorCats, cat)
		if level < 3 {
			childVendorCats, err2 := p.getVendorCategories(level+1, utils.Str2Int64(v.CatID))
			if err2 == nil && len(childVendorCats) > 0 {
				vendorCats = append(vendorCats, childVendorCats...)
			} else {
				cat.IsLeaf = 1
			}
		}
	}
	return vendorCats, nil
}

func (p *PurchaseHandler) GetVendorCategories(ctx *jxcontext.Context) (vendorCats []*model.SkuVendorCategory, err error) {
	vendorCats, err = p.getVendorCategories(1, 0)
	return vendorCats, err
}

func (p *PurchaseHandler) GetOrderRider(vendorOrgCode, vendorStoreID string, param map[string]interface{}) (err error) {
	riderInfo := &ebaiapi.OrderSelfDeliveryLocationSync{
		OrderId: param["order_id"].(string),
		Location: &ebaiapi.RiderLocation{
			UTC:       utils.Int64ToStr(time.Now().Unix()),
			Altitude:  "0",
			Latitude:  param["latitude"].(string),
			Longitude: param["longitude"].(string),
		},
	}
	return api.EbaiAPI.SelfDeliveryLocationSync(riderInfo)
}

func OrderDeliveryCoordinate(param map[string]interface{}) error {
	selfStatus := 0
	switch param["logistics_status"].(int) {
	case 0, 5:
		selfStatus = ebaiapi.OrderDeliveryStatusWaitRider // 2:配送待分配
	case 10:
		selfStatus = ebaiapi.OrderDeliveryStatusReceived // 3.骑士接单
	case 15:
		selfStatus = ebaiapi.OrderDeliveryStatusToStore // 骑士到店
	case 20:
		selfStatus = ebaiapi.OrderDeliveryStatusSend // 骑手送出
	case 40:
		selfStatus = ebaiapi.OrderDeliveryStatusSendOver // 配送完成
	case 100:
		selfStatus = ebaiapi.OrderDeliveryStatusCancel // 取消
	default:
		selfStatus = ebaiapi.OrderDeliveryStatusAbnormal // 配送异常
	}
	param2 := &ebaiapi.PushRiderInfo{
		DistributorId:  201,
		OrderId:        param["order_id"].(string),
		State:          21,
		SelfStatus:     selfStatus,
		SelfStatusDesc: param["logistics_context"].(string),
		DistributorInfoDTO: ebaiapi.DistributorInfoDTO{
			DistributorTypeId: "99999",
			DistributorName:   "商家自行配送",
		},
		Knight: ebaiapi.Knight{
			Id:    utils.Str2Int64(param["order_id"].(string)),
			Name:  param["courier_name"].(string),
			Phone: param["courier_phone"].(string),
		},
	}
	return api.EbaiAPI.OrderselfDeliveryStateSync2(param2)
}
