package tiktok_api

import (
	"bytes"
	"encoding/json"
	"fmt"
	freightTemplate_create_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/freightTemplate_create/request"
	freightTemplate_update_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/freightTemplate_update/request"
	shop_batchCreateStore_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_batchCreateStore/request"
	shop_bindStoreSaleLimit_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_bindStoreSaleLimit/request"
	shop_editStore_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_editStore/request"
	shop_getStoreDetail_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_getStoreDetail/request"
	shop_getStoreList_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_getStoreList/request"
	shop_storeSuspend_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_storeSuspend/request"
	shop_unsuspendStore_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/shop_unsuspendStore/request"
	trade_createTradeLimitTemplate_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/trade_createTradeLimitTemplate/request"
	warehouse_bindFences_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/warehouse_bindFences/request"
	warehouse_bindFencesByStore_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/warehouse_bindFencesByStore/request"
	warehouse_bindStore_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/warehouse_bindStore/request"
	warehouse_create_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/warehouse_create/request"
	warehouse_createBatch_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/warehouse_createBatch/request"
	warehouse_createFence_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/warehouse_createFence/request"
	warehouse_setFence_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/warehouse_setFence/request"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/globals"
	"math/rand"
	"strconv"
	"strings"
	"testing"
	"time"
)

//创建店铺
func TestCreateStore(t *testing.T) {
	accesstoken := `{"access_token":"c4afc5bc-7ddf-4244-b35a-0c393f3dca32","expires_in":1666862533,"scope":"SCOPE","shop_id":"57939570","shop_name":"京西菜市速食","refresh_token":"5a4f9dfe-306b-4bca-8b35-2ae9afc0245e","authority_id":""}`
	a := New("7136048270014416392", "c397aa9f-3927-47c4-8cfe-4d84e02602e0", accesstoken)

	param := shop_batchCreateStore_request.StoreListItem{
		RowId:     1,
		Name:      "测试错误返回1025",
		StoreCode: "668473",
		Longitude: "104.052236",
		Latitude:  "30.691359",
		Province:  "四川省",
		City:      "成都市",
		District:  "金牛区",
		Address:   "成都市金牛区市政府旁",
		Contact:   "18981810340",
		//OpenTime: &shop_batchCreateStore_request.OpenTime{DayMap: map[int64]string{
		//	1: "07:00-12:00 14:00-18:00",
		//}},
	}
	paramList := &shop_batchCreateStore_request.ShopBatchCreateStoreParam{}
	paramList.StoreList = append(paramList.StoreList, param)
	data, err := a.BatchCreateStore(paramList)
	fmt.Println("data==", data)
	fmt.Println("err==", err)
}

//门店列表分页查询
func TestGetStoreList(t *testing.T) {
	data, err := a.GetStoreList(&shop_getStoreList_request.ShopGetStoreListParam{
		Page:     "1",
		PageSize: "20",
	})
	for _, v := range data {
		fmt.Println(v)
	}
	fmt.Println(err)
}

//获取门店详细信息
func TestGetStoreDetail(t *testing.T) {
	data, err := a.GetStoreDetail(&shop_getStoreDetail_request.ShopGetStoreDetailParam{
		StoreId: "62490423",
	})
	fmt.Println(utils.Format4Output(data, false))
	fmt.Println(err)
}
func TestSysnc(t *testing.T) {
	fmt.Println((2 & 2) != 0) // 创建
}

func TestStoreTemp(t *testing.T) {
	a.GetStoreBindTemp(65402632)
}

func TestAPI_CreateTradeLimitTemplate(t *testing.T) {
	parmam := 1
	tempDetail := &freightTemplate_create_request.FreightTemplateCreateParam{
		Template: &freightTemplate_create_request.Template{
			TemplateName:    "盐田蔬菜11号_208452_",
			ProductProvince: 44,
			ProductCity:     440300,
			CalculateType:   2,
			TransferType:    1, // 快递方式-1.快递 目前仅支持1
			RuleType:        1, // 模板类型-0:阶梯计价 1:固定运费 2:卖家包邮 3:货到付款
			FixedAmount:     500,
		},
		Columns: nil,
	}
	rule := []freightTemplate_create_request.ColumnsItem{
		{
			RuleAddress: "{\"44\":{\"440300\":{\"440306\":nil}}}",
			IsOverFree:  true,
			OverAmount:  5000,
			ProvinceInfos: []freightTemplate_create_request.ProvinceInfosItem{
				{
					Id: 44,
					Children: []freightTemplate_create_request.ChildrenItem_4{
						{
							Id: 440300,
							Children: []freightTemplate_create_request.ChildrenItem_5{
								{
									Id:       440306,
									Children: nil,
								},
							},
						},
					}},
			},
		},
	}
	if parmam != 0 {
		tempDetail.Template.TemplateName += "满减模板"
		tempDetail.Columns = rule // 满减
	} else {
		// 固定运费
		tempDetail.Template.TemplateName += "固定运费模板"
	}

	a.FreightTemplateCreate(tempDetail)
}

