package cms

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/ebaiapi"
	"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/purchase/mtwm"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
	beego "github.com/astaxie/beego/server/web"
	"time"

	"git.rosy.net.cn/baseapi/platformapi/mtwmapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
)

const (
	SyncTypeSku = 1
	SyncTypeAct = 2
	SyncTypeAll = 3
)

// CopyOnStoreSkuToOther 将一个美团门店分类和商品复制到另一个门店
func CopyOnStoreSkuToOther(ctx *jxcontext.Context, fromStoreId, toStoreId string, vendorId int, isAsync bool, offSet int, syncType int) ([]string, error) {
	var (
		db         = dao.GetDB()
		copySkuErr = make([]string, 0, 0)
		err        error
	)

	// 门店api加载
	toStore, err := dao.GetStoreDetailByVendorStoreID(db, toStoreId, vendorId, "")
	if err != nil {
		return nil, err
	}

	fromStore, err := dao.GetStoreDetailByVendorStoreID(db, fromStoreId, vendorId, "")
	if err != nil {
		return nil, err
	}

	if syncType == SyncTypeSku || syncType == SyncTypeAll {
		switch vendorId {
		case model.VendorIDMTWM:
			_, copySkuErr, err = CopyMtToMT(ctx, fromStore, toStore, isAsync, offSet)
		case model.VendorIDEBAI:
			_, copySkuErr, err = CopyEBaiToEBai(ctx, fromStore, toStore, isAsync, offSet)
		default:
			return nil, fmt.Errorf("暂时还不支持")
		}
	}

	if syncType == SyncTypeAct || syncType == SyncTypeAll {
		if vendorId == model.VendorIDMTWM {

		}
	}

	return copySkuErr, err
}

//#region 同步商品

// CopyEBaiToEBai 饿了么商品复制到饿了么
func CopyEBaiToEBai(ctx *jxcontext.Context, fromStore, toStore *dao.StoreDetail, isAsync bool, offset int) (hint string, errList []string, err error) {
	VendorCategoryIDMap := map[int64]int64{}
	var errListData = make([]string, 0, 0)
	api := api.EbaiAPI

	taskName := fmt.Sprintf("将饿了么平台门店[%s],分类和商品复制到[%s]", fromStore.VendorStoreID, toStore.VendorStoreID)
	config := tasksch.NewParallelConfig().SetParallelCount(1).SetIsContinueWhenError(false)
	work := func(task *tasksch.ParallelTask, batchItemList []interface{}, params ...interface{}) (retVal interface{}, err error) {
		step := batchItemList[0].(int)
		switch step {
		case 1:
			// 1.加载门店商品,删除商品.当分类下没有商品时.删除分类
			//errs := LoadingStoreSkuList(ctx, toApi, toStore.VendorStoreID)
			//			errs := LoadingStoreSkuList(ctx, toApi, toStore.VendorStoreID)
			//if errs != nil && len(errs) > 0 {
			//	return nil, errs[0]
			//}
		case 2:
			//同步分类
			fromCategoryList, err := api.ShopCategoryGet(utils.Int2Str(fromStore.ID))
			if err != nil {
				return nil, err
			}
			for _, v := range fromCategoryList {
				parentID, categoryErr := api.ShopCategoryCreate(utils.Int2Str(toStore.ID), 0, v.Name, v.Rank)
				if categoryErr != nil {
					globals.SugarLogger.Debugf("err := RetailCatUpdate : %v", categoryErr)
					continue
				}
				VendorCategoryIDMap[v.CategoryID] = parentID
				if v.Children != nil && len(v.Children) != 0 {
					for _, c := range v.Children {
						childrenCateId, err := api.ShopCategoryCreate(utils.Int2Str(toStore.ID), parentID, c.Name, c.Rank)
						if err != nil {
							globals.SugarLogger.Debugf("err := RetailCatUpdate  Children : %v", err)
							continue
						}
						VendorCategoryIDMap[c.CategoryID] = childrenCateId
					}
				}
			}
		case 3:
			i := 1
			for {
				// 同步商品
				fromFoodList, err1 := api.SkuList(utils.Int2Str(fromStore.ID), &ebaiapi.SkuListParams{
					Page: i,
				})
				if len(fromFoodList.List) == 0 || fromFoodList == nil {
					return nil, fmt.Errorf("fromFoodList 为空 %s ,i:= %d", utils.Format4Output(err1, false), i)
				}
				errList := BatchInitSkuEBai2EBai(ctx, fromFoodList.List, api, utils.Int2Str(toStore.ID), VendorCategoryIDMap)
				if errList != nil {
					for _, verr := range errList {
						errListData = append(errListData, verr.Error())
					}
					globals.SugarLogger.Debugf("BatchInitData : %s", utils.Format4Output(errList, false))
				}
				i = i + 1
			}

		}
		return
	}
	task := tasksch.NewParallelTask(taskName, config, ctx, work, []int{1, 2, 3})
	tasksch.HandleTask(task, nil, true).Run()
	if !isAsync {
		_, err = task.GetResult(0)
		hint = "1"
	} else {
		hint = task.ID
	}
	return hint, errList, err
}

