package ebai

import (
	beego "github.com/astaxie/beego/server/web"
	"regexp"
	"strings"
	"time"

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

const (
	defVendorCatID = 201222934 // 其他蔬菜
)

var (
	sensitiveWordRegexp = regexp.MustCompile(`商品名称中含有敏感词(\[.*\])`)
	categoryCheck       = map[int]string{
		175: "赠品专区",
		18:  "烧烤吧台",
	}

	//果园果切的饿百分类ID
	gygqVendorCatID = map[int]int{
		201227732: 1,
		201220933: 1,
		201223525: 1,
		201220334: 1,
	}

	ebaiExSkuCatMap3 = map[int]int{
		35062:   1,
		34759:   1,
		6042855: 1,
		6041992: 1,
		27259:   1,
		6046862: 1,
		6046864: 1,
	}

	ebaiExSkuCatMap2 = map[int]int{
		6046399: 1,
		6046283: 1,
		23001:   1,
		30768:   1,
		24037:   1,
		24838:   1,
		35052:   1,
		30859:   1,
		28490:   1,
		6040798: 1,
		6046267: 1,
		31029:   1,
		35508:   1,
		33727:   1,
	}

	ebaiExSkuCatMap = map[int]int{
		32576:   1,
		22856:   1,
		35231:   1,
		30593:   1,
		6045151: 1,
		6046299: 1,
		31237:   1,
		28854:   1,
		29605:   1,
		26330:   1,
		6045121: 1,
		6045448: 1,
		30629:   1,
		6045163: 1,
		30876:   1,
		6041954: 1,
		23814:   1,
		6045621: 1,
		33298:   1,
		27136:   1,
		6043711: 1,
		30822:   1,
		25019:   1,
		30704:   1,
		30644:   1,
		23868:   1,
		26049:   1,
		30635:   1,
		6045955: 1,
		30672:   1,
		30641:   1,
		6045863: 1,
		30781:   1,
		6046413: 1,
		30686:   1,
		34417:   1,
		30611:   1,
		23065:   1,
		30676:   1,
		30706:   1,
	}
)

func (p *PurchaseHandler) GetStoreSkusBatchSize(funcID int) (batchSize int) {
	switch funcID {
	case partner.FuncUpdateStoreSkusStock, partner.FuncUpdateStoreSkusStatus, partner.FuncUpdateStoreSkusPrice, partner.FuncDeleteStoreSkus:
		batchSize = ebaiapi.MaxStoreSkuBatchSize
	case partner.FuncCreateStoreSkus, partner.FuncUpdateStoreSkus:
		batchSize = 1
	case partner.FuncGetStoreSkusFullInfo:
		batchSize = 1
	case partner.FuncCreateActs, partner.FuncCancelActs:
		batchSize = 1
	}
	return batchSize
}

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

func convertVendorCatList(remoteCats []*ebaiapi.CategoryInfo) (cats []*partner.BareCategoryInfo) {
	for _, rCat := range remoteCats {
		cat := &partner.BareCategoryInfo{
			VendorCatID: utils.Int64ToStr(rCat.CategoryID),
			Name:        rCat.Name,
			Level:       rCat.Level,
			Seq:         jxCatSeq2Ebai(rCat.Rank),
			Children:    convertVendorCatList(rCat.Children),
		}
		cats = append(cats, cat)
	}
	return cats
}

func (p *PurchaseHandler) IsErrCategoryExist(err error) (isExist bool) {
	return ebaiapi.IsErrCategoryExist(err)
}

func (p *PurchaseHandler) IsErrCategoryNotExist(err error) (isNotExist bool) {
	return ebaiapi.IsErrCategoryNotExist(err)
}

func getCheckExdStoreNameAndSeq(storeID int, storeCat *dao.SkuStoreCatInfo) (name string, seq int, isCheck bool) {
	store, err := dao.GetStoreDetail(dao.GetDB(), storeID, model.VendorIDEBAI, "")
	if err != nil || store == nil {
		return storeCat.Name, storeCat.Seq, false
	}
	if strings.Contains(store.Name, model.ExdStoreName) {
		if categoryCheck[storeCat.ID] != "" {
			return storeCat.ExdName, storeCat.ExdSeq, true
		} else {
			return storeCat.ExdName, storeCat.ExdSeq, false
		}
	} else {
		return storeCat.Name, storeCat.Seq, false
	}
	return name, seq, false
}

func (p *PurchaseHandler) CreateStoreCategory(ctx *jxcontext.Context, storeID int, vendorStoreID string, storeCat *dao.SkuStoreCatInfo) (err error) {
	var vendorCatID int64
	if globals.EnableEbaiStoreWrite {
		if catName, catSeq, isCheck := getCheckExdStoreNameAndSeq(storeID, storeCat); !isCheck {
			vendorCatID, err = api.EbaiAPI.ShopCategoryCreate(utils.Int2Str(storeID), utils.Str2Int64WithDefault(storeCat.ParentVendorCatID, 0), formatCatName(catName), jxCatSeq2Ebai(catSeq))
		}
	} else {
		vendorCatID = jxutils.GenFakeID()
	}
	storeCat.VendorCatID = utils.Int64ToStr(vendorCatID)
	return err
}

func (p *PurchaseHandler) UpdateStoreCategory(ctx *jxcontext.Context, storeID int, vendorStoreID string, storeCat *dao.SkuStoreCatInfo) (err error) {
	if globals.EnableEbaiStoreWrite {
		if catName, catSeq, isCheck := getCheckExdStoreNameAndSeq(storeID, storeCat); !isCheck {
			err = api.EbaiAPI.ShopCategoryUpdate(utils.Int2Str(storeID), utils.Str2Int64WithDefault(storeCat.VendorCatID, 0), formatCatName(catName), jxCatSeq2Ebai(catSeq))
			// 修改分类时错误:自定义分类ID(category_id)不存在(降低api调用错误)
			if err != nil && strings.Contains(err.Error(), "自定义分类ID(category_id)不存在") {
				dao.SetStoreCategorySyncStatus(dao.GetDB(), model.VendorIDEBAI, []int{storeID}, []int{storeCat.StoreCatID}, 2)
			}
		}
		// todo, 饿百将一个分类重复改名，也会报分类名重复错，特殊处理一下，不过因为GetStoreCategory其实会拉取所有的门店分类，是比较耗时的操作
		if utils.IsErrMatch(err, "1", []string{"分类名称已经存在"}) {
			if cat, err2 := p.GetStoreCategory(ctx, storeID, vendorStoreID, storeCat.Name); err2 == nil {
				if cat.VendorCatID == storeCat.VendorCatID {
					err = nil
				}
			}
		}
	}
	return err
}

func (p *PurchaseHandler) DeleteStoreCategory(ctx *jxcontext.Context, storeID int, vendorStoreID, vendorCatID string, level int) (err error) {
	if globals.EnableEbaiStoreWrite {
		err = api.EbaiAPI.ShopCategoryDelete(utils.Int2Str(storeID), utils.Str2Int64WithDefault(vendorCatID, 0))
	}
	return err
}

// 门店商品

// 多门店平台不需要实现这个接口

func (p *PurchaseHandler) IsErrSkuExist(err error) (isExist bool) {
	return ebaiapi.IsErrSkuExist(err)
}

func (p *PurchaseHandler) IsErrSkuNotExist(err error) (isNotExist bool) {
	return ebaiapi.IsErrSkuNotExist(err)
}

func (p *PurchaseHandler) updateStoreSkus(ctx *jxcontext.Context, storeID int, vendorStoreID string, storeSkuList []*dao.StoreSkuSyncInfo, isNeedMapCat bool) (failedList []*partner.StoreSkuInfoWithErr, err error) {
	storeSku := storeSkuList[0]
	strStoreID := utils.Int2Str(storeID)
	isExd := false
	if strings.Contains(storeSku.StoreName, model.ExdStoreName) {
		isExd = true
	}
	params := genSkuParamsFromStoreSkuInfo2(storeSku, false, true)
	if globals.EnableEbaiStoreWrite {
		_, err = api.EbaiAPI.SkuUpdate(ctx.GetTrackInfo(), strStoreID, utils.Str2Int64(storeSku.VendorSkuID), params)
		if err != nil {
			failedList = putils.GetErrMsg2FailedSingleList(storeSkuList, err, storeID, model.VendorChineseNames[model.VendorIDEBAI], "更新商品基础信息")
			// 本地商品存在饿百商品id,但是平台不存在该商品
			if strings.Contains(err.Error(), "sku不存在") {
				sql := ` UPDATE store_sku_bind SET ebai_id = 0,ebai_sync_status = 2 WHERE store_id = ? AND sku_id = ?`
				param := []interface{}{storeID, storeSku.SkuID}
				dao.ExecuteSQL(dao.GetDB(), sql, param...)
			} else if strings.Contains(err.Error(), "商品禁止售卖不允许上架，请去商品审核模块进行修改") {
				sql := ` UPDATE store_sku_bind SET ebai_sync_status = 0 WHERE store_id = ? AND sku_id = ?`
				param := []interface{}{storeID, storeSku.SkuID}
				dao.ExecuteSQL(dao.GetDB(), sql, param...)
			}
		}

		if ebaiExSkuCatMap[storeSku.SkuID] == 0 && ebaiExSkuCatMap2[storeSku.SkuID] == 0 && ebaiExSkuCatMap3[storeSku.SkuID] == 0 && err == nil {
			if isNeedMapCat && !isExd {
				utils.CallFuncAsync(func() {
					api.EbaiAPI.SkuShopCategoryMap(strStoreID, utils.Str2Int64(storeSku.VendorSkuID), "", utils.Str2Int64(storeSku.VendorCatID), genSkuCatRank(storeSku))
				})
			}
		}
		err = nil
	}
	return failedList, err
}

func (p *PurchaseHandler) UpdateStoreSkus(ctx *jxcontext.Context, storeID int, vendorStoreID string, storeSkuList []*dao.StoreSkuSyncInfo) (failedList []*partner.StoreSkuInfoWithErr, err error) {
	return p.updateStoreSkus(ctx, storeID, vendorStoreID, storeSkuList, true)
}

// 对于多门店平台来说，storeSkuList中只有SkuID与VendorSkuID有意义
func (p *PurchaseHandler) CreateStoreSkus(ctx *jxcontext.Context, storeID int, vendorStoreID string, storeSkuList []*dao.StoreSkuSyncInfo) (failedList []*partner.StoreSkuInfoWithErr, err error) {
	storeSku := storeSkuList[0]
	var (
		vendorSkuID int64
		isExd       bool = false
		customSkuID string
	)
	if strings.Contains(storeSku.StoreName, model.ExdStoreName) {
		isExd = true
		if storeSku.ExdSkuID == "" {
			customSkuID = ""
		} else {
			customSkuID = storeSku.ExdSkuID
		}
	} else {
		isExd = false
		customSkuID = utils.Int2Str(storeSku.SkuID)
	}

	params := genSkuParamsFromStoreSkuInfo2(storeSku, true, true)
	if globals.EnableEbaiStoreWrite {
		strStoreID := utils.Int2Str(storeID)
		if vendorSkuID, err = api.EbaiAPI.SkuCreate(ctx.GetTrackInfo(), strStoreID, customSkuID, params); err == nil && !isExd {
			utils.AfterFuncWithRecover(5*time.Second, func() {
				api.EbaiAPI.SkuShopCategoryMap(strStoreID, vendorSkuID, "", utils.Str2Int64(storeSku.VendorCatID), genSkuCatRank(storeSku))
				// 饿百平台有BUG，会导致新建一个之前删除的商品时，信息不会及时更新，强制刷新一下
				// 比如门店：100887, skuID：33805，订单：1577176719141226065
				p.updateStoreSkus(ctx, storeID, vendorStoreID, storeSkuList, false)
			})
		} else {
			failedList = putils.GetErrMsg2FailedSingleList(storeSkuList, err, storeID, model.VendorChineseNames[model.VendorIDEBAI], "创建商品")
		}
	} else {
		vendorSkuID = jxutils.GenFakeID()
	}
	err = nil
	storeSku.VendorSkuID = utils.Int64ToStr(vendorSkuID)
	return failedList, err
}

func getFailedVendorSkuIDsFromOpResult(opResult *ebaiapi.BatchOpResult) (skuIDs []string) {
	if opResult != nil {
		for _, v := range opResult.FailedList {
			skuIDs = append(skuIDs, utils.Int64ToStr(v.SkuID))
		}
	}
	return skuIDs
}

func (p *PurchaseHandler) DeleteStoreSkus(ctx *jxcontext.Context, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo) (failedList []*partner.StoreSkuInfoWithErr, err error) {
	if globals.EnableEbaiStoreWrite {
		opResult, err2 := api.EbaiAPI.SkuDelete(ctx.GetTrackInfo(), utils.Int2Str(storeID), partner.BareStoreSkuInfoList(storeSkuList).GetVendorSkuIDIntList(), nil)
		if err = err2; err2 != nil && opResult != nil {
			// if len(storeSkuList) > len(opResult.FailedList) {
			failedList = SelectStoreSkuListByOpResult(storeSkuList, opResult, storeID, model.VendorChineseNames[model.VendorIDEBAI], "删除商品")
			// successList = putils.UnselectStoreSkuListByVendorSkuIDs(storeSkuList, getFailedVendorSkuIDsFromOpResult(opResult))
			// }
		}
		err = nil
	}
	return failedList, err
}

func (p *PurchaseHandler) UpdateStoreSkusStatus(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo, status int) (failedList []*partner.StoreSkuInfoWithErr, err error) {
	vendorSkuIDs := partner.BareStoreSkuInfoList(storeSkuList).GetVendorSkuIDIntList()
	if globals.EnableEbaiStoreWrite {
		var opResult *ebaiapi.BatchOpResult
		if status == model.SkuStatusNormal { // 可售上架
			if len(vendorSkuIDs) > 1 {
				opResult, err = api.EbaiAPI.SkuOnline(ctx.GetTrackInfo(), utils.Int2Str(storeID), vendorSkuIDs, nil, nil)
			} else if len(vendorSkuIDs) == 1 {
				err = api.EbaiAPI.SkuOnlineOne(ctx.GetTrackInfo(), utils.Int2Str(storeID), vendorSkuIDs[0], "", "")
				if err != nil {
					failedList = putils.GetErrMsg2FailedSingleList(storeSkuList, err, storeID, model.VendorChineseNames[model.VendorIDEBAI], "更新商品状态")
				}
				return failedList, err
			}
		} else { // 下架
			if len(vendorSkuIDs) > 1 {
				opResult, err = api.EbaiAPI.SkuOffline(ctx.GetTrackInfo(), utils.Int2Str(storeID), vendorSkuIDs, nil, nil)
			} else if len(vendorSkuIDs) == 1 {
				err = api.EbaiAPI.SkuOfflineOne(ctx.GetTrackInfo(), utils.Int2Str(storeID), vendorSkuIDs[0], "", "")
				if err != nil {
					failedList = putils.GetErrMsg2FailedSingleList(storeSkuList, err, storeID, model.VendorChineseNames[model.VendorIDEBAI], "更新商品状态")
				}
				return failedList, err
			}
		}
		if err != nil && opResult != nil {
			failedList = SelectStoreSkuListByOpResult(storeSkuList, opResult, storeID, model.VendorChineseNames[model.VendorIDEBAI], "更新商品状态")
			// failedList = putils.UnselectStoreSkuListByVendorSkuIDs(storeSkuList, getFailedVendorSkuIDsFromOpResult(opResult))
		}
		err = nil
	}
	return failedList, err
}

func StoreSkuInfoList2Ebai(storeSkuList []*partner.StoreSkuInfo) (outList ebaiapi.ShopSkuInfoList) {
	outList = make(ebaiapi.ShopSkuInfoList, len(storeSkuList))
	for k, v := range storeSkuList {
		outList[k] = &ebaiapi.ShopSkuInfo{
			SkuID: utils.Str2Int64WithDefault(v.VendorSkuID, 0),
			// CustomSkuID: utils.Int2Str(v.SkuID),
			SalePrice: v.VendorPrice,
			Stock:     v.Stock,
		}
	}
	return outList
}

func (p *PurchaseHandler) UpdateStoreSkusPrice(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo) (failedList []*partner.StoreSkuInfoWithErr, err error) {
	if globals.EnableEbaiStoreWrite {
		if len(storeSkuList) > 1 {
			opResult, err2 := api.EbaiAPI.SkuPriceUpdateBatch(ctx.GetTrackInfo(), utils.Int2Str(storeID), StoreSkuInfoList2Ebai(storeSkuList), ebaiapi.SkuIDTypeSkuID)
			if err = err2; err != nil && opResult != nil {
				failedList = SelectStoreSkuListByOpResult(storeSkuList, opResult, storeID, model.VendorChineseNames[model.VendorIDEBAI], "更新商品价格")
			}
		} else if len(storeSkuList) == 1 {
			_, err := api.EbaiAPI.SkuPriceUpdateOne(ctx.GetTrackInfo(), utils.Int2Str(storeID), StoreSkuInfoList2Ebai(storeSkuList)[0])
			if err != nil {
				failedList = putils.GetErrMsg2FailedSingleList(storeSkuList, err, storeID, model.VendorChineseNames[model.VendorIDEBAI], "更新商品价格")
			}
		}
		err = nil
	}
	return failedList, err
}

func (p *PurchaseHandler) UpdateStoreSkusStock(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo) (failedList []*partner.StoreSkuInfoWithErr, err error) {
	if globals.EnableEbaiStoreWrite {
		if len(storeSkuList) > 1 {
			opResult, err2 := api.EbaiAPI.SkuStockUpdateBatch(ctx.GetTrackInfo(), utils.Int2Str(storeID), StoreSkuInfoList2Ebai(storeSkuList), ebaiapi.SkuIDTypeSkuID)
			if err = err2; err != nil && opResult != nil {
				failedList = SelectStoreSkuListByOpResult(storeSkuList, opResult, storeID, model.VendorChineseNames[model.VendorIDEBAI], "更新商品库存")
				// successList = putils.UnselectStoreSkuListByVendorSkuIDs(storeSkuList, getFailedVendorSkuIDsFromOpResult(opResult))
			}
		} else if len(storeSkuList) == 1 {
			err = api.EbaiAPI.SkuStockUpdateOne(ctx.GetTrackInfo(), utils.Int2Str(storeID), StoreSkuInfoList2Ebai(storeSkuList)[0])
			if err != nil {
				failedList = putils.GetErrMsg2FailedSingleList(storeSkuList, err, storeID, model.VendorChineseNames[model.VendorIDEBAI], "更新商品库存")
			}
			// 本地商品存在饿百商品id,但是平台不存在该商品
			if err != nil && strings.Contains(err.Error(), "商品不存在") {
				sql := ` UPDATE store_sku_bind SET ebai_id = 0,ebai_sync_status = 2 WHERE store_id = ? AND sku_id = ?`
				param := []interface{}{storeID, storeSkuList[0].SkuID}
				dao.ExecuteSQL(dao.GetDB(), sql, param...)
			}
		}
		err = nil
	}
	return failedList, err
}

func genSkuParamsFromStoreSkuInfo2(storeSku *dao.StoreSkuSyncInfo, isCreate, isExd bool) (params map[string]interface{}) {
	var img string
	var imgdata []byte

	// PictureUpload 会被限流,但是通过此接口上传的商品不会异步操作会直接展示
	img, err := api.EbaiAPI.PictureUpload(storeSku.Img, imgdata)
	if err != nil {
		img = storeSku.Img
	}
	photos := []map[string]interface{}{
		map[string]interface{}{
			"is_master": 1,
			"url":       img,
		},
	}
	if storeSku.Img2 != "" {
		photos = append(photos, map[string]interface{}{
			"is_master": 0,
			"url":       storeSku.Img2,
		})
	}
	if storeSku.Img3 != "" {
		photos = append(photos, map[string]interface{}{
			"is_master": 0,
			"url":       storeSku.Img3,
		})
	}
	if storeSku.Img4 != "" {
		photos = append(photos, map[string]interface{}{
			"is_master": 0,
			"url":       storeSku.Img4,
		})
	}
	if storeSku.Img5 != "" {
		photos = append(photos, map[string]interface{}{
			"is_master": 0,
			"url":       storeSku.Img5,
		})
	}
	//if storeSku.SpecialPictures != "" {
	//	photos = append(photos, map[string]interface{}{
	//		"is_master": 0,
	//		"url":       storeSku.SpecialPictures,
	//	})
	//}

	params = map[string]interface{}{
		// "name":     utils.LimitMixedStringLen(storeSku.SkuName, ebaiapi.MaxSkuNameByteCount),
		// "category_id": utils.Str2Int64(storeSku.VendorCatID),
		//"predict_cat": 0, // 不使用推荐类目
		// "cat3_id":     getEbaiCat(storeSku.VendorVendorCatID),
		"weight":           storeSku.Weight,
		"photos":           photos,
		"preparation_time": storeSku.PreparationTime,
	}

	if storeSku.Stock == 0 && beego.BConfig.RunMode != model.ServerTypePet {
		params["left_num"] = model.MaxStoreSkuStockQty
	} else if storeSku.Stock > 99999 { // 最大值
		params["left_num"] = 99999
	} else {
		params["left_num"] = storeSku.Stock
	}
	if !isExd {
		var categoryID = utils.Str2Int64(storeSku.VendorCatID)
		if ebaiExSkuCatMap[storeSku.SkuID] != 0 {
			if store, err := dao.GetStoreDetail(dao.GetDB(), storeSku.StoreID, model.VendorIDEBAI, ""); err == nil && store != nil {
				if store.CityCode == 510100 {
					if s, err2 := dao.GetStoreSkuCategoryMap(dao.GetDB(), 439, storeSku.StoreID); err2 == nil && s != nil {
						categoryID = s.EbaiID
					}
				}
			}

		}
		if ebaiExSkuCatMap2[storeSku.SkuID] != 0 {
			if store, err := dao.GetStoreDetail(dao.GetDB(), storeSku.StoreID, model.VendorIDEBAI, ""); err == nil && store != nil {
				if store.CityCode == 510100 {
					if s, err2 := dao.GetStoreSkuCategoryMap(dao.GetDB(), 440, storeSku.StoreID); err2 == nil && s != nil {
						categoryID = s.EbaiID
					}
				}
			}
		}
		if ebaiExSkuCatMap3[storeSku.SkuID] != 0 {
			if store, err := dao.GetStoreDetail(dao.GetDB(), storeSku.StoreID, model.VendorIDEBAI, ""); err == nil && store != nil {
				if store.CityCode == 510100 {
					if s, err2 := dao.GetStoreSkuCategoryMap(dao.GetDB(), 175, storeSku.StoreID); err2 == nil && s != nil {
						categoryID = s.EbaiID
					}
				}
			}
		}
		params["category_id"] = categoryID
		params["name"] = utils.LimitMixedStringLen(storeSku.SkuName, ebaiapi.MaxSkuNameByteCount)
		if getEbaiCat(storeSku.VendorVendorCatID) != 0 {
			params["cat3_id"] = getEbaiCat(storeSku.VendorVendorCatID)
		}
	} else {
		params["upc"] = storeSku.Upc
		params["name"] = storeSku.SkuName
		if storeSku.ExdCategoryThirdID != 0 {
			params["cat3_id"] = storeSku.ExdCategoryThirdID
		}
		params["category_id"] = utils.Str2Int64WithDefault(storeSku.VendorCatID, 0)
	}
	//证明是果园的几个果切分类，需要填加工服务
	if gygqVendorCatID[int(storeSku.VendorVendorCatID)] == 1 {
		params["process_type"] = model.YES
		processDetail := []map[string]interface{}{
			map[string]interface{}{
				"type": "去皮",
				"time": 2,
			},
			map[string]interface{}{
				"type": "不加工",
				"time": 0,
			},
		}
		params["process_detail"] = processDetail
	}
	if storeSku.DescImg != "" {
		params["rtf"] = storeSku.DescImg
	}
	if isCreate /*storeSku.SkuSyncStatus&(model.SyncFlagPriceMask| model.SyncFlagNewMask) != 0 */ {
		params["sale_price"] = storeSku.VendorPrice
	}
	if storeSku.LocationCode != "" {
		params["shelf_number"] = storeSku.LocationCode
	}
	if storeSku.LocationCode == "EMPTY_VALUE" { // EMPTY_VALUE 美团置空
		params["shelf_number"] = ""
	}
	if storeSku.SkuSyncStatus&(model.SyncFlagSaleMask|model.SyncFlagNewMask) != 0 {
		params["status"] = jxSkuStatus2Ebai(storeSku.MergedStatus)
	}
	if storeSku.EbaiAttribute != "" && storeSku.EbaiAttribute != "{}" {
		//attr := map[string]interface{}{}
		//if storeSku.Upc != "" {
		//	attr["upc"] = storeSku.Upc
		//} else {
		//	attr["upc"] = "upc-" + utils.Int2Str(storeSku.SkuID)
		//}
		//attr["sale_price"] = storeSku.VendorPrice
		//attr["left_num"] = params["left_num"]
		//attr["weight"] = storeSku.Weight
		//attr["status"] = 1 // 正常

		//sepcProperty := make([]map[string]interface{}, 0, 0)
		catProperty := make([]map[string]interface{}, 0, 0)
		attributeList := make([]*AttributeListEBai, 0, 0)
		err = utils.UnmarshalUseNumber([]byte(storeSku.EbaiAttribute), &attributeList)
		for _, al := range attributeList {
			for _, pv := range al.PropertyValues {
				//property := map[string]interface{}{
				//	"prop_id":   al.PropertyId,
				//	"prop_text": al.PropertyName,
				//}
				//property["value_id"] = pv.ValueId
				//property["value_text"] = pv.ValueData
				//sepcProperty = append(sepcProperty, property)
				catProperty = append(catProperty, map[string]interface{}{
					"propId":    al.PropertyId,
					"propText":  al.PropertyName,
					"valueId":   pv.ValueId,
					"valueText": pv.ValueData,
				})
			}
		}
		//attr["spec_property"] = sepcProperty
		//params["sku_spec"] = []interface{}{attr}
		params["cat_property"] = catProperty
	}
	// todo 饿百如果给的UPC是空要报错，但如果我要删除UPC怎么弄？
	// if storeSku.Upc != "" {
	// 	params["upc"] = storeSku.Upc
	// }

	//测试ebai  目前未考虑称重商品
	if storeSku.MinOrderCount > 0 {
		params["minimum"] = utils.Int2Float64(storeSku.MinOrderCount)
	}
	if storeSku.MinOrderCount == 0 {
		params["minimum"] = utils.Int2Float64(1)
	}

	return params
}

type AttributeListEBai struct {
	PropertyId     int64  `json:"propertyId"`
	PropertyName   string `json:"propertyName"`
	PropertyValues []struct {
		ValueId   int64  `json:"valueId"`   // 属性值id
		ValueData string `json:"valueData"` // 属性值内容
	} `json:"propertyValues"` // 属性值列表

}

func ebaiSkuStatus2Jx(ebaiSkuStatus int) (jxSkuStatus int) {
	if ebaiSkuStatus == ebaiapi.SkuStatusOnline {
		jxSkuStatus = model.SkuStatusNormal
	} else if ebaiSkuStatus == ebaiapi.SkuStatusOffline {
		jxSkuStatus = model.SkuStatusDontSale
	} else if ebaiSkuStatus == ebaiapi.SkuStatusOnline {
		jxSkuStatus = model.SkuStatusDeleted
	}
	return jxSkuStatus
}

func jxSkuStatus2Ebai(status int) int {
	if status <= 0 {
		return ebaiapi.SkuStatusOffline
	}
	return ebaiapi.SkuStatusOnline
}

func getEbaiCat(catID int64) int64 {
	if catID == 0 {
		return defVendorCatID
	}
	return catID
}

// 饿百的排序是从大到小
func genSkuCatRank(storeSku *dao.StoreSkuSyncInfo) int {
	return int(ebaiapi.MaxSkuCatRank - storeSku.GetSeq())
}

// 饿百的排序是从大到小
func jxCatSeq2Ebai(seq int) int {
	return ebaiapi.MaxCatCatRank - seq
}

func formatCatName(name string) string {
	return utils.LimitUTF8StringLen(name, ebaiapi.MaxCategoryNameLen)
}

func (p *PurchaseHandler) GetStoreSkusFullInfo(ctx *jxcontext.Context, parentTask tasksch.ITask, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo) (skuNameList []*partner.SkuNameInfo, err error) {
	params := &ebaiapi.SkuListParams{
		PageSize: ebaiapi.MaxSkuListPageSize,
	}
	if len(storeSkuList) == 1 {
		if storeSkuList[0].SkuID > 0 {
			params.CustomSkuID = utils.Int2Str(storeSkuList[0].SkuID)
		}
		if storeSkuList[0].VendorSkuID != "" {
			params.SkuID = utils.Str2Int64WithDefault(storeSkuList[0].VendorSkuID, 0)
		}
	}
	page1, err := api.EbaiAPI.SkuList(utils.Int2Str(storeID), params)
	if err == nil {
		skuNameList = append(skuNameList, vendorSkuList2Jx(page1.List)...)
		if page1.Pages > 1 {
			pages := make([]int, page1.Pages-1)
			for i := 2; i <= page1.Pages; i++ {
				pages[i-2] = i
			}
			task := tasksch.NewParallelTask("ebai GetStoreSkusFullInfo", nil, ctx,
				func(t *tasksch.ParallelTask, batchItemList []interface{}, params ...interface{}) (retVal interface{}, err error) {
					callParams := &ebaiapi.SkuListParams{
						PageSize: ebaiapi.MaxSkuListPageSize,
						Page:     batchItemList[0].(int),
					}
					pageSku, err2 := api.EbaiAPI.SkuList(utils.Int2Str(storeID), callParams)
					if err2 == nil {
						return pageSku.List, err2
					}
					return nil, err2
				}, pages)
			tasksch.HandleTask(task, parentTask, true).Run()
			result, err2 := task.GetResult(0)
			if err = err2; err == nil {
				for _, v := range result {
					skuNameList = append(skuNameList, vendorSku2Jx(v.(*ebaiapi.SkuInfo)))
				}
			}
		}
	}
	return skuNameList, err
}

func vendorSku2Jx(vendorSku *ebaiapi.SkuInfo) (skuName *partner.SkuNameInfo) {
	prefix, name, comment, specUnit, unit, specQuality := jxutils.SplitSkuName(vendorSku.Name)
	weight := utils.Str2Int(vendorSku.Weight)
	if weight <= 0 {
		weight = jxutils.FormatSkuWeight(specQuality, specUnit)
	}
	skuID := int(utils.Str2Int64WithDefault(vendorSku.CustomSkuID, 0))
	vendorSkuID := utils.Int64ToStr(vendorSku.SkuId)
	skuName = &partner.SkuNameInfo{
		NameID:       skuID,
		VendorNameID: vendorSkuID,

		Prefix: prefix,
		Name:   name,
		Unit:   unit,
		UPC:    vendorSku.Upc,
		SkuList: []*partner.SkuInfo{
			&partner.SkuInfo{
				StoreSkuInfo: partner.StoreSkuInfo{
					VendorSkuID: vendorSkuID,
					SkuID:       skuID,

					Stock:       vendorSku.LeftNum,
					VendorPrice: int64(vendorSku.SalePrice),
					Status:      ebaiSkuStatus2Jx(utils.Str2Int(vendorSku.Status)),
				},
				SkuName:     vendorSku.Name,
				Comment:     comment,
				SpecQuality: float64(specQuality),
				SpecUnit:    specUnit,
				Weight:      weight,
			},
		},
	}
	for _, v := range vendorSku.Photos {
		skuName.PictureList = append(skuName.PictureList, v.Url)
	}
	// todo, 看起来饿百只返回了最低一级的商家分类信息
	for _, v := range vendorSku.CustomCatList {
		skuName.VendorCatIDList = append(skuName.VendorCatIDList, v.CustomCatID)
	}
	return skuName
}

func vendorSkuList2Jx(vendorSkuList []*ebaiapi.SkuInfo) (skuNameList []*partner.SkuNameInfo) {
	for _, vendorSku := range vendorSkuList {
		skuNameList = append(skuNameList, vendorSku2Jx(vendorSku))
	}
	return skuNameList
}

func (p *PurchaseHandler) GetSensitiveWordRegexp() *regexp.Regexp {
	return sensitiveWordRegexp
}

//饿百api返回
func SelectStoreSkuListByOpResult(storeSkuList []*partner.StoreSkuInfo, opResult *ebaiapi.BatchOpResult, storeID int, vendorName string, syncType string) (selectedStoreSkuList []*partner.StoreSkuInfoWithErr) {
	opResultMap := make(map[int64]string)
	if len(opResult.FailedList) > 0 {
		for _, v := range opResult.FailedList {
			if !(syncType == "删除商品" && ebaiapi.IsMsgSkuNotExist(v.ErrorMsg)) {
				opResultMap[v.SkuID] = v.ErrorMsg
			}
		}
		for _, v := range storeSkuList {
			if opResultMap[utils.Str2Int64(v.VendorSkuID)] != "" {
				opFailed := &partner.StoreSkuInfoWithErr{
					StoreSkuInfo: v,
					ErrMsg:       opResultMap[utils.Str2Int64(v.VendorSkuID)],
					StoreID:      storeID,
					VendoreName:  vendorName,
					SyncType:     syncType,
				}
				// 本地商品存在饿百商品id,但是平台不存在该商品
				if strings.Contains(opResultMap[utils.Str2Int64(v.VendorSkuID)], "商品不存在") {
					sql := ` UPDATE store_sku_bind SET ebai_id = 0,ebai_sync_status = 2 WHERE store_id = ? AND sku_id = ?`
					param := []interface{}{storeID, v.SkuID}
					dao.ExecuteSQL(dao.GetDB(), sql, param...)
				} else if strings.Contains(opResultMap[utils.Str2Int64(v.VendorSkuID)], "商品禁止售卖不允许上架") || strings.Contains(opResultMap[utils.Str2Int64(v.VendorSkuID)], "商品已被禁售") {
					sql := ` UPDATE store_sku_bind SET ebai_sync_status = 4 WHERE store_id = ? AND sku_id = ?`
					param := []interface{}{storeID, v.SkuID}
					dao.ExecuteSQL(dao.GetDB(), sql, param...)
				}
				selectedStoreSkuList = append(selectedStoreSkuList, opFailed)
			}
		}
	}
	return selectedStoreSkuList
}

func (p *PurchaseHandler) CreateStoreSkusAct(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo) (failedList []*partner.StoreSkuInfoWithErr, err error) {
	for _, v := range storeSkuList {
		if vendorActID, err2 := createOneShopAct(putils.GetFixDirectDownAct(vendorOrgCode, storeID, v.SkuID), utils.Int2Str(storeID), putils.StoreSku2ActStoreSku(model.SyncFlagNewMask, vendorStoreID, []*partner.StoreSkuInfo{v})); err2 != nil {
			failedList = append(failedList, &partner.StoreSkuInfoWithErr{
				StoreSkuInfo: v,
				VendoreID:    model.VendorIDEBAI,
				StoreID:      storeID,
				ErrMsg:       err2.Error(),
			})
		} else {
			v.VendorActID = vendorActID
		}
	}
	return failedList, err
}

func (p *PurchaseHandler) CancelActs(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo) (failedList []*partner.StoreSkuInfoWithErr, err error) {
	for _, v := range storeSkuList {
		if err2 := ActivityDisable(utils.Str2Int64(v.VendorActID), utils.Int2Str(storeID), 0, 0); err2 != nil {
			failedList = append(failedList, &partner.StoreSkuInfoWithErr{
				StoreSkuInfo: v,
				VendoreID:    model.VendorIDJD,
				StoreID:      storeID,
				ErrMsg:       err2.Error(),
			})
		}
	}
	return failedList, err
}

func (p *PurchaseHandler) UpdateStoreSkusSpecTag(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo) (err error) {
	return err
}

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

//GetCategoryAttrValueList 查询特殊属性的属性值列表
func GetCategoryAttrValueList(attrID int64) (categoryAttrValueListResult []*ebaiapi.CategoryAttr, err error) {
	switch beego.BConfig.RunMode {
	case model.ServerTypeFruits:
		categoryAttrValueListResult, err = api.EbaiAPI.CategoryAttrValueList(attrID, "800082")
	case model.ServerTypeVegetable:
		categoryAttrValueListResult, err = api.EbaiAPI.CategoryAttrValueList(attrID, "666667")
	case model.ServerTypePet:
		categoryAttrValueListResult, err = api.EbaiAPI.CategoryAttrValueList(attrID, "666667")
	}
	return categoryAttrValueListResult, err
}
