package tiktok_api

import (
	"encoding/json"
	"errors"
	"fmt"
	address_list_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/address_list/request"
	afterSale_applyMarketAfterSale_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/afterSale_ApplyMarketAfterSale/request"
	afterSale_Detail_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/afterSale_Detail/request"
	afterSale_Detail_response "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/afterSale_Detail/response"
	afterSale_List_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/afterSale_List/request"
	afterSale_List_response "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/afterSale_List/response"
	afterSale_buyerExchangeConfirm_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/afterSale_buyerExchangeConfirm/request"
	afterSale_operate_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/afterSale_operate/request"
	afterSale_rejectReasonCodeList_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/afterSale_rejectReasonCodeList/request"
	afterSale_rejectReasonCodeList_response "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/afterSale_rejectReasonCodeList/response"
	afterSale_returnGoodsToWareHouseSuccess_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/afterSale_returnGoodsToWareHouseSuccess/request"
	order_logisticsAdd_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/order_logisticsAdd/request"
	order_logisticsAddSinglePack_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/order_logisticsAddSinglePack/request"
	order_orderDetail_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/order_orderDetail/request"
	order_orderDetail_response "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/order_orderDetail/response"
	order_searchList_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/order_searchList/request"
	"git.rosy.net.cn/baseapi/utils"
	"math"
	"time"
)

// GetTiktokOrderDetail 获取订单详情
func (a *API) GetTiktokOrderDetail(orderId string) (*order_orderDetail_response.ShopOrderDetail, error) {
	reqParam := order_orderDetail_request.New()
	reqParam.Param = &order_orderDetail_request.OrderOrderDetailParam{
		ShopOrderId:  orderId,
		IsSearchable: false,
	}
	orderDetail, err := reqParam.Execute(a.accessTokenObj)
	if err != nil {
		return nil, err
	}
	if orderDetail.Code != RequestSuccessCode {
		return nil, errors.New(orderDetail.SubMsg + ":" + orderDetail.LogId)
	}

	return orderDetail.Data.ShopOrderDetail, nil
}

// QueryAfsOrderDetail 查询售后订单详情 needOperationRecord (是否需要协商记录默认不需要)
// https://op.jinritemai.com/docs/api-docs/17/1095 返回值说明
func (a *API) QueryAfsOrderDetail(afterSaleId string, needOperationRecord bool) (*afterSale_Detail_response.AfterSaleDetailResponse, error) {
	request := afterSale_Detail_request.New()
	param := request.GetParams()
	param.IsSearchable = needOperationRecord
	param.AfterSaleId = afterSaleId

	result, err := request.Execute(a.accessTokenObj)
	if err != nil {
		return nil, err
	}
	if result.Code != RequestSuccessCode {
		return nil, errors.New(result.SubMsg + ":" + result.LogId)
	}
	return result, nil
}

// QueryAfsOrderList 获取订单所有的售后详情
// https://op.jinritemai.com/docs/api-docs/17/1295
func (a *API) QueryAfsOrderList(vendorOrderId string) (*afterSale_List_response.AfterSaleListResponse, error) {
	request := afterSale_List_request.New()
	param := request.GetParams()
	param.OrderId = vendorOrderId
	param.Page = 1
	param.Size = 50
	param.StandardAftersaleStatus = []int64{12}

	result, err := request.Execute(a.accessTokenObj)
	if err != nil {
		return nil, err
	}
	if result.Code != RequestSuccessCode {
		return nil, errors.New(result.SubMsg + ":" + result.LogId)
	}
	return result, nil
}

// ApplyMarketAfterSale 拣货时商户发现订单缺货或者缺重
func (a *API) ApplyMarketAfterSale(skuOrderId, count int64, afterSaleReason int32) (afterSaleId string, err error) {
	request := afterSale_applyMarketAfterSale_request.New()
	param := request.GetParams()
	param.SkuOrderId = skuOrderId
	param.AfterSaleReason = afterSaleReason // 目前固定值为2缺货
	param.ItemCount = count                 // 拒收是必填

	result, err := request.Execute(a.accessTokenObj)
	if err != nil {
		return "", err
	}
	if result.Code != RequestSuccessCode {
		return "", errors.New(result.SubMsg + ":" + result.LogId)
	}
	return result.Data.AfterSaleId, nil
}