// BatchInitSkuEBai2EBai 批量创建商品
func BatchInitSkuEBai2EBai(ctx *jxcontext.Context, fromSku []*ebaiapi.SkuInfo, toApi *ebaiapi.API, storeID string, VendorCategoryIDMap map[int64]int64) []error {
	var errList = make([]error, 0, 0)
	for _, storeSku := range fromSku {
		params := map[string]interface{}{
			"left_num":         model.MaxStoreSkuStockQty,
			"weight":           storeSku.Weight,
			"photos":           storeSku.Photos,
			"preparation_time": storeSku.PreparationTime,
		}
		params["upc"] = storeSku.Upc
		params["name"] = storeSku.Name
		params["cat3_id"] = storeSku.CateId
		params["category_id"] = VendorCategoryIDMap[utils.Str2Int64(storeSku.CustomCatList[0].CustomCatID)]
		params["rtf"] = storeSku.Rtf
		params["left_num"] = storeSku.LeftNum
		params["process_type"] = storeSku.ProcessType
		params["process_detail"] = storeSku.ProcessDetail
		params["sale_price"] = storeSku.SalePrice
		params["status"] = storeSku.Status
		params["minimum"] = storeSku.Minimum
		params["seven_days_no_reason"] = storeSku.SevenDaysNoReason
		if len(storeSku.SkuProperty) != model.NO {
			params["sku_property"] = storeSku.SkuProperty
		}
		customSkuID := storeSku.CustomSkuID
		if customSkuID == "" {
			customSkuID = utils.Int64ToStr(storeSku.SkuId)
		}
		_, err := toApi.SkuCreate(ctx.GetTrackInfo(), storeID, utils.Str2Int64(storeSku.CustomSkuID), params)
		if err != nil {
			errList = append(errList, err)
		}
	}

	return errList
}

