package wsc

import (
	"fmt"
	"math/rand"

	"git.rosy.net.cn/baseapi/platformapi/weimobapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/jxutils/tasksch"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
)

const (
	DefFreightTemplateId = 6537248
	DefDeliveryTypeId    = 177445
	DefVendorCategoryId  = 35
	DefCatImg            = "https://image-c.weimobwmc.com/openruntime/249b77ced5da4736a56641ebcf4875ec.png"
)

// 门店分类
func (p *PurchaseHandler) GetStoreAllCategories(ctx *jxcontext.Context, vendorStoreID string) (cats []*partner.BareCategoryInfo, err error) {
	remoteCats, err := api.WeimobAPI.QueryClassifyInfoList()
	if err == nil {
		cats = convertVendorCatList(remoteCats)
	}
	return cats, err
}

func convertVendorCatList(remoteCats []*weimobapi.GoodsClassify) (cats []*partner.BareCategoryInfo) {
	for _, rCat := range remoteCats {
		cat := &partner.BareCategoryInfo{
			VendorCatID: utils.Int64ToStr(rCat.ClassifyID),
			Name:        rCat.Title,
			Level:       rCat.Level,
			Seq:         0,
			Children:    convertVendorCatList(rCat.ChildrenClassify),
		}
		cats = append(cats, cat)
	}
	return cats
}

func (p *PurchaseHandler) CreateStoreCategory(ctx *jxcontext.Context, vendorStoreID string, storeCat *dao.SkuStoreCatInfo) (err error) {
	var vendorCatID int64
	if globals.EnableWscStoreWrite {
		vendorCatID, err = api.WeimobAPI.AddClassify(storeCat.Name, utils.Str2Int64WithDefault(storeCat.ParentVendorCatID, 0), "")
	} else {
		vendorCatID = jxutils.GenFakeID()
	}
	storeCat.VendorCatID = utils.Int64ToStr(vendorCatID)
	return err
}

func (p *PurchaseHandler) UpdateStoreCategory(ctx *jxcontext.Context, vendorStoreID string, storeCat *dao.SkuStoreCatInfo) (err error) {
	if globals.EnableWscStoreWrite {
		err = api.WeimobAPI.UpdateClassify(utils.Str2Int64WithDefault(storeCat.VendorCatID, 0), storeCat.Name, "")
	}
	return err
}

func (p *PurchaseHandler) DeleteStoreCategory(ctx *jxcontext.Context, vendorStoreID, vendorCatID string, level int) (err error) {
	if globals.EnableWscStoreWrite {
		err = api.WeimobAPI.UpdateClassify(utils.Str2Int64WithDefault(vendorCatID, 0), composeFakeDelName(vendorCatID), "")
	}
	return err
}

// 门店商品

// 多门店平台不需要实现这个接口
func (p *PurchaseHandler) UpdateStoreSkus(ctx *jxcontext.Context, vendorStoreID string, storeSkuList []*dao.StoreSkuSyncInfo) (err error) {
	storeSku := storeSkuList[0]
	goodsInfo := genSkuParams(storeSku)
	if globals.EnableWscStoreWrite {
		_, _, err = api.WeimobAPI.UpdateGoods2(goodsInfo)
	}
	return err
}

// 通用

func (p *PurchaseHandler) GetStoreSkusBatchSize(funcID int) int {
	return 1
}

func genSkuParams(storeSku *dao.StoreSkuSyncInfo) (goodsInfo *weimobapi.PendingSaveGoodsVo) {
	outerGoodsCode := utils.Int2Str(storeSku.NameID)
	isPutAway := storeSku.StoreSkuStatus == model.SkuStatusNormal
	categoryId := storeSku.VendorVendorCatID
	if categoryId == 0 {
		categoryId = DefVendorCategoryId
	}
	classifyIdList := []int64{utils.Str2Int64WithDefault(storeSku.VendorCatID, 0)}
	if storeSku.SkuVendorCatID != "" {
		if int64Value := utils.Str2Int64WithDefault(storeSku.SkuVendorCatID, 0); int64Value > 0 {
			classifyIdList = append(classifyIdList, int64Value)
		}
	}
	b2cGoods := []*weimobapi.PendingSaveB2CGoodsVo{
		&weimobapi.PendingSaveB2CGoodsVo{
			FreightTemplateId:  DefFreightTemplateId,
			DeliveryTypeIdList: []int64{DefDeliveryTypeId},
			B2cGoodsType:       weimobapi.GoodsTypeNormal,
		},
	}
	salePrice := int64(storeSku.Price)
	goodsInfo = &weimobapi.PendingSaveGoodsVo{
		Title:          storeSku.Name,
		OuterGoodsCode: outerGoodsCode,
		IsMultiSku:     0,
		GoodsImageURL:  []string{storeSku.Img},
		InitialSales:   0,
		IsPutAway:      utils.Bool2Int(!isPutAway),
		Sort:           int(storeSku.Price),
		CategoryID:     categoryId,
		B2cGoods:       b2cGoods,
		SkuList: []*weimobapi.PendingSaveSkuVo{
			&weimobapi.PendingSaveSkuVo{
				OuterSkuCode:  utils.Int2Str(storeSku.SkuID),
				ImageURL:      storeSku.Img,
				SalePrice:     jxutils.IntPrice2Standard(salePrice),
				CostPrice:     jxutils.IntPrice2Standard(salePrice * 8 / 10),
				OriginalPrice: jxutils.IntPrice2Standard(salePrice * 10 / (6 + rand.Int63n(4))),
				EditStockNum:  0,
				B2cSku: &weimobapi.PendingSaveB2CSkuVo{
					Weight: jxutils.IntWeight2Float(storeSku.Weight),
				},
			},
		},
	}
	return goodsInfo
}

