package tao_vegetable

import (
	"encoding/json"
	"errors"
	"fmt"
	domain3156 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability3156/domain"
	request3156 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability3156/request"
	domain591 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability591/domain"
	request591 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability591/request"
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/util"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/globals"
	"strconv"
	"testing"
	"time"
)

func TestName(t *testing.T) {
	fmt.Println(len("http://image.jxc4.com/c8e6b01cd8aa6528f40d0719084e238d.png"))
}
func TestGetOrderDetail(t *testing.T) {
	requestParam := &request591.AlibabaAelophyOrderGetRequest{OrderGetRequest: &domain591.AlibabaAelophyOrderGetOrderGetRequest{
		StoreId:    utils.String2Pointer("JX100236"),
		BizOrderId: utils.Int64ToPointer(8000245939558000686),
	}}

	data, err := apiTao.QueryOrderDetail(requestParam)
	var skuPrice int64 = 0       // 商品原价
	var skuMemberPrice int64 = 0 // 商户优惠价
	for _, v := range *data.SubOrderResponseList {
		skuPrice += *v.OriginalFee
		skuMemberPrice += *v.DiscountMerchantFee
	}
	var platformPrice = *data.PlatformDeduction.BaseLogisticsFee + *data.PlatformDeduction.TechnicalServiceFee + *data.PlatformDeduction.PayServiceFee + *data.PlatformDeduction.ThirdpartnarFee

	jieSuanPrice := skuPrice + *data.PostFee - skuMemberPrice - platformPrice

	fmt.Println(jieSuanPrice)
	globals.SugarLogger.Debugf("data := %s", utils.Format4Output(data, false))
	globals.SugarLogger.Debugf("err := %s", utils.Format4Output(err, false))
	globals.SugarLogger.Debugf("errdatadatadata := %s", utils.Format4Output(utils.Str2Int(*data.StoreId), false))
}

func TestPartialRefundReason(t *testing.T) {
	param := &request3156.AlibabaTclsAelophyRefundCsapplyrenderRequest{
		RefundCsApplyRenderDTO: &domain3156.AlibabaTclsAelophyRefundCsapplyrenderRefundCsApplyRenderDto{
			OutOrderId:     utils.String2Pointer("1930521002382804887"),
			StoreId:        utils.String2Pointer("JX668998"),
			OutSubOrderIds: &[]string{"1930521002384804887"},
			OrderFrom:      utils.Int64ToPointer(utils.Str2Int64(TaoVegetableChannelCode)),
		},
	}
	apiTao.PartialRefundReason(param)
}

func TestQueryAfsOrderDetail(t *testing.T) {
	param := &request591.AlibabaWdkOrderRefundGetRequest{
		OrderFrom: utils.Int64ToPointer(31),
		ShopId:    nil,
		StoreId:   utils.String2Pointer("JX100705"),
		RefundIds: &[]int64{1313780273},
	}
	data, err := apiTao.QueryAfsOrderDetail(param)
	globals.SugarLogger.Debugf("data := %s", utils.Format4Output(data, false))
	globals.SugarLogger.Debugf("err := %s", utils.Format4Output(err, false))

}

func Test222(t *testing.T) {
	fmt.Println((3 & 1) != 0)
}