// CopyMtToMT 美团商品复制到美团
func CopyMtToMT(ctx *jxcontext.Context, fromStore, toStore *dao.StoreDetail, isAsync bool, offSet int) (hint string, data []string, err error) {
	var fromApi *mtwmapi.API //= mtwm.GetAPI(fromStore.VendorOrgCode, fromStore.ID, fromStore.VendorStoreID)
	var toApi *mtwmapi.API   // = mtwm.GetAPI(toStore.VendorOrgCode, toStore.ID, toStore.VendorStoreID)
	var errList = make([]*mtwmapi.AppFoodResult, 0, 0)
	var errData = make([]string, 0, 0)

	if fromStore.VendorOrgCode == globals.Mtwm2Code {
		fromApi = mtwmapi.New(beego.AppConfig.DefaultString("mtwmAppID2", ""), beego.AppConfig.DefaultString("mtwmSecret2", ""), beego.AppConfig.DefaultString("mtwmCallbackURL2", ""), "")
		fromApi.SetToken(fromStore.MtwmToken)
	} else {
		fromApi = partner.CurAPIManager.GetAPI(model.VendorIDMTWM, fromStore.VendorOrgCode).(*mtwmapi.API)
	}

	if toStore.VendorOrgCode == globals.Mtwm2Code {
		toApi = mtwmapi.New(beego.AppConfig.DefaultString("mtwmAppID2", ""), beego.AppConfig.DefaultString("mtwmSecret2", ""), beego.AppConfig.DefaultString("mtwmCallbackURL2", ""), "")
		toApi.SetToken(toStore.MtwmToken)
	} else {
		toApi = partner.CurAPIManager.GetAPI(model.VendorIDMTWM, toStore.VendorOrgCode).(*mtwmapi.API)
	}
	taskName := fmt.Sprintf("将美团平台门店[%s],分类和商品复制到[%s]", fromStore.VendorStoreID, toStore.VendorStoreID)
	config := tasksch.NewParallelConfig().SetParallelCount(1).SetIsContinueWhenError(false)
	work := func(task *tasksch.ParallelTask, batchItemList []interface{}, params ...interface{}) (retVal interface{}, err error) {
		step := batchItemList[0].(int)
		switch step {
		case 1:
			// 同步分类
			//fromCategoryList, err := fromApi.RetailCatList(fromStore.VendorStoreID)
			//if len(fromCategoryList) == model.NO {
			//	return nil, err
			//}
			////toCategoryList, err := toApi.RetailCatList(toStore.VendorStoreID)
			////if err != nil {
			////	return nil, err
			////}
			//for _, v := range fromCategoryList {
			//	categoryErr := toApi.RetailCatUpdate(toStore.VendorStoreID, v.Name, &mtwmapi.Param4UpdateCat{
			//		CategoryCode: v.Code,
			//		Sequence:     v.Sequence,
			//	})
			//	if categoryErr != nil {
			//		globals.SugarLogger.Debugf("err := RetailCatUpdate : %v", categoryErr)
			//	}
			//	if v.Children != nil && len(v.Children) != 0 {
			//		for _, c := range v.Children {
			//			if err3 := toApi.RetailCatUpdate(toStore.VendorStoreID, v.Name, &mtwmapi.Param4UpdateCat{
			//				CategoryNameOrigin:    v.Name,
			//				SecondaryCategoryCode: c.Code,
			//				SecondaryCategoryName: c.Name,
			//				Sequence:              c.Sequence,
			//			}); err3 != nil {
			//				globals.SugarLogger.Debugf("err := RetailCatUpdate  Children : %v", err3)
			//			}
			//		}
			//	}
			//}

		case 2:
			i := offSet
			for {
				// 同步商品
				fromFoodList, err1 := fromApi.RetailListAll(fromStore.VendorStoreID, i)
				if len(fromFoodList) == 0 || fromFoodList == nil {
					return nil, fmt.Errorf("fromFoodList 为空 %s ,i:= %d", utils.Format4Output(err1, false), i)
				}

				errDataList, err := BatchInitSkuMT2MT(ctx, fromFoodList, toApi, toStore.VendorStoreID, i)
				if err != nil {
					globals.SugarLogger.Debugf("BatchInitData : %v", err)
				}
				if len(errDataList) > model.NO {
					globals.SugarLogger.Debugf("errListData %d:= %s", i, utils.Format4Output(errDataList, false))
					errList = append(errList, errDataList...)
				}
				globals.SugarLogger.Debugf("==========页数[%d],数据长度[%d]", i, len(fromFoodList))
				if len(fromFoodList) < 100 {
					break
				}
				i++
			}
		}
		return
	}
	task := tasksch.NewParallelTask(taskName, config, ctx, work, []int{1, 2})
	tasksch.HandleTask(task, nil, true).Run()
	if !isAsync {
		_, err = task.GetResult(0)
		hint = "1"
	} else {
		hint = task.ID
	}

	globals.SugarLogger.Debugf("======errrList := %s", utils.Format4Output(errList, false))
	for _, v := range errList {
		errData = append(errData, fmt.Sprintf("food_id:%s,错误:%s", v.AppFoodCode, v.ErrorMsg))
	}

	return hint, errData, err
}

