package tiktok_api

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi"
	product_addV2_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/product_addV2/request"
	product_editV2_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/product_editV2/request"
	product_editV2_commit_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/product_editV2_commit/request"
	product_listV2_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/product_listV2/request"
	sku_editPrice_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/sku_editPrice/request"
	sku_syncStock_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/sku_syncStock/request"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/globals"
	"go.uber.org/zap"
	"math/rand"
	"strings"
	"testing"
	"time"
)

func init() {
	logger, _ := zap.NewDevelopment()
	sugarLogger = logger.Sugar()
	baseapi.Init(sugarLogger)

	// sandbox
	// api = New("7136048270014416392", "c397aa9f-3927-47c4-8cfe-4d84e02602e0")
	// prod
}

func TestCategory(t *testing.T) {
	data, err := a.GetShopCategory(20314)
	for _, v := range data {
		fmt.Println(v.Id, "---", v.Name, "---", v.IsLeaf, "---", v.Level)
	}
	fmt.Println("data====", err)
}

func TestGetCatePropertyV2(t *testing.T) {
	data, err := a.GetCatePropertyV2(33622)
	fmt.Println("err=====", err)
	globals.SugarLogger.Debugf("data:=%s", utils.Format4Output(data, false))
	fmt.Println("data====", data) // 202209281558450102081001701D7B32C5
}