//创建电子围栏
func TestCreateFence(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)
	param := &warehouse_createFence_request.WarehouseCreateFenceParam{
		FenceInfo: &warehouse_createFence_request.FenceInfo{
			OutFenceId: "667094",
			Shape:      1,
			Circular: &warehouse_createFence_request.Circular{
				Center: &warehouse_createFence_request.Center{
					Longitude: 116.686026,
					Latitude:  39.884685,
				},
				Radius: 30000,
			},
		},
	}
	fenceID, err := a.CreateFence(param)
	fmt.Println(fenceID)
	fmt.Println(err)
}

//绑定电子围栏与门店
func TestBindFence(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)
	var ids = []string{"668469"}
	param := &warehouse_bindFencesByStore_request.WarehouseBindFencesByStoreParam{
		StoreId:        63114504,
		AddOutFenceIds: ids,
	}
	_, err := a.BindFenceByStore(param)
	fmt.Println(err)
}

func TestUpdateFence(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)
	param := &warehouse_setFence_request.WarehouseSetFenceParam{
		FenceInfo: &warehouse_setFence_request.FenceInfo{
			OutFenceId: "668469",
			Shape:      1,
			Circular: &warehouse_setFence_request.Circular{
				Center: &warehouse_setFence_request.Center{
					Longitude: 104.056976,
					Latitude:  30.755311,
				},
				Radius: 30000,
			},
		},
	}
	err := a.SetFence(param)
	fmt.Println(err)
}
func TestWarehouseBindFence(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)
	param := &warehouse_bindFences_request.WarehouseBindFencesParam{
		OutWarehouseId: "668510",
		OutFenceIds:    []string{"668410-2"},
	}
	err := a.WarehouseBindFence(param)
	fmt.Println(err)
}
func TestJNTM(t *testing.T) {
	fmt.Println(2 | 8)
}

func TestStoreSuspend(t *testing.T) {
	accesstoken := `{"access_token":"60f530b2-9ab6-4723-b487-c094918f0d21","expires_in":1666257163,"scope":"SCOPE","shop_id":"","shop_name":"小时达开放平台对接专用店","refresh_token":"1220666a-5e88-458c-a8c0-06d949fbbd3f","authority_id":""}`
	a := New("7136048270014416392", "c397aa9f-3927-47c4-8cfe-4d84e02602e0", accesstoken)
	param := &shop_storeSuspend_request.ShopStoreSuspendParam{
		StoreId: 65312663,
	}
	resp, err := a.StoreSuspend(param)
	fmt.Println(resp)
	fmt.Println(err)
}

func TestUnsuspendStore(t *testing.T) {
	accesstoken := `{"access_token":"60f530b2-9ab6-4723-b487-c094918f0d21","expires_in":1666257163,"scope":"SCOPE","shop_id":"","shop_name":"小时达开放平台对接专用店","refresh_token":"1220666a-5e88-458c-a8c0-06d949fbbd3f","authority_id":""}`
	a := New("7136048270014416392", "c397aa9f-3927-47c4-8cfe-4d84e02602e0", accesstoken)
	param := &shop_unsuspendStore_request.ShopUnsuspendStoreParam{
		StoreId: 65312663,
	}
	resp, err := a.UnsuspendStore(param)
	fmt.Println(resp)
	fmt.Println(err)
}

func TestUpdateStore(t *testing.T) {
	param := &shop_editStore_request.ShopEditStoreParam{
		StoreId:   65402632,
		StoreCode: "",
		Name:      "",
		Province:  "",
		City:      "",
		District:  "",
		Address:   "",
		Contact:   "",
		Longitude: "",
		Latitude:  "",
		OpenTime: &shop_editStore_request.OpenTime{DayMap: map[int64]string{
			1: "07:00-20:00", 2: "07:00-20:00", 3: "07:00-20:00", 4: "07:00-20:00", 5: "07:00-20:00", 6: "07:00-20:00", 7: "07:00-20:00",
		}},
	}
	err := a.EditStore(param)
	fmt.Println(err)
}

//获取门店绑定仓库
func TestGetWarehouseByStore(t *testing.T) {
	resp, err := a.GetWarehouseByStore(64270382)
	fmt.Println(resp.WarehouseInfoMap["64270382"][0].OutFenceIds[0])
	fmt.Println(err)
}

func TestUtilsTime2Date(t *testing.T) {
	fmt.Println(utils.Time2Date(time.Now()).Add(24 * time.Hour))
	fmt.Println(time.Now().Day())
}