// BatchInitSkuMT2MT 批量创建商品
func BatchInitSkuMT2MT(ctx *jxcontext.Context, fromSku []*mtwmapi.AppFood, toApi *mtwmapi.API, vendorStoreID string, offset int) ([]*mtwmapi.AppFoodResult, error) {
	errList := make([]*mtwmapi.AppFoodResult, 0, 0)
	foodDataList := make([]map[string]interface{}, len(fromSku))
	//apiObj := apimanager.CurAPIManager.GetAPI(model.VendorIDJD, "320406").(*jdapi.API)

	for k, storeSku := range fromSku {
		foodData := make(map[string]interface{})
		if storeSku.AppFoodCode != "" {
			foodData[mtwmapi.KeyAppFoodCode] = storeSku.AppFoodCode
		} else {
			foodData[mtwmapi.KeyAppFoodCode] = time.Now().UnixNano() + int64(k*3)
		}

		skus := make([]interface{}, 0)
		upc := ""
		for _, v := range storeSku.SkuList {
			if v.Stock == "" {
				v.Stock = "99999"
			}
			if v.SkuId == "" {
				v.SkuId = storeSku.AppFoodCode
			}
			if v.SkuId == "" {
				v.SkuId = utils.Int2Str(storeSku.Ctime + int(k*3))
			}
			//	salesCycle, _ := json.Marshal(v.AvailableTimes)
			mapSkuList := utils.Struct2MapByJson(v)
			if v.BoxNum == "" {
				delete(mapSkuList, "box_num")
			}
			if v.BoxPrice == "" {
				delete(mapSkuList, "box_price")
			}
			if v.LadderBoxNum == "" {
				delete(mapSkuList, "ladder_box_num")
			}
			if v.LadderBoxPrice == "" {
				delete(mapSkuList, "ladder_box_price")
			}
			delete(mapSkuList, "min_order_count")
			if v.AvailableTimes != nil {
				delete(mapSkuList, "available_times")
			}
			if v.Upc != "" {
				upc = v.Upc
			} /* else if toApi.QuerySkuIsNeedUpc(storeSku.TagID) {
				upcList, _ := apiObj.GetJdUpcCodeByName(storeSku.Name, "", 1, 20)
				if len(upcList) != 0 {
					upc = upcList[0].UpcCode
				}
			}*/
			//mapSkuList["available_times"] = string(salesCycle)
			//mapSkuList["available_times"] = v.AvailableTimes
			//if v.MinOrderCount != "" {
			//	mapSkuList["min_order_count"] = utils.Str2Int(v.MinOrderCount)
			//}
			if upc != "" {
				mapSkuList["upc"] = upc
			}
			skus = append(skus, mapSkuList)
		}
		foodData["skus"] = skus
		foodData["name"] = utils.LimitUTF8StringLen(storeSku.Name, mtwmapi.MaxSkuNameCharCount)
		foodData["description"] = storeSku.Description
		foodData["price"] = storeSku.Price
		foodData["min_order_count"] = storeSku.MinOrderCount
		foodData["unit"] = storeSku.Unit

		if storeSku.SecondaryCategoryCode != "" {
			foodData["category_code"] = storeSku.SecondaryCategoryCode
		} else {
			foodData["category_name"] = storeSku.SecondaryCategoryName
		}

		if storeSku.SecondaryCategoryName == "" && storeSku.SecondaryCategoryCode == "" {
			if storeSku.SecondaryCategoryCode != "" {
				foodData["category_code"] = storeSku.CategoryCode
			} else {
				foodData["category_name"] = storeSku.CategoryName
			}
		}

		//todo 增加商品必填属性
		//foodData["common_attr_value"] = storeSku.CommonAttrValue
		commonAttrValue, err := createCommonAttrValue(toApi, utils.Interface2Int64WithDefault(foodData["category_code"], 0), utils.Interface2String(foodData["name"]))
		if err == nil {
			foodData["common_attr_value"] = commonAttrValue
		} else if storeSku.CommonAttrValue != "" && storeSku.CommonAttrValue != "[]" {
			foodData["common_attr_value"] = mtwmapi.CommonAttrValueUpdate(storeSku.CommonAttrValue)
		}

		foodData["is_sold_out"] = storeSku.IsSoldOut
		foodData["picture"] = storeSku.Picture
		foodData["picture_contents"] = storeSku.PictureContents
		foodData["sequence"] = storeSku.Sequence
		foodData["tag_id"] = storeSku.TagID
		foodData["upc"] = storeSku.UpcCode
		if foodData["upc"].(string) == "" {
			foodData["upc"] = upc
		}
		if foodData["upc"].(string) == "" {
			foodData["upc"] = "no_upc"
		}

		foodDataList[k] = foodData
	}

	count := len(foodDataList) / 10
	if len(foodDataList)%10 != 0 {
		count += 1
	}
	for i := 0; i < count; i++ {
		if i == count-1 {
			failedFoodList, _ := toApi.RetailBatchInitData(ctx.GetTrackInfo(), vendorStoreID, foodDataList[i*10:])
			if len(failedFoodList) != 0 {
				globals.SugarLogger.Debugf("failedFoodList := %s", utils.Format4Output(failedFoodList, false))
				errList = append(errList, failedFoodList...)
			}
		} else {
			failedFoodList, _ := toApi.RetailBatchInitData(ctx.GetTrackInfo(), vendorStoreID, foodDataList[i*10:(i+1)*10])
			if len(failedFoodList) != 0 {
				globals.SugarLogger.Debugf("failedFoodList := %s", utils.Format4Output(failedFoodList, false))
				errList = append(errList, failedFoodList...)
			}
		}
	}

	return errList, nil
}