// 接单
func TestDeliveryFinishACCEPTED(t *testing.T) {
	orderID := 8000253695335600623
	storeID := "JX666900"
	param := &request591.AlibabaAelophyOrderWorkCallbackRequest{}
	param.WorkCallbackRequest = &domain591.AlibabaAelophyOrderWorkCallbackWorkCallbackRequest{
		StoreId:      utils.String2Pointer(storeID),
		BizOrderId:   utils.Int64ToPointer(int64(orderID)),
		Status:       utils.String2Pointer(OrderStatusPickedUp),
		StatusRemark: nil,
		//DelivererName:                utils.String2Pointer("张廷"),
		//DelivererPhone:               utils.String2Pointer("SIGN"),
		WorkCallbackSubOrderInfoList: nil,
		DelivererCompany:             nil,
		LogisticsNo:                  nil,
	}

	workCallbackSubOrderInfoList := make([]domain591.AlibabaAelophyOrderWorkCallbackWorkCallbackSubOrderInfo, 0, 0)
	orderDetail, err := apiTao.QueryOrderDetail(&request591.AlibabaAelophyOrderGetRequest{OrderGetRequest: &domain591.AlibabaAelophyOrderGetOrderGetRequest{
		StoreId:    utils.String2Pointer(storeID),
		BizOrderId: utils.Int64ToPointer(utils.Str2Int64(utils.Int2Str(orderID))),
	}})
	if err != nil {
		return
	}
	for _, v := range *orderDetail.SubOrderResponseList {
		workCallbackSubOrderInfo := domain591.AlibabaAelophyOrderWorkCallbackWorkCallbackSubOrderInfo{
			BizSubOrderId:     v.BizSubOrderId,
			SkuCode:           v.SkuCode,
			PickSaleQuantity:  utils.String2Pointer(utils.Float64ToStr(*v.BuySaleQuantity)),
			PickStockQuantity: utils.String2Pointer(utils.Float64ToStr(*v.BuyStockQuantity)),
		}
		workCallbackSubOrderInfoList = append(workCallbackSubOrderInfoList, workCallbackSubOrderInfo)
	}
	param.WorkCallbackRequest.WorkCallbackSubOrderInfoList = &workCallbackSubOrderInfoList
	apiTao.SetToken("50000C00e13l3SYxqadamvelw15656b52A0xeXfaS8nyVCgitlzIq1nDwFzYdcQpIsVz")
	//apiTao.SetToken("50002C01524csKWniqfypk8dbshKRTeFIOIy1a46c0cfgsvodWjsseMsXqpvWvECMj1")
	err = apiTao.DeliveryFinish(param)
	fmt.Println(err)
}

// 取消订单
func TestDeliveryFinishREJECTED(t *testing.T) {
	// 发送取消状态,商户取消
	err := apiTao.DeliveryFinish(&request591.AlibabaAelophyOrderWorkCallbackRequest{
		WorkCallbackRequest: &domain591.AlibabaAelophyOrderWorkCallbackWorkCallbackRequest{
			StoreId:    utils.String2Pointer("JX668594"),
			BizOrderId: utils.Int64ToPointer(5000897098078620922),
			Status:     utils.String2Pointer("REJECTED"),
		},
	})

	fmt.Println(err)
}

func TestGetTransactionOrderList(t *testing.T) {
	queryData := time.Now().AddDate(0, 0, 0)
	create := time.Date(queryData.Year(), queryData.Month(), queryData.Day(), 0, 0, 0, 0, queryData.Location())
	end := time.Date(queryData.Year(), queryData.Month(), queryData.Day(), 23, 59, 59, 59, queryData.Location())
	createTime := util.LocalTime(create)
	endTime := util.LocalTime(end)
	var pageIndex int64 = 1
	var PageSize int64 = 20
	param := &request591.AlibabaWdkOrderListRequest{
		BatchQueryRequest: &domain591.AlibabaWdkOrderListBatchQueryRequest{
			StoreIds:  &[]string{"JX102751"},
			StartTime: &createTime,
			EndTime:   &endTime,
			OrderFrom: utils.Int64ToPointer(ChannelCome),
			ShopId:    nil,
			StoreId:   utils.String2Pointer("JX102751"),
			BizType:   nil,
		},
	}
	param.BatchQueryRequest.SetPageSize(PageSize)
	param.BatchQueryRequest.SetPageIndex(pageIndex)

	data, err := apiTao.GetTransactionOrderList(param)
	if err != nil {
		globals.SugarLogger.Debugf("err := %s", utils.Format4Output(err, false))
		return
	}
	globals.SugarLogger.Debugf("data := %s", utils.Format4Output(data, false))

	// 取消订单
	//for _, v := range *data.Orders {
	//	err := apiTao.DeliveryFinish(&request591.AlibabaAelophyOrderWorkCallbackRequest{
	//		WorkCallbackRequest: &domain591.AlibabaAelophyOrderWorkCallbackWorkCallbackRequest{
	//			StoreId:    utils.String2Pointer("JX668594"),
	//			BizOrderId: utils.Int64ToPointer(*v.BizOrderId),
	//			Status:     utils.String2Pointer("REJECTED"),
	//		},
	//	})
	//	if err != nil {
	//		fmt.Println(err)
	//	}
	//}
}

