package tiktok_api

import (
	"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_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/business/model"
	"git.rosy.net.cn/jx-callback/globals"
	"go.uber.org/zap"
	"strings"
	"testing"
)

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

}

func TestCreateSubProduct(t *testing.T) {
	a.CreateSubProduct(3592508194611683124, 64251631)
}

func TestGetRecommendCategoryByName(t *testing.T) {
	a.GetRecommendCategoryByName("红富士苹果")
}

func TestBatchGetChannelCategoryMapping(t *testing.T) {
	items, err := a.BatchGetChannelCategoryMapping([]int64{
		20326,
		20394,
		20398,
		20401,
		20405,
		20462,
		20470,
		20500,
		20524,
		20527,
		20532,
		20534,
		20537,
		20543,
		20553,
		20557,
		20589,
		20611,
		20693,
		20695,
		20712,
		20714,
		20733,
		20743,
		20744,
		20781,
		20789,
		20816,
		20905,
		20920,
		20921,
		20922,
		20923,
		20941,
		20947,
		20950,
		20951,
		20952,
		20967,
		20969,
		20973,
		21151,
		21672,
		21926,
		22273,
		22317,
		22328,
		22331,
		22334,
		22338,
	})
	globals.SugarLogger.Debugf("-items:= %s", utils.Format4Output(items, false))
	globals.SugarLogger.Debugf("-items:= %v", err)
}