func createCommonAttrValue(apiObj *mtwmapi.API, tempCatID int64, name string) (string, error) {
	var (
		attrValue  mtwm.CommonAttrValue
		attrValues []mtwm.CommonAttrValue
	)

	attrList, err := apiObj.CategoryAttrList(tempCatID)
	if err == nil && len(attrList) > 0 {
		for _, v := range attrList {
			if v.Need == mtwmapi.NeedYes {
				attrValue = mtwm.CommonAttrValue{
					AttrID:   utils.Str2Int(v.AttrID),
					AttrName: v.AttrName,
				}
				if v.AttrID == mtwmapi.SpecialAttrBrand || v.AttrID == mtwmapi.SpecialAttrProducer { //单独获取特殊属性
					data, err1 := apiObj.CategoryAttrValueList(utils.Str2Int64(v.AttrID), name)
					if len(data) > 0 {
						attrValue.ValueList = []mtwm.ValueList{{ //默认取推荐第一个
							ValueID: utils.Str2Int(data[0].ValueID),
							Value:   data[0].Value,
						}}
					}
					if err1 != nil || len(data) == 0 {
						attrValue.ValueList = []mtwm.ValueList{{ //兜底处理
							Value: "其他",
						}}
					}
				} else {
					if len(v.ValueList) > 0 {
						attrValue.ValueList = []mtwm.ValueList{{
							ValueID: utils.Str2Int(v.ValueList[0].ValueID),
							Value:   v.ValueList[0].Value,
						}}
					} else { //兜底处理
						attrValue.ValueList = []mtwm.ValueList{{
							Value: "其他",
						}}
					}
				}
				attrValues = append(attrValues, attrValue)
			}
		}
		temp, err := json.Marshal(attrValues)
		return string(temp), err
	}

	return "", fmt.Errorf("暂未获取到")
}

//#endregion