func TestPickUp(t *testing.T) {
	param := &request591.AlibabaAelophyOrderWorkCallbackRequest{}
	param.WorkCallbackRequest = &domain591.AlibabaAelophyOrderWorkCallbackWorkCallbackRequest{
		StoreId:    utils.String2Pointer("JX666844"),
		BizOrderId: utils.Int64ToPointer(5000921376234590432),
		Status:     utils.String2Pointer(OrderStatusDeliveryOver),
	}

	workCallbackSubOrderInfoList := make([]domain591.AlibabaAelophyOrderWorkCallbackWorkCallbackSubOrderInfo, 0, 0)
	workCallbackSubOrderInfo := domain591.AlibabaAelophyOrderWorkCallbackWorkCallbackSubOrderInfo{
		BizSubOrderId:     utils.Int64ToPointer(5000921376234590432),
		SkuCode:           utils.String2Pointer("22832"),
		PickSaleQuantity:  utils.String2Pointer("1"),
		PickStockQuantity: utils.String2Pointer("1"),
	}
	workCallbackSubOrderInfoList = append(workCallbackSubOrderInfoList, workCallbackSubOrderInfo)

	// 出库
	param.WorkCallbackRequest.WorkCallbackSubOrderInfoList = &workCallbackSubOrderInfoList

	err := apiTao.DeliveryFinish(param)
	fmt.Println(err)
}

func TestString(t *testing.T) {
	skuSt := `{\"income\":\"1\",\"sub_discount_merchant_item_fee\":\"0\",\"afterRefund\":\"false\",\"reverseCaseId\":\"1000010862920670044\",\"discount\":\"[]\",\"sub_refund_item_fee\":\"1800\",\"scenarioGroup\":\"TB\",\"saleUnit\":\"份\",\"refundPostFee\":\"0\",\"refundPlatformFee\":\"0\",\"skuName\":\"西兰花 500g/份\",\"wdkrfqr\":\"{\\\"operatorType\\\":1,\\\"operatorId\\\":3460808748,\\\"operatorName\\\":\\\"BUYER\\\"}\",\"skuBrandSubsidyFee\":\"0\",\"refundSaleQuantity\":\"3\",\"wdkrc\":\"{\\\"operatorType\\\":2,\\\"operatorId\\\":\\\"SYSTEM\\\",\\\"operatorName\\\":\\\"系统\\\"}\",\"price\":\"900\",\"orderClient\":\"2\",\"wdkdfqrrr\":\"补差退款\",\"refundTotalSubCount\":\"1\",\"discount_merchant_fee\":\"0\",\"skuMerchantOfflineSubsidyFee\":\"0\",\"barcode\":\"19930827\",\"refundExpectRefundQuantity\":\"0.0\",\"wdkRefundSource\":\"3\",\"tbBizOrderId\":\"1930802089555804887\",\"wdkrfqrmemo\":\"系统代发起补差退款\",\"gmtDisputeEndTime\":\"2023-07-10 15:53:07\",\"sub_discount_platform_brand_item_fee\":\"0\",\"discount_platform_fee\":\"0\",\"stockUnit\":\"份\",\"tbBizParentId\":\"1930802089553804887\",\"sub_refund_fee\":\"1800\",\"sub_discount_platform_channel_item_fee\":\"0\",\"sub_discount_platform_agent_item_fee\":\"0\",\"weightItem\":\"0\",\"sub_discount_platform_item_fee\":\"0\",\"skuMerchantOnlineSubsidyFee\":\"0\"}`
	str2, err := strconv.Unquote("\"" + skuSt + "\"")
	fmt.Println("err111", err)
	data := &GoodsScarceRefund{}
	if err := json.Unmarshal([]byte(str2), &data); err != nil {
		fmt.Println("err = ", err)
		return
	}
	fmt.Println("data = ", data)
	//a2 := strings.Index(skuSt, "skuName")
	//a3 := strings.Index(skuSt, "wdkrfqr")
	//skuName := skuSt[a2+12 : a3-5]
	//fmt.Println(skuName)
}