func TestCreateStoreCommodity(t *testing.T) {
	//PayType := int64(1)
	//weight := float64(300)
	param := &product_addV2_request.ProductAddV2Param{
		//OuterProductId: utils.String2Pointer("6119735"),
		//ProductType:    0,
		//CategoryLeafId: 1000006281,
		//Name:            "[同城配送]过水猪耳朵1个",
		RecommendRemark: nil,
		//Pic:             "https://p3-aio.ecombdimg.com/obj/ecom-shop-material/png_m_c3009881689e4115f65344a3f230ac23_sx_535006_www800-800",
		//Description:     "https://p3-aio.ecombdimg.com/obj/ecom-shop-material/png_m_0b96110a31122b380d0bb2f9bbacc8a7_sx_705423_www800-800",
		//PayType:                      &PayType,
		DeliveryMethod: nil,
		CdfCategory:    nil,
		//ReduceType:                   1,
		AssocIds: nil,
		//FreightId: 0,
		//Weight:                       &weight,
		//WeightUnit: &PayType,
		//DeliveryDelayDay:             utils.Int64ToPointer(9999),
		//PresellType:                  utils.Int64ToPointer(0),
		PresellDelay:     nil,
		PresellEndTime:   nil,
		Supply7dayReturn: nil,
		//Mobile:                       "18981810340",
		//Commit:                       true,
		Remark:       nil,
		OutProductId: nil,
		QualityList:  nil,
		SpecName:     nil,
		//Specs:                        utils.String2Pointer("总净重|300g"),
		//SpecPrices:      utils.String2Pointer("[{\"spec_detail_name1\":\"300g\",\"spec_detail_name2\":\"\",\"spec_detail_name3\":\"\",\"stock_num\":999999,\"price\":2500,\"code\":\"6119735\",\"step_stock_num\":0,\"supplier_id\":\"\",\"outer_sku_id\":\"6119735\",\"sku_type\":1,\"stock_num_map\":{\"260477060\":999999},\"delivery_infos\":[{\"info_type\":\"weight\",\"info_value\":\"300\",\"info_unit\":\"g\"}]}]"),
		SpecPic:         nil,
		MaximumPerOrder: utils.Int64ToPointer(50),
		LimitPerBuyer:   utils.Int64ToPointer(200),
		MinimumPerOrder: nil,
		//ProductFormatNew:   utils.String2Pointer("{\"1687\": [{\"diy_type\": 0,\"name\": \"品牌\",\"value\": 596120136}]}"),
		SpuId:              nil,
		AppointDeliveryDay: nil,
		ThirdUrl:           nil,
		Extra:              nil,
		Src:                nil,
		//StandardBrandId:    utils.Int64ToPointer(596120136),
		NeedCheckOut:       nil,
		PoiResource:        nil,
		CarVinCode:         nil,
		PresellConfigLevel: nil,
		//NeedRechargeMode:             nil,
		AccountTemplateId:   nil,
		PresellDeliveryType: nil,
		//WhiteBackGroundPicUrl: utils.String2Pointer("https://p3-aio.ecombdimg.com/obj/ecom-shop-material/png_m_c3009881689e4115f65344a3f230ac23_sx_535006_www800-800"),
		LongPicUrl: nil,
		//AfterSaleService: &map[string]string{"supply_day_return_selector": "7-0"},
		SellChannel: nil,
		//StartSaleType:                utils.Int64ToPointer(0),
		DelayRule:       nil,
		MaterialVideoId: nil,
		//PickupMethod:                 utils.String2Pointer("0"),
		SizeInfoTemplateId: nil,
		SubstituteGoodsUrl: nil,
		SaleChannelType:    nil,
		RecruitInfo:        nil,
		StoreId:            nil,
		MainProductId:      nil,
		//SaleLimitId:                  nil,
		NamePrefix:                   nil,
		ReferencePrice:               nil,
		ReferencePriceCertificate:    nil,
		MainImageThreeToFour:         nil,
		UnitPriceInfo:                nil,
		QualityInspectionInfo:        nil,
		IsC2bSwitchOn:                nil,
		MicroAppId:                   nil,
		IsAutoCharge:                 nil,
		ShortProductName:             nil,
		AfterSaleServiceV2:           nil,
		SpecInfo:                     nil,
		SpecPricesV2:                 nil,
		WithSkuType:                  nil,
		NameSuffix:                   nil,
		UseBrandName:                 nil,
		OpenLogisticsInfo:            nil,
		PriceHasTax:                  nil,
		BizKind:                      nil,
		CustomProperty:               nil,
		IsEvaluateOpened:             nil,
		DefaultProcessTime:           nil,
		CompanyId:                    nil,
		IsSecondHandDigital:          nil,
		RecommendIds:                 &map[string]string{"key": "2026031817465122DCADE158861CDE62EC_17cf3282b23449a"},
		ShowCheckoutEntry:            nil,
		PickupPrepareTime:            nil,
		HomeInstallServiceTemplateId: nil,
		CategoryPropertyPics:         nil,
	}
	a.CreateStoreCommodity(param)
}

func TestGetCatePropertyV2(t *testing.T) {
	categoryList, err := a.GetCatePropertyV2(1000009871)
	if err != nil {
		fmt.Println(err)
	}
	categoryMap := make(map[string][]map[string]interface{})
	for _, v := range categoryList.Data.Data {
		if v.Required != model.YES {
			continue
		}
		options := make([]map[string]interface{}, 0)
		if v.PropertyName == "品牌" {
			options = append(options, map[string]interface{}{"name": v.PropertyName, "value": 596120136, "diy_type": v.DiyType})
			categoryMap[utils.Int64ToStr(v.PropertyId)] = options
		} else if v.PropertyName == "产地" {
			options = append(options, map[string]interface{}{"name": v.PropertyName, "value": 13850, "diy_type": v.DiyType})
			categoryMap[utils.Int64ToStr(v.PropertyId)] = options
		} else if v.PropertyName == "生鲜储存温度" {
			options = append(options, map[string]interface{}{"name": v.PropertyName, "value": 2808, "diy_type": v.DiyType})
			categoryMap[utils.Int64ToStr(v.PropertyId)] = options
		} else if len(v.Options) == 0 {
			options = append(options, map[string]interface{}{"name": v.PropertyName, "value": 0, "diy_type": v.DiyType})
			categoryMap[utils.Int64ToStr(v.PropertyId)] = options
		} else {
			options = append(options, map[string]interface{}{"name": v.PropertyName, "value": utils.Str2Int64(v.Options[0].Value), "diy_type": v.DiyType})
			categoryMap[utils.Int64ToStr(v.PropertyId)] = options
		}
	}
	productFormatNew := utils.Format4Output(categoryMap, false)
	fmt.Println(productFormatNew)
}

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

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

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