////#region 同步活动
//
//func CopyMtActToMt(ctx *jxcontext.Context, fromStore, toStore *dao.StoreDetail) {
//	var fromApi, toApi *mtwmapi.API
//	var errData = make([]error, 0, 0)
//
//	if fromStore.VendorOrgCode == globals.Mtwm2Code {
//		fromApi = mtwmapi.New(beego.AppConfig.DefaultString("mtwmAppID2", ""), beego.AppConfig.DefaultString("mtwmSecret2", ""), beego.AppConfig.DefaultString("mtwmCallbackURL2", ""), "")
//		fromApi.SetToken(fromStore.MtwmToken)
//	} else {
//		fromApi = partner.CurAPIManager.GetAPI(model.VendorIDMTWM, fromStore.VendorOrgCode).(*mtwmapi.API)
//	}
//
//	if toStore.VendorOrgCode == globals.Mtwm2Code {
//		toApi = mtwmapi.New(beego.AppConfig.DefaultString("mtwmAppID2", ""), beego.AppConfig.DefaultString("mtwmSecret2", ""), beego.AppConfig.DefaultString("mtwmCallbackURL2", ""), "")
//		toApi.SetToken(toStore.MtwmToken)
//	} else {
//		toApi = partner.CurAPIManager.GetAPI(model.VendorIDMTWM, toStore.VendorOrgCode).(*mtwmapi.API)
//	}
//
//	// 买赠活动
//	buyGiftList, err := fromApi.BatchQueryBuyGiftsAll(fromStore.VendorStoreID)
//	if err != nil {
//		errData = append(errData, fmt.Errorf("买赠活动异常:%v", errData))
//	}
//	if len(buyGiftList) == model.NO {
//		errData = append(errData, fmt.Errorf("门店暂无买赠活动"))
//	}
//
//	param := make([]*mtwmapi.BatchCreateBuyGiftsParam, 0, 0)
//	for _, v := range buyGiftList {
//		buyGift := &mtwmapi.BatchCreateBuyGiftsParam{
//			AppSpuCode:      v.AppSpuCode,
//			StartTime:       v.StartTime,
//			EndTime:         v.EndTime,
//			GiftsType:       v.GiftsType,
//			GiftsName:       v.GiftsName,
//			GiftsAppSpuCode: v.GiftsAppSpuCode,
//			BuyNum:          v.BuyNum,
//			GiftsNum:        v.GiftsNum,
//			GiftsCharge:     v.GiftsCharge,
//			GiftsDayLimit:   v.GiftsDayLimit,
//		}
//
//		// 赠品成本
//		giftsCharge := &mtwmapi.GiftsChargeObj{}
//		if err := json.Unmarshal([]byte(v.Charge), giftsCharge); err != nil {
//			return
//		}
//
//		buyGift.GiftsCharge = utils.Str2Float64(fmt.Sprintf("%.2f", utils.Str2Float64(giftsCharge.GiftsCharge)))
//		param = append(param, buyGift)
//	}
//	toApi.BatchCreateBuyGifts(toStore.VendorStoreID, param)
//
//}
//
//// SyncStoreFullReduction 同步门店满减活动
//func SyncStoreFullReduction(fromStoreApi, toStoreApi *mtwmapi.API, fromStoreId, toStoreId string) error {
//	data, err := fromStoreApi.BatchGetDiscountList(fromStoreId, 0)
//	if err != nil {
//		return err
//	}
//
//	errList := make([]string, 0.0)
//	for k, v := range data {
//		param := &mtwmapi.CreateDiscountList{
//			AppPoiCode: toStoreId,
//			ActInfo:    "",
//			ActDetails: "",
//			AppFoods:   "",
//		}
//		actInfo := &mtwmapi.CreateDisCountActInfo{
//			StartTime: v.ActInfo.StartTime,
//			EndTime:   v.ActInfo.EndTime,
//			ActType:   0, // 0 不传app_food
//			AutoDelay: 1,
//		}
//		if v.ActInfo.ActName != "" {
//			actInfo.ActName = v.ActInfo.ActName
//		} else {
//			actInfo.ActName = "全店满减" + utils.Int2Str(k)
//		}
//
//		actInfoByte, err := json.Marshal(actInfo)
//		if err != nil {
//			return err
//		}
//		param.ActInfo = string(actInfoByte)
//
//		actDetails := make([]mtwmapi.CreateDiscountActDetails, 0, 0)
//		for _, ads := range v.ActDetails {
//			actDetails = append(actDetails, mtwmapi.CreateDiscountActDetails{
//				OriginPrice: utils.Float64TwoInt(ads.OriginPrice),
//				ActPrice:    utils.Float64TwoInt(ads.ActPrice),
//			})
//		}
//		actDetailsByte, err := json.Marshal(actDetails)
//		if err != nil {
//			return err
//		}
//		param.ActDetails = string(actDetailsByte)
//		_, err = toStoreApi.BatchCreateDiscountList(param)
//		if err != nil {
//			errList = append(errList, actInfo.ActName+":"+err.Error())
//		}
//	}
//
//	return fmt.Errorf(strings.Join(errList, ","))
//}
//
//// SyncStoreShippingFee 同步门店运费满减活动
//func SyncStoreShippingFee(fromStoreApi, toStoreApi *mtwmapi.API, fromStoreId, toStoreId string) error {
//	data, err := fromStoreApi.BatchGetShippingFee(fromStoreId)
//	if err != nil {
//		return err
//	}
//
//	if data.SuccessList != nil && len(data.SuccessList) != 0 {
//		param := make([]*mtwmapi.ShippingFeeBatchCreateActData, 0, 0)
//		for _, v := range data.SuccessList {
//			shippingFee := &mtwmapi.ShippingFeeBatchCreateActData{
//				StartTime: v.StartTime,
//				EndTime:   v.EndTime,
//				WeeksTime: v.WeeksTime,
//				Period:    v.Period,
//				MaxPrice:  v.MaxPrice,
//			}
//			actDetail := make([]mtwmapi.ShippingFeeBatchCreateActDataActDetail, 0, 0)
//			for _, ad := range v.ActDetail {
//				actDetail = append(actDetail, mtwmapi.ShippingFeeBatchCreateActDataActDetail{
//					LimitPrice:    ad.LimitPrice,
//					DiscountPrice: ad.DiscountPrice,
//				})
//			}
//			shippingFee.ActDetail = actDetail
//
//			param = append(param, shippingFee)
//		}
//
//		resultData, err := toStoreApi.BatchCreateShippingFee(toStoreId, param)
//		if err != nil {
//			return err
//		}
//		if resultData.Data != "ok" {
//			return fmt.Errorf(resultData.Msg)
//		}
//	}
//	return nil
//}
//
//// SyncStoreProducts 同步门店折扣爆品活动
//func SyncStoreProducts(fromStoreApi, toStoreApi *mtwmapi.API, fromStoreId, toStoreId string) error {
//	secKillALL, err := fromStoreApi.QueryProductsAll(fromStoreId, mtwmapi.RetailActTypeSecKill)
//	if err != nil {
//		return err
//	}
//
//	killAct := make([]*mtwmapi.RetailDiscountActData, 0, 0)
//	for _, v := range secKillALL {
//		kill := &mtwmapi.RetailDiscountActData{
//			AppFoodCode:         v.AppFoodCode,
//			UserType:            v.UserType,
//			StartTime:           v.StartTime,
//			EndTime:             v.EndTime,
//			OrderLimit:          v.OrderLimit,
//			DayLimit:            v.DayLimit,
//			Period:              v.Period,
//			WeeksTime:           v.WeeksTime,
//			SettingType:         v.SettingType,
//			ActPrice:            v.ActPrice,
//			DiscountCoefficient: v.DiscountCoefficient,
//			Sequence:            v.Sequence,
//			ItemID:              v.ItemID,
//			OriginalPrice:       v.OriginalPrice,
//			Stock:               v.Stock,
//			Status:              v.Status,
//			Name:                v.Name,
//		}
//		killAct = append(killAct, kill)
//	}
//
//	//todo 折扣活动查询出来一万多条,暂时工单处理
//	directDownALL, err := fromStoreApi.QueryProductsAll(fromStoreId, mtwmapi.RetailActTypeDirectDown)
//	for _, v := range directDownALL {
//		kill := &mtwmapi.RetailDiscountActData{
//			AppFoodCode:         v.AppFoodCode,
//			UserType:            v.UserType,
//			StartTime:           v.StartTime,
//			EndTime:             v.EndTime,
//			OrderLimit:          v.OrderLimit,
//			DayLimit:            v.DayLimit,
//			Period:              v.Period,
//			WeeksTime:           v.WeeksTime,
//			SettingType:         v.SettingType,
//			ActPrice:            v.ActPrice,
//			DiscountCoefficient: v.DiscountCoefficient,
//			Sequence:            v.Sequence,
//			ItemID:              v.ItemID,
//			OriginalPrice:       v.OriginalPrice,
//			Stock:               v.Stock,
//			Status:              v.Status,
//			Name:                v.Name,
//		}
//		killAct = append(killAct, kill)
//	}
//	if len(killAct) != 0 {
//		_, _, err := toStoreApi.CreateProductsAct(toStoreId, mtwmapi.RetailActTypeSecKill, killAct)
//		if err != nil {
//			return err
//		}
//	}
//
//	return nil
//}
//
//// SyncStoreCoupon 同步门店商家券(单店店内商家券)
//func SyncStoreCoupon(fromStoreApi, toStoreApi *mtwmapi.API, fromStoreId, toStoreId string) error {
//	couponList, err := fromStoreApi.QueryStoreCoupon(fromStoreId)
//	if err != nil {
//		return err
//	}
//
//	errList := make([]string, 0, 0)
//	if len(couponList) != 0 {
//		for _, v := range couponList {
//			couponInfoList := make([]*mtwmapi.CouponInfo, 0, 0)
//			for _, ad := range v.ActData {
//				couponInfoList = append(couponInfoList, &mtwmapi.CouponInfo{
//					LimitPrice:   ad.LimitPrice,
//					CouponPrice:  ad.CouponPrice,
//					UserType:     ad.UserType,
//					ValidityDays: ad.ValidityDays,
//					Stock:        ad.Stock,
//				})
//			}
//
//			limitTime := &mtwmapi.LimitTime{
//				StartTime: v.StartTime,
//				EndTime:   v.EndTime,
//			}
//
//			if _, err := toStoreApi.CreateStoreCouponBatch(toStoreId, limitTime, couponInfoList); err != nil {
//				errList = append(errList, err.Error())
//			}
//		}
//	}
//
//	if len(errList) != 0 {
//		return fmt.Errorf(strings.Join(errList, ","))
//	}
//	return nil
//}
//
//// SyncStoreXDiscount 同步门店X件优惠活动(x件m元/X件m折/X件减m元)目前只有x件m元,其他两个查询不出来,美团创建成功也查询不出来
//// 暂时不能创建,无法获取商品的活动价格和活动库存
//func SyncStoreXDiscount(fromStoreApi, toStoreApi *mtwmapi.API, fromStoreId, toStoreId string) error {
//	//result := make([]*mtwmapi.BundlesSuccessListDetail, 0, 0)
//	//// X件M元
//	//bundlesXM, _ := fromStoreApi.QueryBundlesAct(fromStoreId, 0)
//	//if bundlesXM != nil {
//	//	result = append(result, bundlesXM...)
//	//}
//	//// X件Y折
//	//bundlesXY, _ := fromStoreApi.QueryBundlesAct(fromStoreId, 2)
//	//if bundlesXY != nil {
//	//	result = append(result, bundlesXY...)
//	//}
//	//
//	//errList := make([]error, 0, 0)
//	//for _, v := range result {
//	//	actSku, err := fromStoreApi.QueryBundlesSku(fromStoreId, utils.Int64ToStr(v.ActId))
//	//	if err != nil {
//	//		errList = append(errList, err)
//	//		continue
//	//	}
//	//
//	//}
//
//	return nil
//}
//
//// SyncRepurchaseSku 加价购[无法获取活动商品的价格和库存暂不创建]
//func SyncRepurchaseSku() {
//	return
//}
//
//// SyncStoreCouponAct 门店商品券活动
//func SyncStoreCouponAct(fromStoreApi, toStoreApi *mtwmapi.API, fromStoreId, toStoreId string) error {
//	couponInfoAll := make([]*mtwmapi.GetStoreCouponActSuccessList, 0, 0)
//	pageNumber := 1
//	pageSize := 100
//	for {
//		param := &mtwmapi.GetStoreCouponActParam{
//			AppPoiCode: fromStoreId,
//			ActStatus:  1,
//			StartTime:  time.Now().AddDate(-1, 0, 0).Unix(),
//			EndTime:    time.Now().AddDate(1, 0, 0).Unix(),
//			PageNum:    pageNumber,
//			PageSize:   pageSize,
//		}
//
//		couponList, err := fromStoreApi.GetStoreCouponAct(param)
//		if err != nil {
//			return err
//		}
//		couponInfoAll = append(couponInfoAll, couponList...)
//		if len(couponList) < pageSize {
//			break
//		}
//		pageNumber++
//	}
//
//	for _, v := range couponInfoAll {
//		couponSkuList, err := fromStoreApi.GetCouponActSkuList(fromStoreId, utils.Int64ToStr(v.ActId))
//		if err != nil {
//			return err
//		}
//
//		for _, csl := range couponSkuList {
//			param := &mtwmapi.CreateCouponAct{
//				AppPoiCodes:         csl.AppPoiCodes,
//				CouponName:          csl.CouponName,
//				IsSinglePoi:         csl.IsSinglePoi,
//				AppSpuCodes:         csl.AppSpuCodes,
//				TakeCouponStartTime: csl.TakeCouponStartTime,
//				TakeCouponEndTime:   csl.TakeCouponEndTime,
//				UseCouponStartTime:  csl.UseCouponStartTime,
//				CouponLimitCount:    csl.CouponLimitCount,
//				Type:                csl.Type,
//			}
//
//			if csl.SpuData != nil && len(csl.SpuData) != 0 {
//				for _, sd := range csl.SpuData {
//					param.SpuData = append(param.SpuData, mtwmapi.CreateCouponActSpuData{
//						AppSpuCode: sd.AppSpuCode,
//						SkuId:      sd.SkuId,
//						Upc:        sd.Upc,
//					})
//				}
//			}
//
//			if csl.ActPriceCouponInfo != nil && len(csl.ActPriceCouponInfo) != 0 {
//				param.ActPriceCouponInfo = csl.ActPriceCouponInfo
//			}
//			if csl.DiscountCouponInfo != nil && len(csl.DiscountCouponInfo) != 0 {
//				param.DiscountCouponInfo = csl.DiscountCouponInfo
//			}
//
//			_, err = toStoreApi.CreateCouponAct(param)
//			if err != nil {
//				return err
//			}
//		}
//	}
//
//	return nil
//}
//
////#endregion