// 骑手变更
func TestDelivererChange(t *testing.T) {
	param := &request591.AlibabaAelophyOrderDelivererChangeRequest{
		DelivererChangeRequest: &domain591.AlibabaAelophyOrderDelivererChangeDelivererChangeRequest{
			StoreId:          utils.String2Pointer("JX668594"),
			BizOrderId:       utils.Int64ToPointer(5000900610990770922),
			DelivererName:    utils.String2Pointer("张廷"),
			DelivererPhone:   utils.String2Pointer("13302290396"),
			DelivererCompany: utils.String2Pointer(TaoDeliveryTypeSELF),
			LogisticsNo:      utils.String2Pointer("1504611792359260160"),
		},
	}
	apiTao.DelivererChange(param)
}

// 骑手坐标
func TestDeliveryTrajectory(t *testing.T) {
	param := &request591.AlibabaAelophyOrderLogisticsTraceCallbackRequest{
		LogisticsTraceCallbackRequest: &domain591.AlibabaAelophyOrderLogisticsTraceCallbackLogisticsTraceCallbackRequest{
			StoreId:    utils.String2Pointer("JX668594"),
			BizOrderId: utils.Int64ToPointer(5000900574962430922),
			Longitude:  utils.String2Pointer("104045460"),
			Latitude:   utils.String2Pointer("30693001"),
			UpdateTime: (*util.LocalTime)(utils.Time2Pointer(time.Now())),
		},
	}
	apiTao.DeliveryTrajectory(param)
}

func TestQueryBillList(t *testing.T) {
	queryData := time.Now()
	create := time.Date(queryData.Year(), queryData.Month(), queryData.Day()-17, 0, 0, 0, 0, queryData.Location())
	end := time.Date(queryData.Year(), queryData.Month(), queryData.Day()-15, 23, 59, 59, 59, queryData.Location())

	data, err := GetOrderTotalShopMoney("", "JX668429", create, end)

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

// GetOrderTotalShopMoney 获取门店结算信息
func GetOrderTotalShopMoney(appOrgCode string, vendorStoreID string, start, end time.Time) (map[string]string, error) {
	if start.IsZero() || end.IsZero() {
		return nil, errors.New("开始时间和结束时间不能为空")
	}

	settlement := make(map[string]string, 0)

	api := apiTao
	startBillDate := util.LocalTime(start)
	endBillDate := util.LocalTime(end)
	pageSize := 200
	pageIndex := 1

	param := &request591.AlibabaWdkBillListRequest{
		TxdBillListGetRequest: &domain591.AlibabaWdkBillListTxdBillListGetRequest{
			EndBillDate:   &endBillDate,
			StartBillDate: &startBillDate,
			ShopCode:      utils.String2Pointer(vendorStoreID),
			PageSize:      utils.Int64ToPointer(int64(pageSize)),
			PageIndex:     utils.Int64ToPointer(int64(pageIndex)),
		},
	}

	var totalIndex int64 = 0
	result, err := api.QueryBillList(param)
	if err != nil {
		return nil, err
	}
	for _, v := range *result.TxdBillDetailBOS {
		if *v.OrderType == "positive" {
			settlement[*v.BizOrderId] = *v.ReceivableAmount
		}
	}

	if *result.Total > int64(pageSize) {
		totalIndex = *result.Total / int64(pageSize)
		if *result.Total%int64(pageSize) != model.NO {
			totalIndex += 1
		}

		for i := 2; i <= int(totalIndex); i++ {
			param.TxdBillListGetRequest.PageIndex = utils.Int64ToPointer(int64(i))
			result2, _ := api.QueryBillList(param)
			for _, v := range *result2.TxdBillDetailBOS {
				if *v.OrderType == "positive" {
					settlement[*v.BizOrderId] = *v.ReceivableAmount
				}
			}
		}
	}

	return settlement, nil
}