func TestUpdateSkuStore(t *testing.T) {
	err := a.UpdateSkuStock(&sku_syncStock_request.SkuSyncStockParam{
		ProductId:   3602878545761816498,
		OutSkuId:    25250,
		StockNum:    0,
		Incremental: false,
	})
	fmt.Println(err)
}

func TestEiduPrice(t *testing.T) {
	err := a.EditPrice(&sku_editPrice_request.SkuEditPriceParam{
		Price:     1000,
		SkuId:     1746278107578416,
		ProductId: 3605159442921953230,
	})
	fmt.Println(err)
}

//// s上架1
//func TestEditStoreCommodity(t *testing.T) {
//	a.GetProductUpdateRule(32241)
//	err := a.EditStoreCommodity(&product_editV2_request.ProductEditV2Param{
//		ProductId:        3605562143317059130,
//		ProductType:      0,
//		CategoryLeafId:   32241,
//		ProductFormat:    "",
//		Name:             "三线肉约500g/份【同城配送】",
//		RecommendRemark:  "",
//		Pic:              "https://p3-aio.ecombdimg.com/obj/ecom-shop-material/VqGYBUaL_m_4bf295c4d3b6466138c5650a4d433935_sx_504060_www800-800",
//		Description:      "https://p3-aio.ecombdimg.com/obj/ecom-shop-material/VqGYBUaL_m_2e3b9a6bbf7649895bff131393b42b4c_sx_463917_www750-3527",
//		PayType:          1,
//		DeliveryMethod:   0,
//		CdfCategory:      "",
//		ReduceType:       2,
//		AssocIds:         "",
//		FreightId:        0,
//		Weight:           500,
//		WeightUnit:       1,
//		DeliveryDelayDay: 9999,
//		PresellType:      0,
//		PresellDelay:     0,
//		PresellEndTime:   "",
//		Supply7dayReturn: 0,
//		Mobile:           "18598908808",
//		Commit:           true,
//		BrandId:          0,
//		Remark:           "",
//		//OutProductId:          0,
//		QualityList:        nil,
//		SpecName:           "",
//		Specs:              "重量|500g",
//		SpecPrices:         "[{\"spec_detail_name1\":\"500g\",\"spec_detail_name2\":\"\",\"spec_detail_name3\":\"\",\"stock_num\":999999,\"price\":3500,\"code\":\"22700\",\"step_stock_num\":0,\"supplier_id\":\"\",\"outer_sku_id\":\"70122700701\",\"sku_type\":1,\"stock_num_map\":{\"173965249\":999999},\"delivery_infos\":[{\"info_type\":\"weight\",\"info_value\":\"500\",\"info_unit\":\"g\"}]}]",
//		SpecPic:            "",
//		MaximumPerOrder:    0,
//		LimitPerBuyer:      0,
//		MinimumPerOrder:    0,
//		ProductFormatNew:   "{\n\t\"1687\": [\n\t\t{\n\t\t\t\"diy_type\": 0,\n\t\t\t\"name\": \"品牌\",\n\t\t\t\"value\": 596120136\n\t\t}\n\t],\n\t\"1758\": [\n\t\t{\n\t\t\t\"diy_type\": 1,\n\t\t\t\"name\": \"包装方式\",\n\t\t\t\"value\": 8197\n\t\t}\n\t],\n\t\"1880\": [\n\t\t{\n\t\t\t\"diy_type\": 0,\n\t\t\t\"name\": \"产地\",\n\t\t\t\"value\": 13850\n\t\t}\n\t],\n\t\"2130\": [\n\t\t{\n\t\t\t\"diy_type\": 0,\n\t\t\t\"name\": \"生鲜储存温度\",\n\t\t\t\"value\": 2808\n\t\t}\n\t]\n}",
//		SpuId:              0,
//		AppointDeliveryDay: 0,
//		ThirdUrl:           "",
//		Extra:              "",
//		Src:                "",
//		//OuterProductId:        "",
//		StandardBrandId:       596120136,
//		NeedCheckOut:          false,
//		PoiResource:           nil,
//		ForceUseQualityList:   false,
//		CarVinCode:            "",
//		PresellConfigLevel:    0,
//		NeedRechargeMode:      false,
//		PresellDeliveryType:   0,
//		WhiteBackGroundPicUrl: "https://p3-aio.ecombdimg.com/obj/ecom-shop-material/VqGYBUaL_m_4bf295c4d3b6466138c5650a4d433935_sx_504060_www800-800",
//		LongPicUrl:            "",
//		AfterSaleService: map[string]string{
//			"supply_day_return_selector": "7-0",
//		},
//		SellChannel:        []int64{0},
//		DelayRule:          nil,
//		MaterialVideoId:    "",
//		PickupMethod:       "0",
//		SizeInfoTemplateId: 0,
//		SubstituteGoodsUrl: "",
//		SaleChannelType:    "",
//		NamePrefix:         "",
//		StoreId:            0,
//		MainProductId:      0,
//		SaleLimitId:        0,
//	})
//	t.Fatal(err)
//}

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

