package cms

import (
	"fmt"
	"git.rosy.net.cn/jx-callback/globals"
	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"
	"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"
)

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

	// 门店api加载
	toStore, err := dao.GetStoreDetailByVendorStoreID(db, utils.Int2Str(toStoreId), model.VendorIDMTWM, "")
	if err != nil {
		return "", err
	}
	//firstApi := api.Mtwm2API
	toApi := mtwmapi.New(beego.AppConfig.DefaultString("mtwmAppID2", ""), beego.AppConfig.DefaultString("mtwmSecret2", ""), beego.AppConfig.DefaultString("mtwmCallbackURL2", ""), "")
	toApi.SetToken(toStore.MtwmToken)

	fromStore, err := dao.GetStoreDetailByVendorStoreID(db, utils.Int2Str(fromVendorStoreId), model.VendorIDMTWM, "")
	if err != nil {
		return "", err
	}
	fromApi := mtwmapi.New(beego.AppConfig.DefaultString("mtwmAppID2", ""), beego.AppConfig.DefaultString("mtwmSecret2", ""), beego.AppConfig.DefaultString("mtwmCallbackURL2", ""), "")
	fromApi.SetToken(fromStore.MtwmToken)
	//fromApi := partner.CurAPIManager.GetAPI(model.VendorIDMTWM, fromStore.VendorOrgCode).(*mtwmapi.API)
	//fromApi.SetToken(fromStore.MtwmToken)

	taskName := fmt.Sprintf("将平台门店[%d],分类和商品复制到[%d]", fromVendorStoreId, toStoreId)
	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)
			//if errs != nil && len(errs) > 0 {
			//	return nil, errs[0]
			//}
		case 2:
			// 同步分类
			//fromCategoryList, err := fromApi.RetailCatList(utils.Int2Str(fromVendorStoreId))
			//globals.SugarLogger.Debugf("err ============ %v", 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,
			//				//CategoryCodeOrigin:    v.Code,
			//				//CategoryCode:          v.Code,
			//				SecondaryCategoryCode: c.Code,
			//				SecondaryCategoryName: c.Name,
			//				Sequence:              c.Sequence,
			//			}); err3 != nil {
			//				globals.SugarLogger.Debugf("err := RetailCatUpdate  Children : %v", err3)
			//			}
			//		}
			//	}
			//}

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

				if err := BatchInitData(ctx, fromFoodList, toApi, toStore.VendorStoreID, i); err != nil {
					globals.SugarLogger.Debugf("BatchInitData : %s", utils.Format4Output(err, false))
				}
				if len(fromFoodList) < 100 {
					break
				}
				i++
			}

		}
		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, err
}

func LoadingStoreSkuList(ctx *jxcontext.Context, api *mtwmapi.API, poiCode string) (err []error) {
	foodList, err1 := api.RetailListAll(poiCode, 0)
	if err1 != nil {
		return append(err, err1)
	}

	i := 0
	for _, v := range foodList {
		err1 := api.RetailDelete(ctx.GetTrackInfo(), poiCode, v.AppFoodCode)
		if err1 != nil {
			err = append(err, err1)
		}
		if i%40 == 0 {
			time.Sleep(200 * time.Millisecond)
		}
		i++
	}

	return
}

type Skus struct {
	AvailableTimes struct {
		Friday    string `json:"friday"`
		Monday    string `json:"monday"`
		Saturday  string `json:"saturday"`
		Sunday    string `json:"sunday"`
		Thursday  string `json:"thursday"`
		Tuesday   string `json:"tuesday"`
		Wednesday string `json:"wednesday"`
	} `json:"available_times"`
	BoxNum                string `json:"box_num"`
	BoxPrice              string `json:"box_price"`
	IsSellFlag            int    `json:"isSellFlag"`
	LadderBoxNum          string `json:"ladder_box_num"`
	LadderBoxPrice        string `json:"ladder_box_price"`
	LimitOpenSyncStockNow bool   `json:"limit_open_sync_stock_now"`
	LocationCode          string `json:"location_code"`
	MinOrderCount         string `json:"min_order_count"`
	Price                 string `json:"price"`
	SkuId                 string `json:"sku_id"`
	Spec                  string `json:"spec"`
	Stock                 string `json:"stock"`
	Unit                  string `json:"unit"`
	Upc                   string `json:"upc"`
	Weight                string `json:"weight"`
	WeightForUnit         string `json:"weight_for_unit"`
	WeightUnit            string `json:"weight_unit"`
}

// BatchInitData 批量创建商品
func BatchInitData(ctx *jxcontext.Context, fromSku []*mtwmapi.AppFood, toApi *mtwmapi.API, vendorStoreID string, i int) error {
	foodDataList := make([]map[string]interface{}, len(fromSku))
	for i, storeSku := range fromSku {
		foodData := make(map[string]interface{})
		if storeSku.AppFoodCode != "" {
			foodData[mtwmapi.KeyAppFoodCode] = storeSku.AppFoodCode
		} else {
			foodData[mtwmapi.KeyAppFoodCode] = time.Now().UnixNano() + int64(i*3)
		}

		skus := make([]interface{}, 0)
		for _, v := range storeSku.SkuList {
			mapSkuList := utils.Struct2MapByJson(v)
			if v.BoxNum == "" {
				delete(mapSkuList, "box_num")
			}
			if v.BoxPrice == "" {
				delete(mapSkuList, "box_price")
			}
			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
		//todo 增加商品必填属性
		foodData["common_attr_value"] = storeSku.CommonAttrValue
		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
			}
		}

		foodData["is_sold_out"] = storeSku.IsSoldOut
		foodData["picture"] = storeSku.Picture
		foodData["picture_contents"] = storeSku.PictureContents
		foodData["sequence"] = storeSku.Sequence
		foodData["tag_id"] = storeSku.TagID

		foodDataList[i] = 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("RetailBatchInitData2 failedFoodList :%s", utils.Format4Output(failedFoodList, false))
			}
		} else {
			failedFoodList, _ := toApi.RetailBatchInitData(ctx.GetTrackInfo(), vendorStoreID, foodDataList[i*10:(i+1)*10])
			if len(failedFoodList) != 0 {
				globals.SugarLogger.Debugf("RetailBatchInitData4 failedFoodList :%s", utils.Format4Output(failedFoodList, false))
			}
		}

	}

	return nil
}