// AfterSaleOperate 售后审核接口聚合版
// 售后审核接口聚合版
// 售后统一操作接口，此接口可以提供所有售后操作类型。通过此接口操作时，需要通过type字段说明本次期望的操作（详情可见下表）。
// 此接口每次最多支持对20个售后单进行操作。但任意一个售后单操作失败，接口遍会整体报错，因此推荐使用此接口每次操作一个售后单，从而获得更加明确的报错信息。
// type说明:
// 值  前置条件-售后类型 前置条件-售后状态 	说明 				必须参数
// 101 0 				6,27 		同意退货申请（一次审核） 	Logistics.ReceiverAddressId 或 Logistics.AfterSaleAddressDetail
// 102 0 				6  		 	拒绝退货申请（一次审核） 	reason , evidence
// 111 0 				7,11,29  	同意退货（二次审核）
// 112 0 				11 			拒绝退货 (二次审核) 		reason , evidence
// 121 0 				6,27 		退货转退款
// 201 1 				6,27 		同意仅退款
// 202 1 				6 			拒绝仅退款 				reason , evidence
// 203 1 				6 			同意拒签后退款
// 301 3 				6,27 		同意换货申请（一次审核) 	Logistics.ReceiverAddressId 或 Logistics.AfterSaleAddressDetail
// 302 3 				6 			拒绝换货申请（一次审核） 	reason,evidence
// 311 3 				7,11,29 	同意换货（二次审核） 		logistics.companyCode,logistics.logisticsCode
// 312 3 				11 			拒绝换货（二次审核） 		reason,evidence
// 321 3 				6,7,11,29 	换货转退款
// 401 2 				6 			同意售前退申请(拒绝售前退款请使用发货接口)
// 501 7 				6,27 		同意补寄
// 502 7 				6 			拒绝补寄
func (a *API) AfterSaleOperate(refundType int32, refundId, remark string, storeId int64) error {
	//afsOrderDetail, err := a.QueryAfsOrderDetail(refundId, false)
	//if err != nil {
	//	return err
	//}
	//// 平台售后单状态
	//afterSaleType := afsOrderDetail.Data.ProcessInfo.AfterSaleInfo.AfterSaleType
	//afterSaleStatus := afsOrderDetail.Data.ProcessInfo.AfterSaleInfo.AfterSaleStatus
	//
	//switch afterSaleType {
	//case AfterSaleTypeAll: // 0
	//	afterSaleStatusMap := map[int64]int{AfterSaleStatusApply: 1, AfterSaleStatusRefuse: 1, AfterSaleStatusLoading: 1, AfterSaleStatusSendBag: 1, AfterSaleStatusRefuseBag: 1}
	//	if isAgree {
	//		if afterSaleStatusMap[afterSaleStatus] == 1 {
	//
	//		}
	//	} else {
	//
	//	}
	//case AfterSaleTypeSendPkgOnlyReturnMoney: // 1
	//case AfterSaleTypeReturnMoney: // 2
	//case AfterSaleTypeChangePkg: // 3
	//case AfterSaleTypeSystemCancel: // 4
	//case AfterSaleTypeUserCancel: // 5
	//case AfterSaleTypeInsuredPrice: // 6
	//case AfterSaleTypeReissue: // 7
	//case AfterSaleTypeService: // 8
	//default:
	//	return fmt.Errorf("暂不支持的售后类型,请联系开发")
	//}

	request := afterSale_operate_request.New()
	param := request.GetParams()
	param.Type = refundType

	refundListParam := make([]afterSale_operate_request.ItemsItem, 0, 0)
	switch refundType {
	// 101同意退货申请（一次审核） 				301 同意换货申请（一次审核) 	Logistics.ReceiverAddressId 或 Logistics.AfterSaleAddressDetail
	case AfterSaleEmuAgreeToReturnOneApply, AfterSaleEmuAgreeChangeGoodsOneApply: // 101 // 同意退货申请（一次审核） 	Logistics.ReceiverAddressId 或 Logistics.AfterSaleAddressDetail
		var paramList = afterSale_operate_request.ItemsItem{}
		addressId, _ := a.GetRefundAddressId(storeId)
		paramList.AftersaleId = refundId
		logistics := &afterSale_operate_request.Logistics{}
		logistics.ReceiverAddressId = addressId

		paramList.Logistics = logistics
		refundListParam = append(refundListParam, paramList)
		// 102拒绝退货申请（一次审核）     			112拒绝退货 							202拒绝仅退款	reason , evidence  302拒绝换货申请（一次审核） 					312换货转退款
	case AfterSaleEmuRefuseToReturnOneApply, AfterSaleEmuRefuseToReturnTwoApply, AfterSaleEmuRefuseOnlyRefundApply, AfterSaleEmuRefundChangeGoodsOneApply, AfterSaleEmuRefundChangeGoodsTwoApply:
		reasonItem, err := a.QueryAllReason(utils.Str2Int64(refundId))
		if err != nil {
			return err
		}
		evidence := afterSale_operate_request.EvidenceItem{}
		evidenceList := make([]afterSale_operate_request.EvidenceItem, 0, 1)
		if reasonItem[0].EvidenceNeed == "Y" {
			evidence = afterSale_operate_request.EvidenceItem{
				Type: 4,
				Url:  "",
				Desc: "拒绝退货/拒绝仅退款/拒绝换货申请,请电话联系商家",
			}
			evidenceList = append(evidenceList, evidence)
		}
		var paramList = afterSale_operate_request.ItemsItem{}
		paramList.AftersaleId = refundId
		paramList.Evidence = evidenceList
		paramList.RejectReasonCode = reasonItem[0].RejectReasonCode
		paramList.Reason = reasonItem[0].Reason
		paramList.Remark = remark
		refundListParam = append(refundListParam, paramList)
	// 111同意退货（二次审核）				121退货转退款							201同意仅退款							203同意拒签后退款						321换货转退款								401同意售前退申请					501同意补寄						502	拒绝补寄
	case AfterSaleEmuAgreeToReturnTwoApply, AfterSaleEmuReturnGoodsToRefundApply, AfterSaleEmuAgreeOnlyRefundApply, AfterSaleEmuRefundAfterRefusalApply, AfterSaleEmuChangeGoodsToRefundApply, AfterSaleEmuAgreePreSaleReturnApply, AfterSaleEmuAgreeReissueApply, AfterSaleEmuRefundReissueApply:
		var paramList = afterSale_operate_request.ItemsItem{}
		paramList.AftersaleId = refundId
		refundListParam = append(refundListParam, paramList)
	case AfterSaleEmuAgreeChangeGoodsTwoApply: //  	311 // 同意换货（二次审核） 		logistics.companyCode,logistics.logisticsCode
		// 不好处理,暂时不处理
		return nil
	}
	param.Items = refundListParam
	// 同意退货
	result, err := request.Execute(a.accessTokenObj)
	if err != nil {
		return err
	}
	if result.Code != RequestSuccessCode {
		return errors.New(result.SubMsg + ":" + result.LogId)
	}
	return nil
}