// 新增总部商品
func TestCreateStoreCommodity(t *testing.T) {
	param := &product_addV2_request.ProductAddV2Param{
		//ProductType:           0,
		CategoryLeafId:  29146,
		ProductFormat:   "",
		Name:            "精华补水液-1",
		RecommendRemark: "商家推荐话术-1",
		Pic:             "https://p3-aio.ecombdimg.com/obj/ecom-shop-material/mXJgSMMc_m_b3dbe91196472e0f4bb05e779a21bf81_sx_112313_www800-800|https://p3-aio.ecombdimg.com/obj/ecom-shop-material/mXJgSMMc_m_8433e90bec56f791d4bfa4d47ee1e12c_sx_206128_www800-800", //轮播图,第一张为主图
		Description:     "https://p3-aio.ecombdimg.com/obj/ecom-shop-material/mXJgSMMc_m_b3dbe91196472e0f4bb05e779a21bf81_sx_112313_www800-800|https://p3-aio.ecombdimg.com/obj/ecom-shop-material/mXJgSMMc_m_8433e90bec56f791d4bfa4d47ee1e12c_sx_206128_www800-800", //商品描述图
		//PayType:               0,
		//DeliveryMethod:        0,
		//CdfCategory:           "",
		ReduceType: SkuReduceTypePayMakeOrder, //1 减库存类型：1-拍下减库存 2-付款减库存
		//AssocIds:              "",
		FreightId: 11111, // 运费模板id
		//Weight:                0,
		//WeightUnit:            0,
		DeliveryDelayDay:   DeliveryDelayDayTomorrow, // 现货发货(presell_type=0)和阶梯发货模式(presell_type=2)时必填
		PresellType:        1,                        // 0现发货/1预售发货/2阶梯发货
		PresellConfigLevel: 1,                        // 0现发货/1预售发货/2阶梯发货
		//PresellDelay:          0,
		//PresellEndTime:        "",
		//Supply7dayReturn:      0,
		Mobile: "18981810340",
		Commit: false,
		//BrandId:               0,
		Remark: "商家备注",
		//OutProductId:          0,
		//QualityList:           nil,
		//SpecName:              "",
		Specs: "颜色|红色,黑色",
		//SpecPrices:            "",
		//SpecPic:               "",
		//MaximumPerOrder:       0,
		//LimitPerBuyer:         0,
		//MinimumPerOrder:       0,
		//ProductFormatNew: "29146",
		//SpuId:                 0,
		//AppointDeliveryDay:    0,
		//ThirdUrl:              "",
		//Extra:                 "",
		//Src:                   "",
		//StandardBrandId:       0,
		//NeedCheckOut:          false,
		//PoiResource:           nil,
		//CarVinCode:            "",
		//PresellConfigLevel:    0,
		//NeedRechargeMode:      false,
		//AccountTemplateId:     "",
		//PresellDeliveryType:   0,
		//WhiteBackGroundPicUrl: "",
		//LongPicUrl:            "",
		//AfterSaleService:      nil,
		//SellChannel:           nil,
		StartSaleType: 0, // 立即上架
		//DelayRule:             nil,
		//MaterialVideoId:       "",
		PickupMethod: "0",
		//SizeInfoTemplateId:    0,
		//SubstituteGoodsUrl:    "",
		//SaleChannelType:       "",
		//RecruitInfo:           nil,
		//StoreId:               0,
		//MainProductId:         0,
		//SaleLimitId:           0,
		//NamePrefix:            "",
	}

	// 获取属性
	category, err := a.GetCatePropertyV2(param.CategoryLeafId)
	format := make(map[string][]*ProductFormatNewList, 0)
	for _, v := range category.Data.Data {
		if v.Required != 1 {
			continue
		}
		for _, d := range v.Options {
			formateNew := &ProductFormatNewList{
				Value:   utils.Str2Int64(d.Value),
				Name:    d.Name,
				DiyType: v.DiyType,
			}
			format[utils.Int64ToStr(v.PropertyId)] = append(format[utils.Int64ToStr(v.PropertyId)], formateNew)
		}
	}
	productFormatNew, err := json.Marshal(format)
	param.ProductFormatNew = string(productFormatNew)

	skuSize := make([]*SpecDetailList, 0, 0)
	skuDetail := param.Specs
	detail1 := strings.Split(skuDetail, "^")
	if len(detail1) > 3 {
		return
	}

	switch len(detail1) {
	case 1:
		name1 := strings.Split(strings.Split(detail1[0], "|")[1], ",")
		for i := 0; i < len(name1); i++ {
			sku := &SpecDetailList{
				SpecDetailName1: name1[i],
				StockNum:        750,
				Price:           100,
				Code:            "19930826",
				StepStockNum:    0,
				SupplierID:      "jxcs1993",
				OuterSkuID:      "1997338" + utils.Int2Str(i),
				DeliveryInfos: []*DeliveryInfos{
					{InfoType: "weight", InfoUnit: "kg", InfoValue: "250"},
					{InfoType: "weight", InfoUnit: "g", InfoValue: "250"},
					{InfoType: "weight", InfoUnit: "mg", InfoValue: "250"},
				},
			}
			skuSize = append(skuSize, sku)
		}
	case 2:
		name1 := strings.Split(strings.Split(detail1[0], "|")[1], ",")
		name2 := strings.Split(strings.Split(detail1[1], "|")[1], ",")
		for i := 0; i < len(name1); i++ {
			for j := 0; j < len(name2); j++ {
				sku := &SpecDetailList{
					SpecDetailName1: name1[i],
					SpecDetailName2: name2[j],
					StockNum:        750,
					Price:           100,
					Code:            "19930826",
					StepStockNum:    0,
					SupplierID:      "jxcs1993",
					OuterSkuID:      "1997338",
					DeliveryInfos: []*DeliveryInfos{
						{InfoType: "weight", InfoUnit: "kg", InfoValue: "250"},
						{InfoType: "weight", InfoUnit: "g", InfoValue: "250"},
						{InfoType: "weight", InfoUnit: "mg", InfoValue: "250"},
					},
				}
				skuSize = append(skuSize, sku)
			}
		}
	case 3:
		name1 := strings.Split(strings.Split(detail1[0], "|")[1], ",")
		name2 := strings.Split(strings.Split(detail1[1], "|")[1], ",")
		name3 := strings.Split(strings.Split(detail1[2], "|")[1], ",")
		for i := 0; i < len(name1); i++ {
			for j := 0; j < len(name2); j++ {
				for k := 0; k < len(name3); k++ {
					sku := &SpecDetailList{
						SpecDetailName1: name1[i],
						SpecDetailName2: name2[j],
						SpecDetailName3: name3[k],
						StockNum:        750,
						Price:           100,
						Code:            "19930826",
						StepStockNum:    0,
						SupplierID:      "jxcs1993",
						OuterSkuID:      "1997338",
						DeliveryInfos: []*DeliveryInfos{
							{InfoType: "weight", InfoUnit: "kg", InfoValue: "250"},
							{InfoType: "weight", InfoUnit: "g", InfoValue: "250"},
							{InfoType: "weight", InfoUnit: "mg", InfoValue: "250"},
						},
					}
					skuSize = append(skuSize, sku)
				}
			}
		}
	}

	specPricesString, _ := json.Marshal(skuSize)
	param.SpecPrices = string(specPricesString)
	data, err := a.CreateStoreCommodity(param)
	fmt.Println("err=============", err)
	fmt.Println("data===", fmt.Sprintf("%v", data))
}

