package ebaiapi

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/jx-callback/globals"
	"io/ioutil"
	"net/http"
	"strings"
	"testing"
	"time"

	"git.rosy.net.cn/baseapi/utils"
)

func TestCancelOrder(t *testing.T) {

}

func TestOrderGet(t *testing.T) {
	result, err := api.OrderGet("4013706166788204275")
	orderMap := result["order"].(map[string]interface{})
	sendFeeDetail := orderMap["send_fee_detail"].(map[string]interface{})["one_on_one_delivery_fee"]
	fmt.Println(orderMap)
	fmt.Println(sendFeeDetail)
	products := result["products"].([]interface{})[0].([]interface{})
	for _, product2 := range products {
		product := product2.(map[string]interface{})
		SkuID := int(utils.Str2Int64WithDefault(utils.Interface2String(product[KeyCustomSkuID]), 0))
		if SkuID == 0 {
			if product["upc"] != nil {
				fmt.Println(strings.Split(product["upc"].(string), "-"))
				SkuID = utils.Str2Int(strings.Split(product["upc"].(string), "-")[1])
			} else if product["baidu_product_id"] != nil {
				globals.SugarLogger.Debugf("-----baidu_product_id := %s", product["baidu_product_id"].(string))
			}
		}
	}
	if err != nil {
		t.Fatal(err)
	} else {
		t.Log(utils.Format4Output(result, false))
	}
}

func TestOrderAgreePartRefund(t *testing.T) {
	param := &RefundOrderExamine{
		ReverseOrderId: "",
		OrderId:        "4033500150064003740",
		IdempotentId:   utils.Int64ToStr(time.Now().UnixNano()),
		ActionType:     RefundTypeRefuse,
		ReasonCode:     "7001",
		ReasonRemarks:  "1111",
	}
	refundProductList := make([]*RefundProductList, 0, 0)
	date, _, _ := api.GetReverseOrder("4033500150064003740")
	for _, v := range date {
		v2 := v.(map[string]interface{})
		refundProduct := &RefundProductList{
			SubBizOrderId: v2["sub_biz_order_id"].(string),
			PlatformSkuId: utils.Int64ToStr(utils.Interface2Int64WithDefault(v2["platform_sku_id"], 0)),
		}
		param.ReverseOrderId = utils.Int64ToStr(utils.MustInterface2Int64(v2["refund_order_id"]))
		switch utils.MustInterface2Int64(v2["fund_calculate_type"]) {
		case 0:
			refundProduct.Number = utils.Int64ToStr(utils.MustInterface2Int64(v2["refund_quantity"]))
		case 1:
			refundProduct.RefundAmount = utils.Int64ToStr(utils.MustInterface2Int64(v2["refund_user_amount"]))
		}
		refundProductList = append(refundProductList, refundProduct)
	}
	param.RefundProductList = refundProductList

	err := api.OrderDisagreeReturnGoods(param)
	globals.SugarLogger.Debugf("err := %s", utils.Format4Output(err, false))
}

func TestOrderAgreeRefund(t *testing.T) {
	err := api.OrderAgreeRefund(&RefundOrderExamine{
		ReverseOrderId: "2308279044977730245",
		OrderId:        "4002450124418844395",
		IdempotentId:   utils.Int64ToStr(time.Now().UnixNano()),
		ActionType:     "1",
		ReasonRemarks:  "",
	})
	fmt.Println(err)
}

func Test11111(t *testing.T) {
	fmt.Println(strings.Contains("[隐私保护]顾客地址已隐藏，您可登录饿了么商家端或骑手端查看", "隐私保护"))
}

func TestGetReverseOrder(t *testing.T) {
	date, isAll, err := api.GetReverseOrder("4031960081244121804")
	fmt.Println(isAll)
	fmt.Println(err)
	refundSkuList := make([]*ReverseSkuList, 0, len(date))
	refundByte, _ := json.Marshal(date)

	if err = json.Unmarshal(refundByte, &refundSkuList); err != nil {
		fmt.Println(err)
		return
	}

	globals.SugarLogger.Debugf("refundSkuList := %s", utils.Format4Output(refundSkuList, false))
}
func TestOrderGet2(t *testing.T) {
	result, err := api.OrderGet2("601124101999169939")
	if err != nil {
		t.Fatal(err)
	} else {
		t.Log(utils.Format4Output(result, false))
	}
}