// 解密购买用户电话,名字,地址
func TestBatchDecrypt(t *testing.T) {
	orderID := "6944648365692229066"
	order, err := a.GetTiktokOrderDetail(orderID)
	if err != nil || order == nil {
		globals.SugarLogger.Debugf("GetTiktokOrderDetail err := %s", utils.Format4Output(order, false))
		return
	}
	name, tel, address, err := a.OrderUserInfoDecrypt(orderID, order.EncryptPostReceiver, order.EncryptPostTel, order.PostAddr.EncryptDetail)
	fmt.Println(name)
	fmt.Println(tel)
	fmt.Println(address)
	fmt.Println(err)
}

var c = []int64{}

// 删除已经创建商品,重新同步
func TestDeleteSkuAndUploadSku(t *testing.T) {
	var errList = make([]error, 0, 0)

	//for _, v := range c {
	//for i := 1; i < 100; i++ {
	result, err := a.GetSkuDetailList(&product_listV2_request.ProductListV2Param{
		//Status:      0,
		//CheckStatus: 3, // 1-未提交；2-待审核；3-审核通过；4-审核未通过；5-封禁；7-审核通过待上架
		Page: int64(1),
		Size: 100,
		ProductId: []string{
			"3603821366169751183"},
	})
	if err != nil {
		fmt.Println(err)
	}

	for i2, v2 := range result.Data {
		if v2.ProductId == 3592586515512991033 {
			fmt.Println("aa")
		}
		var sonSkuid int64 = 0
		if len(v2.SpecPrices) != 0 {
			sonSkuid = v2.SpecPrices[0].Id
		}
		sql := fmt.Sprintf(` UPDATE store_sku_bind SET vendor_son_sku_id = "%d" WHERE dd_id = "%d";`, sonSkuid, v2.ProductId)
		fmt.Println(i2-i2, sql)
	}

	//}
	//}

	for _, v := range errList {
		globals.SugarLogger.Debugf("err := %s", utils.Format4Output(v, false))
	}
}