func TestInt16(t *testing.T) {
	fmt.Println(utils.Str2Int16(strings.ReplaceAll("08:00", ":", "")))
}

// 查询商品详情(抖音平台id)
func TestGetSkuDetail(t *testing.T) {
	data, err := a.GetSkuDetailLocalID("", "6099286")
	fmt.Println(err)
	// 3582171870197365727 3582171870197365727
	globals.SugarLogger.Debugf("====%s", utils.Format4Output(data, false))
}

// 查询商品详情本地商品id
func TestGetSkuDetailLocalId(t *testing.T) {
	data, err := a.GetSkuDetail("3588469215562226655", "")
	fmt.Println(err)
	globals.SugarLogger.Debugf("====%s", utils.Format4Output(data, false))
}

func TestUpdateSkuStore(t *testing.T) {
	err := a.UpdateSkuStock(&sku_syncStock_request.SkuSyncStockParam{
		SkuId:          1747916594479148,
		ProductId:      3579733194175557759,
		OutProductId:   0,
		Incremental:    false,
		IdempotentId:   "",
		StockNum:       2,
		OutWarehouseId: "65402632",
		Code:           "",
		OutSkuId:       0,
		SupplierId:     "",
		StepStockNum:   0,
	})
	fmt.Println(err)
}

func TestEiduPrice(t *testing.T) {
	token := `{"access_token":"a1746210-a8a3-4497-a87b-09d1f10dbb95","expires_in":1665652230,"scope":"SCOPE","shop_id":"","shop_name":"小时达开放平台对接专用店","refresh_token":"c1cf8d88-0983-4f2a-b969-3746fae6b0cd","authority_id":""}`
	a := New("7136048270014416392", "c397aa9f-3927-47c4-8cfe-4d84e02602e0", token)
	err := a.EditPrice(&sku_editPrice_request.SkuEditPriceParam{
		Price: 500,
		//Code:         "",
		SkuId: 1746278107578416,
		//OutSkuId:     0,
		ProductId: 3576377564144516403,
		//OutProductId: 0,
	})
	fmt.Println(err)
}