func TestOrderStatusGet(t *testing.T) {
	result, err := api.OrderStatusGet("1576493808229489038")
	if err != nil {
		t.Fatal(err)
	} else {
		t.Log(utils.Format4Output(result, false))
	}
}
func TestOrderList(t *testing.T) {
	result, err := api.OrderList("300104", 32267046052, utils.Str2Time("2022-08-22").Unix(), utils.Str2Time("2022-09-08").Unix(), 0, 1)
	if err != nil {
		t.Fatal(err)
	} else {
		t.Log(utils.Format4Output(result, false))
	}
}

func TestOrderListAll(t *testing.T) {
	result, err := api.OrderListAll("", 32267046052, utils.Str2Time("2022-09-01").Unix(), utils.Str2Time("2022-09-08").Unix(), 0)
	if err != nil {
		t.Fatal(err)
	} else {
		t.Log(utils.Format4Output(result, false))
	}
}

func TestOrderPartRefundGet(t *testing.T) {
	result, err := api.OrderPartRefundGet("4089040181400256193")
	fmt.Println(utils.MustInterface2Int64(result["merchant_income"]))
	if err != nil {
		t.Fatal(err)
	} else {
		fmt.Println(utils.Interface2String(result["order_id"]))
		fmt.Println(utils.MustInterface2Int64(result["remain_user_total_amount"]))
		fmt.Println(utils.MustInterface2Int64(result["merchant_income"]))
		if result["reverse_order_list"] != nil {
			refundDetail := result["reverse_order_list"].([]interface{})
			refundSkuList := refundDetail[len(refundDetail)-1].(map[string]interface{})["sub_reverse_order_list"].([]interface{})
			for _, refundInfo := range refundSkuList {
				xMap := refundInfo.(map[string]interface{})
				if utils.Interface2String(xMap["sku_name"]) != "包装费" { // 暂时跳出包装费
					globals.SugarLogger.Debugf("========map := %s", utils.Format4Output(xMap, false))
					fmt.Println(utils.Int64ToStr(utils.MustInterface2Int64(xMap["platform_sku_id"])))
					fmt.Println(int(utils.Str2Int64WithDefault(utils.Interface2String(xMap["custom_sku_id"]), 0)))
					fmt.Println(utils.Interface2String(xMap["sku_name"]))
					fmt.Println(utils.MustInterface2Int64(xMap["refund_user_amount"]))

					aa := utils.Interface2Int64WithDefault(xMap["discount_detail"].(map[string]interface{})["platform_discount_amount"], 0) + utils.Interface2Int64WithDefault(xMap["discount_detail"].(map[string]interface{})["agent_discount_amount"], 0) + utils.Interface2Int64WithDefault(xMap["discount_detail"].(map[string]interface{})["user_discount_amount"], 0)
					fmt.Println(aa)
				}
			}
		}
	}
}

// func TestOrderPartRefundGet2(t *testing.T) {
// 	result, err := api.OrderPartRefundGet2("1557459492221457830")
// 	if err != nil {
// 		t.Fatal(err)
// 	} else {
// 		t.Log(utils.Format4Output(result, false))image/upload
// 	}
// }

func TestOrderConfirm(t *testing.T) {
	err := api.OrderConfirm("4087880039095667221")
	if err != nil {
		t.Fatal(err)
	}
}

func TestOrderPickComplete(t *testing.T) {
	err := api.OrderPickComplete("4087880039095667221")
	if err != nil {
		t.Fatal(err)
	}
}

func TestOrderCallDelivery(t *testing.T) {
	err := api.OrderCallDelivery("1556617836226053651")
	if err != nil {
		t.Fatal(err)
	}
}

func TestOrderSwitchselfdelivery(t *testing.T) {
	err := api.OrderSwitchselfdelivery("1574550169196474502")
	if err != nil {
		t.Fatal(err)
	}
}