// GetRefundAddressId 获取抖店售后地址列表
func (a *API) GetRefundAddressId(storeID int64) (int64, error) {
	request := address_list_request.New()
	param := request.GetParams()
	param.PageSize = 10
	param.PageNo = 1
	param.OrderField = "create_time"
	param.OrderBy = "desc"
	param.StoreId = storeID

	result, err := request.Execute(a.accessTokenObj)
	if err != nil {
		return 0, err
	}
	if result.Code != RequestSuccessCode {
		return 0, errors.New(result.SubMsg + ":" + result.LogId)
	}
	if len(result.Data.AddressList) < 1 {
		return 0, errors.New("门店详细地址获取错误")
	}
	return result.Data.AddressList[0].AddressId, nil
}

// QueryAllReason 查询所有的售后审核处理原因详情
func (a *API) QueryAllReason(afterSaleId int64) ([]afterSale_rejectReasonCodeList_response.ItemsItem, error) {
	request := afterSale_rejectReasonCodeList_request.New()
	param := request.GetParams()
	if afterSaleId > 0 {
		param.AfterSaleId = afterSaleId
	}

	result, err := request.Execute(a.accessTokenObj)
	if err != nil {
		return nil, err
	}
	if result.Code != RequestSuccessCode {
		return nil, errors.New(result.SubMsg + ":" + result.LogId)
	}
	return result.Data.Items, nil
}