// s上架1
func TestEditStoreCommodity(t *testing.T) {
	err := a.EditStoreCommodity(&product_editV2_request.ProductEditV2Param{
		CategoryLeafId:      22428,
		Name:                "净芹菜约350g/份(净菜芹菜摘叶洗净，保鲜膜包装)",
		Pic:                 "https://p3-aio.ecombdimg.com/obj/ecom-shop-material/PTWpUjYg_m_78dbc86c51be55406cd2f51bc863b2e0_sx_32178_www800-800",
		Description:         "https://p3-aio.ecombdimg.com/obj/ecom-shop-material/PTWpUjYg_m_4fdaab3dd1df6ed4aa8d0990b0e99ee7_sx_456574_www750-3527",
		PayType:             1,
		ReduceType:          2,
		Weight:              350,
		WeightUnit:          1,
		DeliveryDelayDay:    9999,
		Mobile:              "18048531223",
		Commit:              true,
		Specs:               "重量|350g",
		SpecPrices:          "[{\"spec_detail_name1\":\"350g\",\"spec_detail_name2\":\"\",\"spec_detail_name3\":\"\",\"stock_num\":9999,\"price\":850,\"code\":\"23010\",\"step_stock_num\":0,\"supplier_id\":\"\",\"outer_sku_id\":\"23010\",\"sku_type\":1,\"stock_num_map\":{\"79226307\":9999},\"delivery_infos\":[{\"info_type\":\"weight\",\"info_value\":\"350\",\"info_unit\":\"g\"}]}]",
		ProductFormatNew:    "{\n\t\"1687\": [\n\t\t{\n\t\t\t\"diy_type\": 0,\n\t\t\t\"name\": \"品牌\",\n\t\t\t\"value\": 789194134\n\t\t}\n\t]\n}",
		StandardBrandId:     789194134,
		NeedCheckOut:        false,
		ForceUseQualityList: false,
		NeedRechargeMode:    false})
	t.Fatal(err)
}

// 上架2
func TestEditStoreCommodity2(t *testing.T) {
	a.EditStoreCommodityCommit(&product_editV2_commit_request.ProductEditV2Param2{
		ProductId: 3576377564144516403,
		Commit:    true,
	})
}

// 下架
func TestProductSetOffline(t *testing.T) {
	token := `{"access_token":"a1746210-a8a3-4497-a87b-09d1f10dbb95","expires_in":1665652230,"scope":"SCOPE","shop_id":"","shop_name":"小时达开放平台对接专用店","refresh_token":"c1cf8d88-0983-4f2a-b969-3746fae6b0cd","authority_id":""}`
	a := New("7136048270014416392", "c397aa9f-3927-47c4-8cfe-4d84e02602e0", token)
	a.ProductSetOffline(3576377564144516403)
}

// 解密购买用户电话,名字,地址
func TestBatchDecrypt(t *testing.T) {
	token := `{"access_token":"a1746210-a8a3-4497-a87b-09d1f10dbb95","expires_in":1665652230,"scope":"SCOPE","shop_id":"","shop_name":"小时达开放平台对接专用店","refresh_token":"c1cf8d88-0983-4f2a-b969-3746fae6b0cd","authority_id":""}`

	a := New("7136048270014416392", "c397aa9f-3927-47c4-8cfe-4d84e02602e0", token)
	encrypt_post_tel := `##3aVwfhe5fJHdlO0UijiOA3GbeZYsIZppi+Y9bpYZ9gRBshpl555DP9B1FFp8R0fbyiTaeU9LAck8nkzKNMp5frZUO0w2ba8lsm+1zwYZrBkFlQ==*CgkIARCtHCABKAESPgo8d1IWxRMUZ/3UM2wAbb6m8jXa0z/h/RDf4NnIrUK3Zfiqg+/rrvoo/3DX9DQfmAW/5DkNVk2beqYZx0tYGgA=#1##`
	encrypt_post_receiver := `##K3dJts44TlQGmLNQAHud1Iivzu6rWDeFx8EwQYK35oMXVtlLGgN+ZmQDIa7K6rVzXYReq3dgKz8Vi4VGVR8kR45BpHZdaVJUx2tCwM0=*CgkIARCtHCABKAESPgo8X7FrpSxbV2yGA29uxewKEdHW+Rp1tiqWGxRZgwirlJX2uOILTwCWTN6Q1sT3JHeTjXgXslRTEqqWcdd/GgA=#1##`
	encrypt_post_name := ``
	a.OrderUserInfoDecrypt("4988546918828606694", encrypt_post_name, encrypt_post_tel, encrypt_post_receiver)
}