func TestOrderPrivateInfo(t *testing.T) {
	_, err := api.OrderPrivateInfo("1542178206811884")
	if err != nil {
		t.Fatal(err)
	}
	// t.Log(result)
}

func TestOrderDeliveryGet(t *testing.T) {
	result, err := api.OrderDeliveryGet("4040090353958939256")
	if err != nil {
		t.Fatal(err)
	}
	t.Log(result)
}

func TestSmartOrderIdConvert(t *testing.T) {
	result, err := api.SmartOrderIdConvert("3035779376398878822")
	if err != nil {
		t.Fatal(err)
	}
	t.Log(result)
}

func TestOrderPartRefund(t *testing.T) {
	err := api.OrderPartRefund("3035779376398878822", []*RefundSku{
		&RefundSku{
			CustomeSkuID: "",
			Number:       "1",
		},
	})
	if err != nil {
		t.Fatal(err)
	}
}

func TestOrderCancel(t *testing.T) {
	err := api.OrderCancel("2122788271803194389", CancelTypeCustom, "admin")
	if err != nil {
		t.Fatal(err)
	}
}

func TestOrderQueryAcceptancecode(t *testing.T) {
	err := api.OrderQueryAcceptancecode("5021871103848829132")
	if err != nil {
		t.Fatal(err)
	}
}

type Data1 struct {
	Data interface{} `json:"data"`
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
}