//设置门店打包费
func TestSetStorePackageFee(t *testing.T) {
	err := a.SetStorePackageFee(62490423, 5) //单位 分
	fmt.Println(err)
}

//限售模板
//创建起送价限售模板
func TestCreateMinPriceTemplate(t *testing.T) {
	param := &trade_createTradeLimitTemplate_request.TradeCreateTradeLimitTemplateParam{
		StoreId: 62490423,
		TradeLimitRuleRequestList: []trade_createTradeLimitTemplate_request.TradeLimitRuleRequestListItem{
			{
				TradeLimitModel: 4,
				TradeLimitPattern: &trade_createTradeLimitTemplate_request.TradeLimitPattern{
					Minimum: 10,
				},
				TradeLimitSubjectList: []int32{1, 2, 3, 4, 5, 6, 7},
			},
		},
	}
	templateID, err := a.CreateTradeLimitTemplate(param)
	fmt.Println(templateID)
	fmt.Println(err)
}

//门店绑定限售模板
func TestStoreBindSaleTemplate(t *testing.T) {
	param := &shop_bindStoreSaleLimit_request.ShopBindStoreSaleLimitParam{
		StoreId:     62490423,
		SaleLimitId: 7161729424591700237,
	}
	err := a.BindStoreSaleLimit(param)
	fmt.Println(err)
}

//获取门店限售模板
func TestGetStoreSaleLimit(t *testing.T) {
	SaleLimitID, err := a.StoreQuerySaleLimitTemp(62490423)
	fmt.Println(SaleLimitID)
	fmt.Println(err)
}

//电子围栏
//创建电子围栏

//更新电子围栏
func TestSplitFence(t *testing.T) {
	tempStr := strings.Split("119.264545,26.059759;119.267963,26.055704;119.270453,26.056799;119.272496,26.054101;119.283454,26.049432;119.292113,26.043478;119.302748,26.04082;119.312766,26.046162;119.315166,26.042427;119.319187,26.029725;119.317819,26.016577;119.311271,26.004756;119.301256,25.996395;119.29311,25.999295;119.288793,25.991763;119.282818,25.996189;119.28234,25.998187;119.281131,25.997151;119.282488,25.99604;119.276974,25.99953;119.273954,25.99893;119.272637,26.001784;119.26865,26.003418;119.26928,25.999592;119.251217,26.018658;119.239497,26.024498;119.240308,26.034097;119.246036,26.046258;119.25243,26.052965;119.264545,26.059759;", ";")
	str := []string{}
	for _, v := range tempStr {
		str = append(str, v)
	}
	fmt.Printf("str======%s\n", str)
	fmt.Printf("len(str)======%d\n", len(str))
	for v := len(tempStr) - 1; v > 0; v-- {
		s2 := strings.Split(tempStr[v], ",")
		Longitude, _ := strconv.ParseFloat(s2[0], 64)
		Latitude := utils.Str2Float64(s2[1])
		fmt.Printf("Longitude=============%f,Latitude================%f\n", Longitude, Latitude)
		//fmt.Println("Longitude type:", reflect.TypeOf(Longitude))
		//fmt.Println("Latitude type:", reflect.TypeOf(Latitude))
	}
}
func TestGetAns(t *testing.T) {
	rand.Seed(time.Now().Unix())
	fmt.Println((rand.Intn(999-8) + 8) % 8)
}

//运费模板
//创建运费模板
//func TestCreateFreightTemplate(t *testing.T) {
//	param := &freightTemplate_create_request.FreightTemplateCreateParam{
//		Template: &freightTemplate_create_request.Template{
//			TemplateName:    "这是一个测试固定运费模板",
//			ProductProvince: utils.Str2Int64(utils.Int2Str(storeDetail.ProvinceCode)[:2]),
//			ProductCity:     int64(storeDetail.CityCode),
//			CalculateType:   2, //计价方式-1.按重量 2.按数量
//			TransferType:    1,
//			RuleType:        1,   //固定运费&卖家包邮
//			FixedAmount:     500, //固定运费 单位：分
//		},
//	}
//}

//更新运费模板
func TestUpdateFreightTemplate(t *testing.T) {
	param := &freightTemplate_update_request.FreightTemplateUpdateParam{
		Template: &freightTemplate_update_request.Template{
			Id:              11332268,
			TemplateName:    "京西菜市(盐田一店)_668619的运费模板",
			ProductProvince: 44,
			ProductCity:     440300,
			CalculateType:   2, //计价方式-1.按重量 2.按数量
			TransferType:    1,
			RuleType:        1,   //固定运费
			FixedAmount:     500, //固定运费 单位：分
		},
		Columns: []freightTemplate_update_request.ColumnsItem{{
			//RuleAddress: "{\"440000\":{\"440300\":{\"440306\":[0]}}}",
			IsOverFree: true, //是否包邮
			IsDefault:  0,
			IsLimited:  false,
			OverAmount: 9900, //此字段在vendor_id=14时 存储满x包邮金额
		}},
	}
	templateID, err := a.FreightTemplateUpdate(param)
	fmt.Println(templateID)
	fmt.Println(err)
}

