package mtwmapi

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/globals"
	"testing"
	"time"
)

var fromStoreId = "7111680"
var toStoreId = "8694010"

func TestBatchQueryBuyGiftsAll(t *testing.T) {
	var errData = make([]error, 0, 0)
	buyGiftList, err := api.BatchQueryBuyGiftsAll(fromStoreId)

	if err != nil {
		errData = append(errData, fmt.Errorf("买赠活动异常:%v", errData))
		return
	}
	if len(buyGiftList) == 0 {
		errData = append(errData, fmt.Errorf("门店暂无买赠活动"))
		return
	}

	param := make([]*BatchCreateBuyGiftsParam, 0, 0)
	for _, v := range buyGiftList {
		buyGift := &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 := &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)
	}

	result, err := api.BatchCreateBuyGifts(toStoreId, param)
	globals.SugarLogger.Debugf("result := %s", utils.Format4Output(result, false))
	globals.SugarLogger.Debugf("result := %v", err)
}

// 获取门店满减
func TestBatchGetDiscountList(t *testing.T) {
	// 全店满减活动
	data, err := api.BatchGetDiscountList(fromStoreId, 0)
	globals.SugarLogger.Debugf("data:= %s", utils.Format4Output(data, false))
	globals.SugarLogger.Debugf("err:= %v", err)
	for k, v := range data {
		param := &CreateDiscountList{
			AppPoiCode: toStoreId,
			ActInfo:    "",
			ActDetails: "",
			AppFoods:   "",
		}
		actInfo := &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
		}
		param.ActInfo = string(actInfoByte)

		actDetails := make([]CreateDiscountActDetails, 0, 0)
		for _, ads := range v.ActDetails {
			actDetails = append(actDetails, CreateDiscountActDetails{
				OriginPrice: utils.Float64TwoInt(ads.OriginPrice),
				ActPrice:    utils.Float64TwoInt(ads.ActPrice),
			})
		}
		actDetailsByte, err := json.Marshal(actDetails)
		if err != nil {
			return
		}
		param.ActDetails = string(actDetailsByte)
		api.BatchCreateDiscountList(param)
	}
}

// 运费满减
func TestGetShippingFee(t *testing.T) {
	data, err := api.BatchGetShippingFee(fromStoreId)
	if err != nil {
		return
	}

	if data.SuccessList != nil && len(data.SuccessList) != 0 {
		param := make([]*ShippingFeeBatchCreateActData, 0, 0)
		for _, v := range data.SuccessList {
			shippingFee := &ShippingFeeBatchCreateActData{
				StartTime: v.StartTime,
				EndTime:   v.EndTime,
				WeeksTime: v.WeeksTime,
				Period:    v.Period,
				MaxPrice:  v.MaxPrice,
			}
			actDetail := make([]ShippingFeeBatchCreateActDataActDetail, 0, 0)
			for _, ad := range v.ActDetail {
				actDetail = append(actDetail, ShippingFeeBatchCreateActDataActDetail{
					LimitPrice:    ad.LimitPrice,
					DiscountPrice: ad.DiscountPrice,
				})
			}
			shippingFee.ActDetail = actDetail

			param = append(param, shippingFee)
		}

		resultData, err := api.BatchCreateShippingFee(toStoreId, param)
		if err != nil {
			return
		}
		if resultData.Data != "ok" {
			return //resultData.Msg
		}
		return // nil
	}

	return // 满减运费活动获取失败
	globals.SugarLogger.Debugf("==result := %s", utils.Format4Output(data, false))
	globals.SugarLogger.Debugf("==err := %v", err)
}