// 对于多门店平台来说，storeSkuList中只有SkuID与VendorSkuID有意义
func (p *PurchaseHandler) CreateStoreSkus(ctx *jxcontext.Context, vendorStoreID string, storeSkuList []*dao.StoreSkuSyncInfo) (err error) {
	storeSku := storeSkuList[0]
	goodsInfo := genSkuParams(storeSku)
	var goodsID, vendorSkuID int64
	if globals.EnableWscStoreWrite {
		var skuMap map[string]int64
		if goodsID, skuMap, err = api.WeimobAPI.AddGoods2(goodsInfo); err == nil {
			vendorSkuID = skuMap[utils.Int2Str(storeSku.SkuID)]
		}
	} else {
		goodsID = jxutils.GenFakeID()
		vendorSkuID = jxutils.GenFakeID()
	}
	storeSku.VendorSkuID = utils.Int64ToStr(vendorSkuID)
	storeSku.VendorNameID = utils.Int64ToStr(goodsID)
	return err
}

func (p *PurchaseHandler) DeleteStoreSkus(ctx *jxcontext.Context, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo) (err error) {
	storeSku := storeSkuList[0]
	goodsID := utils.Str2Int64(storeSku.VendorNameID)
	if globals.EnableWscStoreWrite {
		if err = api.WeimobAPI.UpdateGoodsShelfStatus([]int64{goodsID}, false); err == nil {
			err = api.WeimobAPI.UpdateGoodsTitle(goodsID, composeFakeDelName(storeSku.VendorNameID))
		} else if intErr, ok := err.(*utils.ErrorWithCode); ok && intErr.Code() == "1001930300001" { // 商品不存在错
			err = nil // 强制忽略
		}
	}
	return err
}

func (p *PurchaseHandler) UpdateStoreSkusStatus(ctx *jxcontext.Context, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo) (err error) {
	var validGoodsIDList, invalidGoodsIDList []int64
	for _, storeSku := range storeSkuList {
		if storeSku.Status == model.SkuStatusNormal {
			validGoodsIDList = append(validGoodsIDList, utils.Str2Int64(storeSku.VendorSkuID))
		} else {
			invalidGoodsIDList = append(invalidGoodsIDList, utils.Str2Int64(storeSku.VendorSkuID))
		}
	}
	if globals.EnableWscStoreWrite {
		if len(validGoodsIDList) > 0 {
			err = api.WeimobAPI.UpdateGoodsShelfStatus(validGoodsIDList, true)
		}
		if err == nil && len(invalidGoodsIDList) > 0 {
			err = api.WeimobAPI.UpdateGoodsShelfStatus(invalidGoodsIDList, false)
		}
	}
	return err
}

func (p *PurchaseHandler) UpdateStoreSkusPrice(ctx *jxcontext.Context, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo) (err error) {
	err = fmt.Errorf("内部错误，微商城不支持UpdateStoreSkusPrice!")
	return err
}

func (p *PurchaseHandler) GetStoreSkusInfo(ctx *jxcontext.Context, parentTask tasksch.ITask, storeID int, vendorStoreID string, inStoreSkuList []*partner.StoreSkuInfo) (outStoreSkuList []*partner.StoreSkuInfo, err error) {
	return outStoreSkuList, err
}

func composeFakeDelName(name string) string {
	return "del_" + name
}
func (p *PurchaseHandler) GetSkuCategoryIdByName(vendorOrgCode, skuName string) (vendorCategoryId string, err error) {
	return "", err
}