//// 脱敏购买用户电话,名字,地址
//func TestOrderUserInfoSensitive(t *testing.T) {
//	token := `{"access_token":"a1746210-a8a3-4497-a87b-09d1f10dbb95","expires_in":1665652230,"scope":"SCOPE","shop_id":"","shop_name":"小时达开放平台对接专用店","refresh_token":"c1cf8d88-0983-4f2a-b969-3746fae6b0cd","authority_id":""}`
//
//	a := New("7136048270014416392", "c397aa9f-3927-47c4-8cfe-4d84e02602e0", token)
//	a.OrderUserInfoSensitive("4988354190732430566")
//}

func TestGetSkuList(t *testing.T) {
	result, err := a.GetSkuDetailList(&product_listV2_request.ProductListV2Param{
		Status:          0,
		CheckStatus:     4,
		ProductType:     0,
		StartTime:       0,
		EndTime:         0,
		Page:            1,
		Size:            100,
		UpdateStartTime: 0,
		UpdateEndTime:   0,
	})

	for _, v := range result.Data {
		fmt.Println(fmt.Sprintf("mainid:[%d],outId:[%d],outerId:[%s]", v.ProductId, v.OutProductId, v.OuterProductId))
	}
	globals.SugarLogger.Debugf("result:= %s", err)
}

func TestGetBrandId(t *testing.T) {
	a.GetSkuBrand(29073)
}

func Test11111(t *testing.T) {
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < 10; i++ {
		randNumber := rand.Int63n(481)
		if randNumber < 60 {
			randNumber += 60
		}
		fmt.Println(randNumber)
	}
}

func TestGetProductUpdateRule(t *testing.T) {
	keys := make(map[int64]bool, 0)
	data, _ := a.GetShopCategory(0)
	for _, v1 := range data {
		if len(v1.Children) > 0 {
			for _, v2 := range v1.Children {
				if len(v2.Children) > 0 {
					for _, v3 := range v2.Children {
						if len(v3.Children) > 0 {
							for _, v4 := range v3.Children {
								if v4.Enable {
									keys[v4.Id] = a.GetProductUpdateRule(v4.Id)
								}
							}
						}
						keys[v3.Id] = a.GetProductUpdateRule(v3.Id)
					}
				}
				keys[v2.Id] = a.GetProductUpdateRule(v2.Id)
			}
		}
		keys[v1.Id] = a.GetProductUpdateRule(v1.Id)
	}
	globals.SugarLogger.Debugf("====%d", len(keys))
	globals.SugarLogger.Debugf("====%s", utils.Format4Output(keys, false))
}

func TestNameeeee(t *testing.T) {
	aa := `667278_/image/4229fbb12a40ddcc7a2d42728f`
	fmt.Println(strings.Contains(aa, "detail_"))
}

func TestGetProductUpdateRule2(t *testing.T) {
	a.GetProductUpdateRule2(20219)
}

func TestPPPPPPPPPPPPPP(t *testing.T) {
	aa := "该商品类目选择错误，推荐放置在“面条/挂面（待煮面条）”类目中."

	for _, v := range strings.Split(aa, "“") {
		fmt.Println(v)
	}
}

func TestGetProductAuditList(t *testing.T) {
	data, _, _ := a.GetProductAuditList(1, 100, 2)
	updateCategory := make(map[string]string, 0) // 修改分类的Map
	for _, v := range data {
		if _, ok := v.AuditReason["综合原因"]; ok {
			if strings.Contains(v.AuditReason["综合原因"][0], "该商品类目选择错误，推荐放置在") {
				list := strings.Split(v.AuditReason["综合原因"][0], `“`)
				list2 := strings.Split(list[1], `”`)
				categoryNameList := strings.Split(list2[0], "/")
				updateCategory[utils.Int64ToStr(v.ProductId)] = categoryNameList[len(categoryNameList)-1]
			}
		}

	}
}

func Test111(t *testing.T) {
	fmt.Println(time.Now().Sub(time.Now().Add(time.Minute * 120)))
}