// 创建折扣爆品活动
func TestProductsAct(t *testing.T) {
	secKillALL, err := api.QueryProductsAll(fromStoreId, RetailActTypeSecKill)
	if err != nil {
		return
	}

	killAct := make([]*RetailDiscountActData, 0, 0)
	for _, v := range secKillALL {
		kill := &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 := api.QueryProductsAll(fromStoreId, RetailActTypeDirectDown)
	for _, v := range directDownALL {
		kill := &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 := api.CreateProductsAct(toStoreId, RetailActTypeSecKill, killAct)
		if err != nil {
			return
		}

		return
	}

}

func TestQueryStoreCoupon(t *testing.T) {
	couponList, err := api.QueryStoreCoupon(fromStoreId)
	if err != nil {
		return
	}
	if len(couponList) != 0 {
		for _, v := range couponList {
			couponInfoList := make([]*CouponInfo, 0, 0)
			for _, ad := range v.ActData {
				couponInfoList = append(couponInfoList, &CouponInfo{
					LimitPrice:   ad.LimitPrice,
					CouponPrice:  ad.CouponPrice,
					UserType:     ad.UserType,
					ValidityDays: ad.ValidityDays,
					Stock:        ad.Stock,
				})
			}

			limitTime := &LimitTime{
				StartTime: v.StartTime,
				EndTime:   v.EndTime,
			}

			if _, err := api.CreateStoreCouponBatch(toStoreId, limitTime, couponInfoList); err != nil {
				return
			}
		}
	}
	globals.SugarLogger.Debugf("======err := %v", err)
	globals.SugarLogger.Debugf("======couponList := %s", utils.Format4Output(couponList, false))
}

// todo 创建X件Y折,X件减Y元活动查询不出来,商家端也不展示
func TestQueryBundlesAct(t *testing.T) {
	result := make([]*BundlesSuccessListDetail, 0, 0)
	// X件M元
	bundlesXM, _ := api.QueryBundlesAct(fromStoreId, 0)
	if bundlesXM != nil {
		result = append(result, bundlesXM...)
	}
	// X件Y折
	bundlesXY, _ := api.QueryBundlesAct(fromStoreId, 2)
	if bundlesXY != nil {
		result = append(result, bundlesXY...)
	}
	globals.SugarLogger.Debugf("=bundlesXM := %s", utils.Format4Output(bundlesXM, false))
	globals.SugarLogger.Debugf("=bundlesXY := %s", utils.Format4Output(bundlesXY, false))

	for _, v := range result {
		actSku, err := api.QueryBundlesSku(fromStoreId, utils.Int64ToStr(v.ActId))
		globals.SugarLogger.Debugf("=actSku := %s", utils.Format4Output(actSku, false))
		globals.SugarLogger.Debugf("=actSkuerr := %v", err)
	}
	//	for _, as := range actSku {
	//		param := &CreateBundlesActParam{
	//			ActName:   v.ActName,
	//			StartTime: v.StartTime,
	//			EndTime:   v.EndTime,
	//			ActPrice:  v.a,
	//			ActNum:    v.a,
	//			AppFoods:  nil,
	//		}
	//		api.CreateBundlesAct(toStoreId)
	//	}
	//
	//}
	//for _, v := range result {
	//	param := &CreateBundlesActParam{
	//		ActId:     0, // 更新时填写
	//		ActName:   v.ActName,
	//		StartTime: v.StartTime,
	//		EndTime:   v.EndTime,
	//		ActPrice:  0,
	//		ActNum:    0,
	//		AppFoods:  nil,
	//	}
	//	for _, ads := range v.ActDetails {
	//		param.ActPrice = ads.ActNum
	//	}
	//	api.CreateBundlesAct()
	//}
}

// 加价购
func TestQueryStoreRepurchase(t *testing.T) {

	repurchase, err := api.QueryStoreRepurchase(fromStoreId)
	//for _, v := range repurchase {
	//	param := &RepurchaseCreate{
	//		ActName:   v.ActName,
	//		StartTime: v.StartTime,
	//		EndTime:   v.EndTime,
	//		ActPrice:  v.ActPrice,
	//		ActRemark: v.ActRemark,
	//		AppFoods:  nil,
	//	}
	//	appFoods := make([]RepurchaseCreateAppFoods, 0, 0)
	//	for _, sei := range v.ExtraInfo.SkuExtraInfo {
	//		appFood := RepurchaseCreateAppFoods{
	//			AppSpuCode: sei.AppSpuCode,
	//			ActPrice:   v.ActPrice,
	//			DayLimit:   sei.,
	//		}
	//	}
	//	api.CreateStoreRepurchase(toStoreId,param)
	//}
	globals.SugarLogger.Debugf("=repurchase := %s", utils.Format4Output(repurchase, false))
	globals.SugarLogger.Debugf("=bundlesXY := %v", err)
}

// 商品券
func TestCreateCouponAct(t *testing.T) {

	couponInfoAll := make([]*GetStoreCouponActSuccessList, 0, 0)
	pageNumber := 1
	pageSize := 100
	for {
		param := &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 := api.GetStoreCouponAct(param)
		globals.SugarLogger.Debugf("=couponList := %s", utils.Format4Output(couponList, false))
		globals.SugarLogger.Debugf("=err := %v", err)
		if err != nil {
			return
		}
		couponInfoAll = append(couponInfoAll, couponList...)
		if len(couponList) < pageSize {
			break
		}
		pageNumber++
	}

	for _, v := range couponInfoAll {
		couponSkuList, err := api.GetCouponActSkuList(fromStoreId, utils.Int64ToStr(v.ActId))
		if err != nil {
			return
		}

		for _, csl := range couponSkuList {
			param := &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, CreateCouponActSpuData{
						AppSpuCode: sd.AppSpuCode,
						SkuId:      sd.SkuId,
						Upc:        sd.Upc,
					})
				}
			}

			if csl.ActPriceCouponInfo != nil && len(csl.ActPriceCouponInfo) != 0 {
				//actPriceCouponInfoStr := make([]string, 0, 0)
				//for _, apci := range csl.ActPriceCouponInfo {
				//	actPriceCouponInfo, _ := json.Marshal(apci)
				//	actPriceCouponInfoStr = append(actPriceCouponInfoStr, string(actPriceCouponInfo))
				//}
				param.ActPriceCouponInfo = csl.ActPriceCouponInfo
			}
			if csl.DiscountCouponInfo != nil && len(csl.DiscountCouponInfo) != 0 {
				//discountCouponInfoStr := make([]string, 0, 0)
				//for _, dci := range csl.DiscountCouponInfo {
				//	discountCouponInfo, _ := json.Marshal(dci)
				//	discountCouponInfoStr = append(discountCouponInfoStr, string(discountCouponInfo))
				//}
				param.DiscountCouponInfo = csl.DiscountCouponInfo
			}

			createCouponResult, err := api.CreateCouponAct(param)
			if err != nil {
				return
			}
			globals.SugarLogger.Debugf("=%v", createCouponResult)
		}
	}

}