// 删除已经创建商品,重新同步封禁
func TestDeleteSkuAndUploadSkuFengJinBiXu222(t *testing.T) {
	var errList = make([]error, 0, 0)
	for i := 1; i < 100; i++ {
		result, err := a.GetSkuDetailList(&product_listV2_request.ProductListV2Param{
			Status:      0,
			CheckStatus: 3, // 1-未提交；2-待审核；3-审核通过；4-审核未通过；5-封禁；7-审核通过待上架
			Page:        int64(i),
			Size:        10,
			StoreId:     255085124,
		})
		if err != nil {
			globals.SugarLogger.Debugf("=index := %d ,err := %s", i, utils.Format4Output(err, false))
			continue
		}
		if len(result.Data) == 0 {
			break
		}
		//for _, v := range result.Data {
		//	err := a.DeleteStoreCommodity(v.ProductId)
		//	if err != nil {
		//		errList = append(errList, err)
		//	}
		//}
	}

	for _, v := range errList {
		globals.SugarLogger.Debugf("err := %s", utils.Format4Output(v, false))
	}
}

// 删除已经创建商品,重新同步
func TestDeleteSkuAndUploadSku55(t *testing.T) {
	var errList = make([]error, 0, 0)
	for _, v := range c {
		for i := 1; i < 100; i++ {
			result, err := a.GetSkuDetailList(&product_listV2_request.ProductListV2Param{
				CheckStatus: 3, // 1-未提交；2-待审核；3-审核通过；4-审核未通过；5-封禁；7-审核通过待上架
				Page:        int64(i),
				Size:        100,
				StoreId:     v,
			})
			if err != nil {
				globals.SugarLogger.Debugf("=index := %d ,err := %s", i, utils.Format4Output(err, false))
				continue
			}
			if len(result.Data) == 0 {
				globals.SugarLogger.Debugf("====没有商品的门店 %d", v)
				break
			}
			for _, v := range result.Data {
				err := a.DeleteStoreCommodity(v.ProductId)
				if err != nil {
					errList = append(errList, err)
				}
			}
		}
	}

	for _, v := range errList {
		globals.SugarLogger.Debugf("err := %s", utils.Format4Output(v, false))
	}
}
func TestDelete(t *testing.T) {
	a.DeleteStoreCommodity(3809577644748571000)
}

// 删除已经创建商品,重新同步
func TestDeleteSkuAndUploadSku7(t *testing.T) {
	var errList = make([]error, 0, 0)
	for _, v := range c {
		for i := 1; i < 100; i++ {
			result, err := a.GetSkuDetailList(&product_listV2_request.ProductListV2Param{
				CheckStatus: 1, // 1-未提交；2-待审核；3-审核通过；4-审核未通过；5-封禁；7-审核通过待上架
				Page:        int64(i),
				Size:        100,
				StoreId:     v,
				Status:      1,
			})
			if err != nil {
				globals.SugarLogger.Debugf("=index := %d ,err := %s", i, utils.Format4Output(err, false))
				continue
			}
			if len(result.Data) == 0 {
				globals.SugarLogger.Debugf("====没有商品的门店 %d", v)
				break
			}
			for _, v := range result.Data {
				err := a.DeleteStoreCommodity(v.ProductId)
				if err != nil {
					errList = append(errList, err)
				}
			}
		}
	}

	for _, v := range errList {
		globals.SugarLogger.Debugf("err := %s", utils.Format4Output(v, false))
	}
}

/***********************************/
// 删除已经创建商品,重新同步 下架
func TestDeleteSkuAndUploadSkuXiaJiaBiXu(t *testing.T) {
	var errList = make([]error, 0, 0)
	for _, v := range c {
		for i := 1; i < 100; i++ {
			result, err := a.GetSkuDetailList(&product_listV2_request.ProductListV2Param{
				Status:      1,
				CheckStatus: 1, // 1-未提交；2-待审核；3-审核通过；4-审核未通过；5-封禁；7-审核通过待上架
				Page:        int64(i),
				Size:        100,
				StoreId:     63509510,
			})
			if err != nil {
				globals.SugarLogger.Debugf("=index := %d ,err := %s", i, utils.Format4Output(err, false))
				continue
			}
			if len(result.Data) == 0 {
				globals.SugarLogger.Debugf("====没有商品的门店 %d", v)
				break
			}
			for _, v := range result.Data {
				err := a.DeleteStoreCommodity(v.ProductId)
				if err != nil {
					errList = append(errList, err)
				}
			}
		}
	}

	for _, v := range errList {
		globals.SugarLogger.Debugf("err := %s", utils.Format4Output(v, false))
	}
}