//获取门店运费模板
func TestGetStoreBindFreight(t *testing.T) {
	var token = `{"access_token":"d590b649-0dd9-4988-a5e2-bf7e06e2f105","expires_in":1667808519,"scope":"SCOPE","shop_id":57939570,"shop_name":"京西菜市速食","refresh_token":"f57c6a55-af5f-45ca-8ade-b2282be86341","authority_id":""}`
	var a2 = New("7136048270014416392", "c397aa9f-3927-47c4-8cfe-4d84e02602e0", token)
	resp, err := a2.GetStoreFreight(64251634)
	fmt.Println(resp)
	fmt.Println(err)
}

//仓库
//创建单个仓库
func TestCreateWarehouse(t *testing.T) {
	warehouseID, err := a.CreateWarehouse(&warehouse_create_request.WarehouseCreateParam{
		OutWarehouseId: "test1108",
		Intro:          "这是一个测试区域仓",
		Warehouse: &warehouse_create_request.Warehouse{
			AddressDetail: "这是一个测试仓库地址",
			WarehouseLocation: &warehouse_create_request.WarehouseLocation{
				AddressId1: 35,
				AddressId2: 350100,
				AddressId3: 350104,
				AddressId4: 0,
			},
		},
	})
	fmt.Println(warehouseID)
	fmt.Println(err)
}

// 批量创建区域仓
func TestBatchCreateWarehouse(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)

	data, err := a.BatchCreateWarehouse(&warehouse_createBatch_request.WarehouseCreateBatchParam{
		OutWarehouseList: []warehouse_createBatch_request.OutWarehouseListItem{
			{
				OutWarehouseId: "666668",
				Name:           "V派区域仓",
				Intro:          "VV派区域仓,仓库id为京西门店id",
				AddressDetail:  "四川省成都市金牛区万科加州湾V派",
				WarehouseLocation: &warehouse_createBatch_request.WarehouseLocation{
					AddressId1: 51,
					AddressId2: 510100,
					AddressId3: 510106,
					AddressId4: 0,
				},
			},
		}})
	fmt.Println(data)
	fmt.Println(err)
}

// 仓库绑定门店
func TestBindWarehouseToStore(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)

	data, err := a.StoreBindWarehouse(&warehouse_bindStore_request.WarehouseBindStoreParam{
		StoreIds:       []int64{65312663},
		OutWarehouseId: "668510",
	})
	fmt.Println(data)
	fmt.Println(err)
}

// 仓库解绑门店
func TestUnBind(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.WarehouseUnbindStore([]int64{63114504}, "666667")
}
func TestTime(t *testing.T) {
	fmt.Println(BatchStr2Time("2022-10-31", "2022-11-06"))
}
func BatchStr2Time(strTime ...string) (timeList []time.Time, err error) {
	timeList = make([]time.Time, len(strTime))
	for k, v := range strTime {
		if v == "" {
			timeList[k] = utils.DefaultTimeValue
		} else {
			if timeList[k], err = utils.TryStr2Time(v); err != nil {
				return nil, err
			}
		}
	}
	return timeList, nil
}
func TestPrint(t *testing.T) {
	globals.SugarLogger.Debugf("%d", []int{1, 2, 3, 46, 65})
}

type RelInfo struct {
	StoreID       string `json:"storeID"`
	VendorStoreID string `json:"vendorStoreID"`
}

func TestToMap(t *testing.T) {
	//data := `{"16218203":[{"storeID":"7346348","vendorStoreID":"67"}]}`
	//payload := make(map[string][]RelInfo)
	//err := UnmarshalUseNumber([]byte(data), &payload)
	//fmt.Println(payload)
	//fmt.Println(err)

	ans := strings.Contains(fmt.Sprint("创建电子围栏失败:该电子围栏已经存在，请使用修改接口"), fmt.Sprint("已经存在，请使用修改接口"))
	fmt.Println(ans)
}

func UnmarshalUseNumber(data []byte, result interface{}) error {
	err := TryUnmarshalUseNumber(data, result)
	if err != nil {
		globals.SugarLogger.Infof("decode data:%v, error:%v", string(data), err)
	}
	return err
}

func TryUnmarshalUseNumber(data []byte, result interface{}) error {
	d := json.NewDecoder(bytes.NewReader(data))
	d.UseNumber()
	return d.Decode(result)
}