// GetStoreOrderList 获取门店订单列表
func (a *API) GetStoreOrderList(queryData time.Time, storeId int64) ([]string, error) {
	request := order_searchList_request.New()
	param := request.GetParams()

	createTime := time.Date(queryData.Year(), queryData.Month(), queryData.Day(), 0, 0, 0, 0, queryData.Location())
	endTime := time.Date(queryData.Year(), queryData.Month(), queryData.Day(), 23, 59, 59, 59, queryData.Location())
	param.CreateTimeStart = createTime.Unix()
	param.CreateTimeEnd = endTime.Unix()
	param.Page = 0
	param.Size = 100

	orderDetailList, err := request.Execute(a.accessTokenObj)
	if err != nil {
		return nil, err
	}
	if orderDetailList.Code != RequestSuccessCode {
		return nil, errors.New(orderDetailList.Msg + ":" + orderDetailList.LogId)
	}

	orderList := make([]string, 0, 0)
	for _, v := range orderDetailList.Data.ShopOrderList {
		if v.ShopId == storeId {
			orderList = append(orderList, v.OrderId)
		}
	}
	if orderDetailList.Data.Total < 100 {
		return orderList, nil
	}

	totalPage := 0
	if orderDetailList.Data.Total%100 != 0 {
		totalPage = int(math.Floor(utils.Int64ToFloat64(orderDetailList.Data.Total)/utils.Int64ToFloat64(100)) + 1)
	} else {
		totalPage = int(math.Floor(utils.Int64ToFloat64(orderDetailList.Data.Total) / utils.Int64ToFloat64(100)))
	}

	for i := 1; i < totalPage; i++ {
		createTime := time.Date(queryData.Year(), queryData.Month(), queryData.Day(), 0, 0, 0, 0, queryData.Location())
		endTime := time.Date(queryData.Year(), queryData.Month(), queryData.Day(), 23, 59, 59, 59, queryData.Location())
		param.CreateTimeStart = createTime.Unix()
		param.CreateTimeEnd = endTime.Unix()
		param.Page = int64(i)
		param.Size = 100

		orderDetailList, err := request.Execute(a.accessTokenObj)
		if err != nil {
			return nil, err
		}
		if orderDetailList.Code != RequestSuccessCode {
			return nil, errors.New(orderDetailList.Msg + ":" + orderDetailList.LogId)
		}
		for _, v := range orderDetailList.Data.ShopOrderList {
			if v.ShopId == storeId {
				orderList = append(orderList, v.OrderId)
			}
		}
	}
	return orderList, nil
}

// ReturnGoodsToWareHouseSuccess
//商家确认售后单对应的用户退货入仓成功
//商家在抖店后台售后小助手配置退货入仓自动退策略；
//当用户发起退货退款申请，商家同意且退货商品返回到商家仓内，由商家确认质检无误后入仓；
//命中策略后该售后单自动执行退款操作。
func (a *API) ReturnGoodsToWareHouseSuccess(afsOrderId string) error {
	request := afterSale_returnGoodsToWareHouseSuccess_request.New()
	param := request.GetParams()
	param.AftersaleId = afsOrderId
	param.OpTime = time.Now().Unix()

	result, err := request.Execute(a.accessTokenObj)
	if err != nil {
		return err // 202210141114300102101071350D6F3847
	}
	if result.Code != RequestSuccessCode {
		return errors.New(result.SubMsg + ":" + result.LogId)
	}
	return nil
}

// ConfirmReceivedReturnGoods 用户填写换货物流后，商家处理，确认是否收到换货，收货之后退款
func (a *API) ConfirmReceivedReturnGoods(afsOrderId int64, agree bool) {
	request := afterSale_buyerExchangeConfirm_request.New()
	param := request.GetParams()
	param.AfterSaleId = afsOrderId
	param.IsReject = agree
	if !agree {
		param.Action = "refund_agree" // 同意换货转退款
		param.LogisticsCode = ""
		param.CompanyCode = ""
	} else {
		param.Comment = "11"
	}
}