// 删除已经创建商品,重新同步封禁
func TestDeleteSkuAndUploadSkuFengJinBiXu(t *testing.T) {
	var errList = make([]error, 0, 0)
	for _, v := range c {
		for i := 1; i < 100; i++ {
			result, err := a.GetSkuDetailList(&product_listV2_request.ProductListV2Param{
				Status:      1,
				CheckStatus: 5, // 1-未提交；2-待审核；3-审核通过；4-审核未通过；5-封禁；7-审核通过待上架
				Page:        int64(i),
				Size:        100,
				StoreId:     v,
			})
			if err != nil {
				globals.SugarLogger.Debugf("=index := %d ,err := %s", i, utils.Format4Output(err, false))
				continue
			}
			if len(result.Data) == 0 {
				globals.SugarLogger.Debugf("====没有商品的门店 %d", v)
				break
			}
			for _, v := range result.Data {
				err := a.DeleteStoreCommodity(v.ProductId)
				if err != nil {
					errList = append(errList, err)
				}
			}
		}
	}

	for _, v := range errList {
		globals.SugarLogger.Debugf("err := %s", utils.Format4Output(v, false))
	}
}

// 删除已经创建商品,重新同步延迟上架
func TestDeleteSkuAndUploadSkuYanChiBiXu(t *testing.T) {
	var errList = make([]error, 0, 0)
	for _, v := range c {
		for i := 1; i < 100; i++ {
			result, err := a.GetSkuDetailList(&product_listV2_request.ProductListV2Param{
				Status:      0,
				CheckStatus: 7, // 1-未提交；2-待审核；3-审核通过；4-审核未通过；5-封禁；7-审核通过待上架
				Page:        int64(i),
				Size:        100,
				StoreId:     v,
			})
			if err != nil {
				globals.SugarLogger.Debugf("=index := %d ,err := %s", i, utils.Format4Output(err, false))
				continue
			}
			if len(result.Data) == 0 {
				globals.SugarLogger.Debugf("====没有商品的门店 %d", 111)
				break
			}
			for _, v := range result.Data {
				err := a.DeleteStoreCommodity(v.ProductId)
				if err != nil {
					errList = append(errList, err)
				}
			}
		}
	}
	for _, v := range errList {
		globals.SugarLogger.Debugf("err := %s", utils.Format4Output(v, false))
	}
}

// 删除已经创建商品,重新同步封禁
func TestDeleteSkuAndUploadSkuFengJinBiXu22332(t *testing.T) {
	var errList = make([]error, 0, 0)
	for i := 1; i < 100; i++ {
		result, err := a.GetSkuDetailList(&product_listV2_request.ProductListV2Param{
			Status:      0,
			CheckStatus: 3, // 1-未提交；2-待审核；3-审核通过；4-审核未通过；5-封禁；7-审核通过待上架
			Page:        int64(i),
			Size:        100,
			StoreId:     81521327,
		})
		if err != nil {
			globals.SugarLogger.Debugf("=index := %d ,err := %s", i, utils.Format4Output(err, false))
			continue
		}
		if len(result.Data) == 0 {
			break
		}
		for _, v := range result.Data {
			err := a.DeleteStoreCommodity(v.ProductId)
			if err != nil {
				errList = append(errList, err)
			}
		}
	}

	for _, v := range errList {
		globals.SugarLogger.Debugf("err := %s", utils.Format4Output(v, false))
	}
}