func TestGetMtData(t *testing.T) {
	url := "https://shangoue.meituan.com/reuse/sc/product/shangou/ucube/r/getProducts?yodaReady=h5&csecplatform=4&csecversion=2.4.0"
	pageNum := 1
	strList := make([]string, 0, 0)
	for {
		payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"pageNum\"\r\n\r\n" + utils.Int2Str(pageNum) +
			"\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"pageSize\"\r\n\r\n100" +
			"\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"templateId\"\r\n\r\n24" +
			"\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"wmPoiId\"\r\n\r\n20760911\r\n-----011000010111000001101001--\r\n\r\n")

		req, _ := http.NewRequest("POST", url, payload)

		req.Header.Add("Cookie", `uuid_update=true; _lxsdk_cuid=18a8c469cebc8-0d5443d9234ef1-26021051-240000-18a8c469cebc8; uuid=19f97d5039dc40979c40.1701152326.1.0.0; device_uuid=!303ca77f-1f5c-4db9-8beb-2140b78696e2; pushToken=01YLhAxagh8b3tlBORRhDbRt9URjGhSdCG84G5-PA1w0*; WEBDFPID=29z4yy3y961959z509u92w75626y558381x7618yx56979584y00uw64-2016762763564-1701402763564QQKUMAGfd79fef3d01d5e9aadc18ccd4d0c95073707; iuuid=6150CECD00F8926053D5784EE8E108EC3F622CECA73B5042408DE46AB37C3D80; _lxsdk=6150CECD00F8926053D5784EE8E108EC3F622CECA73B5042408DE46AB37C3D80; n=tel1808018; e_u_id_3299326472=cbee20e50a13edae555928828ac9a4e7; _ga=GA1.1.2133425411.1707118186; isNewCome=1; _ga_95GX0SH5GM=GS1.1.1730448478.2.1.1730448606.0.0.0; wm_order_channel=default; swim_line=default; utm_source=; _lx_utm=utm_source%3DBaidu%26utm_medium%3Dorganic; au_trace_key_net=default; openh5_uuid=6150CECD00F8926053D5784EE8E108EC3F622CECA73B5042408DE46AB37C3D80; isIframe=false; mtcdn=K; userTicket=NWQspZZHEKhavgSsahmXAhrPIfKMJTzafKhWifyg; wpush_server_url=wss://wpush.meituan.com; acctId=183320634; token=0E7ksb36K1-IyWKIQaE5W_qqFdFOr1Jg54jD4aoKkDDU*; brandId=-1; isOfflineSelfOpen=0; city_id=0; isChain=1; existBrandPoi=true; ignore_set_router_proxy=true; region_id=; region_version=0; newCategory=true; bsid=eo5EYZF6ACWlfHJinMd5V2SY6oIXbfytL5DlOUctgPAiRRgON_rJ3meItgRw12c5-hqVkUy1D-qB3JQdgrTfUg; grayPath=newRoot; cityId=510100; provinceId=510000; city_location_id=0; location_id=0; gatherPoi=; cacheTimeMark=2024-11-07; _gw_ab_call_29855_7=TRUE; _gw_ab_29855_7=80; igateApp=shangouepc; timeout=2000; pharmacistAccount=0; accessToken=eo5EYZF6ACWlfHJinMd5V2SY6oIXbfytL5DlOUctgPAiRRgON_rJ3meItgRw12c5-hqVkUy1D-qB3JQdgrTfUg; _gw_ab_call_31449_50=TRUE; _gw_ab_31449_50=866; wmPoiId=20760911; wmPoiName=%E6%99%A8%E5%85%89%E6%96%87%E5%85%B7%EF%BC%88%E4%B9%9D%E6%B1%9F%E5%BA%97%EF%BC%89; shopCategory=market; signToken="xbmL6cP7LyPPTl8Sl+TJBLOGZTvv8Akw9MtDIah2IA4+bpGQVQb1cPNwdRP7/W6mRsEhGuB4YNlvG+4rN1ykMtt9xTbNd1YCkZTjV6tUeBk1XbLLsNJ652VgtwYe8bWgWg3L2J/UYfYCl3ZT9tu1nw=="; logistics_support=1; set_info=%7B%22wmPoiId%22%3A20760911%2C%22ignoreSetRouterProxy%22%3Atrue%7D; logan_session_token=kje3jttthj5mbubh9geg; _lxsdk_s=1930484d165-c2d-357-ea3%7C%7C165`)
		req.Header.Add("mtgsig", `{"a1":"1.1","a2":1730948559156,"a3":"29z4yy3y961959z509u92w75626y558381x7618yx56979584y00uw64","a5":"Ef9M2utMucRATMZ1exYWZT/HTU+wmBOk","a6":"h1.56rrQch2k10ZGgB+uJXlxBvZNZl6ZLsE1GUIEXsRA1c8cGiuKlv/K4DPdwGXXFCQR2y6/lpotSTuTmsw9gJa9lqle27OAS7ImcdsJY63ssbUyaVULRu7CRfFv9EvjYTi+iUr9QqDiWDIZ2XYLmLtJw7bCF1qP1AJ3pPq8vDQw8yM0L11UDIU4MZKo599omSYZRacgXRiOvm4wuRaJCL3SRUNYr32o8H+7xzOiQb8ztbfFNk9klmFBwurBGUo0jwmHY2ECH+hQEeqYR/K3Eer81do7lDh/wE7FdmNmiNHm9tY6LtTYi52GU/DwPNkDvM1RV/8JJH2BEeieMPjjhHmfIqlASJv7odfGt3BpjOUdXlrZ4YYBaZL5VUx3z6DDp1tWD+Ar1s1O4OF6tHdK4ra/Uw==","x0":4,"d1":"405ec0522582813313a7597365dc4166"}`)
		req.Header.Add("content-type", "multipart/form-data; boundary=---011000010111000001101001")

		res, _ := http.DefaultClient.Do(req)

		defer res.Body.Close()
		body, _ := ioutil.ReadAll(res.Body)
		SpData := &Data1{}
		if err := json.Unmarshal(body, SpData); err != nil {
			globals.SugarLogger.Debugf("-----err := %v", err)
		}

		for _, v := range SpData.Data.(map[string]interface{})["productGroups"].([]interface{}) {
			if v.(map[string]interface{})["productVo"] != nil {
				strSql := fmt.Sprintf("INSERT INTO sp_data VALUES(null,'%s','%s')", v.(map[string]interface{})["productVo"].(map[string]interface{})["name"], v.(map[string]interface{})["productVo"].(map[string]interface{})["upcCode"])
				strList = append(strList, strSql)
			}
		}
		if pageNum == 6 {
			break
		}
		pageNum += 1
	}

	fmt.Println("=====", len(strList))
	for k, i2 := range strList {
		fmt.Println(k-k, i2)
		time.Sleep(100 * time.Millisecond)
	}

}