// OrderDelivering 订单发货
// 暂时只支持整单出库，即接口调用时入参只能传父订单号。
// Tips：部分发货状态下的父订单，调此接口发货，会报错：该订单当前为“部分发货”状态，无法调用此接口
// orderId主订单id,companyCode 物流公司code,isRefundReject 是否拒绝退款申请（true表示拒绝退款，并继续发货),addressId发货地址id
func (a *API) OrderDelivering(param *order_logisticsAdd_request.OrderLogisticsAddParam) error {
	request := order_logisticsAdd_request.New()
	request.Param = param

	result, err := request.Execute(a.accessTokenObj)
	if err != nil {
		return err
	}
	if result.Code == RequestSuccessRepeatedShipment {
		return nil
	}
	if result.Code != RequestSuccessCode {
		return errors.New("OrderDelivering err:" + param.OrderId + ":" + result.SubMsg + ":" + result.LogId)
	}
	return nil
}

// CreateOrderCallback 订单创建,抖店创建订单后,回调消息通知本服务器
func (a *API) CreateOrderCallback(orderStatus []byte) (map[string][]interface{}, *CallbackResponse) {
	var resp []*OrderCallback
	if err := json.Unmarshal(orderStatus, &resp); err != nil {
		fmt.Println(err)
		return nil, &CallbackResponse{Code: CallbackFailCode, Msg: CallbackFail}
	}

	callbackResult := make(map[string][]interface{}, 0)
	for _, data := range resp {
		switch data.Tag {
		case CallbackCreatedOrderMsgTagId: // 创建订单
			create := CreateOrderData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackCreatedOrderMsgTagId] = append(callbackResult[CallbackCreatedOrderMsgTagId], create)
		case CallbackPayOrderMsgTagId: // 支付订单
			create := PayOrderData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackPayOrderMsgTagId] = append(callbackResult[CallbackPayOrderMsgTagId], create)
		case CallbackWaitOrderMsgTagId: // 支付订单待处理(风控审核)
			create := WaitOrderData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackWaitOrderMsgTagId] = append(callbackResult[CallbackWaitOrderMsgTagId], create)
		case CallbackPartGoodsMsgTagId: // 卖家部分发货
			create := SomeSendOrderData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackPartGoodsMsgTagId] = append(callbackResult[CallbackPartGoodsMsgTagId], create)
		case CallbackPartAllGoodsMsgTagId: // 卖家发货
			create := BusinessDeliveryData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackPartAllGoodsMsgTagId] = append(callbackResult[CallbackPartAllGoodsMsgTagId], create)
		case CallbackCancelOrderMsgTagId: // 取消订单
			create := CreateOrderData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackCancelOrderMsgTagId] = append(callbackResult[CallbackCancelOrderMsgTagId], create)
		case CallbackSuccessOrderMsgTagId: //  卖家确认收货时,会自动完成
			create := SuccessOrderData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackSuccessOrderMsgTagId] = append(callbackResult[CallbackSuccessOrderMsgTagId], create)
		case CallbackWayBillChangeOrderMsgTagId: // 发货物流消息便跟
			create := WayBillChangeData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackWayBillChangeOrderMsgTagId] = append(callbackResult[CallbackWayBillChangeOrderMsgTagId], create)
		case CallbackReceivingChangeOrderMsgTagId: // 收货地址消息变更(商家审核通过触发)
			create := ReceivingAddressChangeData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackReceivingChangeOrderMsgTagId] = append(callbackResult[CallbackReceivingChangeOrderMsgTagId], create)
		case CallbackChangeMoneyMsgTagId: // 卖家修改订单/运单金额回调
			create := UpdateAmountChangeData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackChangeMoneyMsgTagId] = append(callbackResult[CallbackChangeMoneyMsgTagId], create)
		case CallbackBusinessRemarkMsgTagId: // 买家收货消息变更(手机,地址,姓名),用户C端修改触发(需要上面审核接口)
			create := BuyerUpdateWayBillData{}
			if err := json.Unmarshal([]byte(data.Data), create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackBusinessRemarkMsgTagId] = append(callbackResult[CallbackBusinessRemarkMsgTagId], create)
		case CallbackApplyUpdateAddressMsgTagId: // 商家修改交易备注回调
			create := BusinessUpdateRemakeData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackApplyUpdateAddressMsgTagId] = append(callbackResult[CallbackApplyUpdateAddressMsgTagId], create)
		case CallbackSendOrderTimeChangeMsgTagId: // 订单发货时消息变更回调
			create := AppointmentChangeData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackSendOrderTimeChangeMsgTagId] = append(callbackResult[CallbackSendOrderTimeChangeMsgTagId], create)
			/*********下面属于订单退货消息************/
		case CallbackRefundOrderMsgTagId: // 买家发起售后申请消息
			create := BuyerRefundCreatedData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackRefundOrderMsgTagId] = append(callbackResult[CallbackRefundOrderMsgTagId], create)
		case CallbackUpdateRefundOrderMsgTagId: // 买家修改售后申请消息
			create := BuyerRefundModifiedData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackUpdateRefundOrderMsgTagId] = append(callbackResult[CallbackUpdateRefundOrderMsgTagId], create)
		case CallbackRefundOrderSuccessMsgTagId: // 退款成功消息
			create := BusinessRefundSuccessData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackRefundOrderSuccessMsgTagId] = append(callbackResult[CallbackRefundOrderSuccessMsgTagId], create)
		case CallbackRefundOrderRefuseMsgTagId: // 拒绝退款消息
			create := BusinessNotRefundRefusedData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackRefundOrderRefuseMsgTagId] = append(callbackResult[CallbackRefundOrderRefuseMsgTagId], create)
		case CallbackRefundShopMsgTagId: // 拒绝退货申请消息
			create := BusinessNotReturnApplyRefusedData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackRefundShopMsgTagId] = append(callbackResult[CallbackRefundShopMsgTagId], create)
		case CallbackReturnApplyAgreedMsgTagId: // 卖家同意时，推送此消息
			create := BusinessReturnApplyAgreedData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackReturnApplyAgreedMsgTagId] = append(callbackResult[CallbackReturnApplyAgreedMsgTagId], create)
		case CallbackReturnRefundAgreedMsgTagId: // 同意退款消息
			create := BusinessRefundAgreedData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackReturnRefundAgreedMsgTagId] = append(callbackResult[CallbackReturnRefundAgreedMsgTagId], create)
		case CallbackRefundClosedMsgTagId:
			create := UserCancelRefundOrderData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackRefundClosedMsgTagId] = append(callbackResult[CallbackRefundClosedMsgTagId], create)
		case CallbackShipmentInfoChange: //运单状态回调
			create := ShipmentInfoData{}
			if err := json.Unmarshal([]byte(data.Data), &create); err != nil {
				return nil, CallbackResponseErr(false)
			}
			callbackResult[CallbackShipmentInfoChange] = append(callbackResult[CallbackShipmentInfoChange], create)
		default:
			return nil, CallbackResponseErr(false)
		}
	}

	return callbackResult, &CallbackResponse{Code: CallbackSuccessCode, Msg: CallbackSuccess}
}

// GetCallbackOrderId 获取回调函数订单id
func (a *API) GetCallbackOrderId(msgId string, data interface{}) (string, int64, *CallbackResponse) {
	switch msgId {
	case CallbackCreatedOrderMsgTagId: // 创建订单
		create := CreateOrderData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, Err2CallbackResponse(err, "")
		}
		return utils.Int64ToStr(create.PId), create.ShopId, Err2CallbackResponse(nil, "")
	case CallbackPayOrderMsgTagId: // 支付订单
		create := PayOrderData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), create.ShopId, Err2CallbackResponse(nil, "")
	case CallbackWaitOrderMsgTagId: // 支付订单待处理(风控审核)
		create := WaitOrderData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), create.ShopId, Err2CallbackResponse(nil, "")
	case CallbackPartGoodsMsgTagId: // 卖家部分发货
		create := SomeSendOrderData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), create.ShopId, Err2CallbackResponse(nil, "")
	case CallbackPartAllGoodsMsgTagId: // 卖家发货
		create := BusinessDeliveryData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), create.ShopId, Err2CallbackResponse(nil, "")
	case CallbackCancelOrderMsgTagId: // 取消订单
		create := CancelOrderData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), create.ShopId, Err2CallbackResponse(nil, "")
	case CallbackSuccessOrderMsgTagId: //  卖家确认收货时,会自动完成
		create := SuccessOrderData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), create.ShopId, Err2CallbackResponse(nil, "")
	case CallbackWayBillChangeOrderMsgTagId: // 发货物流消息便跟
		create := WayBillChangeData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), create.ShopId, Err2CallbackResponse(nil, "")
	case CallbackReceivingChangeOrderMsgTagId: // 收货地址消息变更(商家审核通过触发)
		create := ReceivingAddressChangeData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), create.ShopId, Err2CallbackResponse(nil, "")
	case CallbackChangeMoneyMsgTagId: // 卖家修改订单/运单金额回调
		create := UpdateAmountChangeData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), create.ShopId, Err2CallbackResponse(nil, "")
	case CallbackBusinessRemarkMsgTagId: // 买家收货消息变更(手机,地址,姓名),用户C端修改触发(需要上面审核接口)
		create := BuyerUpdateWayBillData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), create.ShopId, Err2CallbackResponse(nil, "")
	case CallbackApplyUpdateAddressMsgTagId: // 商家修改交易备注回调
		create := BusinessUpdateRemakeData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), create.ShopId, Err2CallbackResponse(nil, "")
	case CallbackSendOrderTimeChangeMsgTagId: // 订单发货时消息变更回调
		create := AppointmentChangeData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return create.PId, create.ShopId, Err2CallbackResponse(nil, "")
	/*********下面属于订单退货消息************/
	case CallbackRefundOrderMsgTagId: // 买家发起售后申请消息
		create := BuyerRefundCreatedData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), int64(create.ShopId), Err2CallbackResponse(nil, "")
	case CallbackUpdateRefundOrderMsgTagId: // 买家修改售后申请消息
		create := BuyerRefundModifiedData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), int64(create.ShopId), Err2CallbackResponse(nil, "")
	case CallbackRefundOrderSuccessMsgTagId: // 退款成功消息
		create := BusinessRefundSuccessData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), int64(create.ShopId), Err2CallbackResponse(nil, "")
	case CallbackRefundOrderRefuseMsgTagId: // 拒绝退款消息
		create := BusinessNotRefundRefusedData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), int64(create.ShopId), Err2CallbackResponse(nil, "")
	case CallbackRefundShopMsgTagId: // 拒绝退货申请消息
		create := BusinessNotReturnApplyRefusedData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), int64(create.ShopId), Err2CallbackResponse(nil, "")
	case CallbackReturnApplyAgreedMsgTagId: // 卖家同意时，推送此消息
		create := BusinessReturnApplyAgreedData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), int64(create.ShopId), Err2CallbackResponse(nil, "")
	case CallbackReturnRefundAgreedMsgTagId: // 同意退款消息
		create := BusinessRefundSuccessData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), create.ShopId, Err2CallbackResponse(nil, "")
	case CallbackRefundClosedMsgTagId: // 当买家取消申请或系统超时机制导致退款取消时，会推送此消息
		create := UserCancelRefundOrderData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		return utils.Int64ToStr(create.PId), int64(create.ShopId), Err2CallbackResponse(nil, "")
	case CallbackShipmentInfoChange: //商家从运力平台呼叫运力以后，推送运力状态变更消息
		create := ShipmentInfoData{}
		if err := utils.Map2StructByJson(data, &create, false); err != nil {
			return "", 0, CallbackResponseErr(false)
		}
		//返回   呼叫运力的订单号      抖音店铺ID
		return utils.Int64ToStr(create.ShopOrderID), create.ShopID, Err2CallbackResponse(nil, "")
	default:
		return "", 0, CallbackResponseErr(false)
	}
}

// LogisticsAddSinglePack 支持多个订单发同一个物流包裹
func (a *API) LogisticsAddSinglePack() {
	request := order_logisticsAddSinglePack_request.New()
	request.Param.OrderIdList = []string{"4989180160180927898"}
	request.Param.ShippedOrderInfo = []order_logisticsAddSinglePack_request.ShippedOrderInfoItem{
		{ShippedOrderId: "4989180160180927898", ShippedNum: 1},
	}
	request.Param.LogisticsCode = "4989180160180927898fake"
	request.Param.RequestId = "1267250f-8b9d-4d9e-9fad-0cd9629c83de"
	request.Param.CompanyCode = "dajiangwangluo"
	request.Param.StoreId = 63114504

	data, err := request.Execute(a.accessTokenObj)
	fmt.Println(data)
	fmt.Println(err)
}
