package ebaiapi

import (
	"fmt"
	"git.rosy.net.cn/jx-callback/globals"
	"time"

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

const (
	CancelTypeNotInServiceArea    = "1"
	CancelTypeShopClosed          = "2"
	CancelTypeSoldOut             = "3"
	CancelTypePriceChanged        = "4"
	CancelTypeClientCanceled      = "5"
	CancelTypeDuplicatedOrder     = "6"
	CancelTypeTooBusy             = "7"
	CancelTypeCanNotContactClient = "8"
	CancelTypeFakeOrder           = "9"
	CancelTypePushOrderFailed     = "53"
	CancelTypeCustom              = "-1"
)

const (
	OrderStatusNew             = "1"
	OrderStatusAccepted        = "5"  // 订单确认
	OrderStatusCourierAccepted = "7"  // 骑士已接单开始取餐（此时可通过订单详情接口获取骑士手机号)
	OrderStatusCourierPickedup = "8"  // 骑士已取餐正在配送
	OrderStatusFinished        = "9"  // 订单完成
	OrderStatusCanceled        = "10" // 订单取消
	OrderStatusRefund          = "15" // 订单退款，这个是售后之后的事件，不应该当成正常订单事件处理
)

const (
	RefundTypeAgree       = "1" // 同意全单/部分退款申请
	RefundTypeRefuse      = "2" // 拒绝全单/部分退款申请
	RefundTypeAgreeGoods  = "3" // 同意退货申请
	RefundTypeRefuseGoods = "4" // 拒绝退货申请
)

const (
	WaybillStatusEvent           = "1" // 一般事件
	WaybillStatusNew             = "2" // 生成运单
	WaybillStatusRequestDelivery = "3" // 请求配送
	WaybillStatusWait4Courier    = "4" // 等待分配骑士
	WaybillStatusCourierAccepted = "7" // 骑士接单
	WaybillStatusCourierPickedup = "8" // 骑士取餐
	// 饿百在发送运单取消事件后，如果订单没有及时（具体时间未知）转出自送，则订单会被取消，且不会发送订单取消事件
	// https://open-be.ele.me/dev/answer/reedit?list_id=23667&question=my
	WaybillStatusDeliveryCancled  = "15" // 配送取消
	WaybillStatusFinished         = "16" // 配送完成
	WaybillStatusExceptional      = "17" // 配送异常
	WaybillStatusSelfDelivery     = "18" // 自行配送
	WaybillStatusDontDeliver      = "19" // 不再配送
	WaybillStatusDeliveryRejected = "20" // 配送拒单
	WaybillStatusCourierArrived   = "21" // 骑士到店
)

const (
	// 订单下行 - order.partrefund.push-部分退款订单信息推送(老版本)
	OrderPartRefuncTypeMerchant = 1 // 表示商户发起的部分退款
	OrderPartRefuncTypeCustomer = 2 // 表示用户发起的部分退款
	OrderPartRefuncTypeCS       = 3 // 表示客服直接发起的部分退款

	// 订单下行 - order.reverse.push-部分退款订单信息推送(新版本)
	OrderReverseRefuncTypeCustomer = 10 // 表示用户发起的部分退款
	OrderReverseRefuncTypeMerchant = 20 // 表示商户发起的部分退款
	OrderReverseRefuncTypeCS       = 30 // 表示客服直接发起的部分退款
	OrderReverseRefuncTypeAPI      = 25 // 表示api商家直接发起的部分退款
	OrderReverseRefuncTypeSys      = 40 // 系统自动发起

	// 老版本消息通知(售后单子)
	OrderPartRefundApply                = 10 // 表示商家/用户发起部分退款申请
	OrderPartRefundSuccess              = 20 // 表示部分退款成功
	OrderPartRefundUserApplyArbitration = 30 // 用户申请仲裁,客服介入
	OrderPartRefundFailed               = 40 // 表示部分退款失败
	OrderPartRefundMerchantRefused      = 50 // 表示商家拒绝用户发起的部分退款申请
	// 新版本的消息通知(售后单子)
	OrderReversePushApplyInit        = 0  // 初始化
	OrderReversePushApply            = 10 // 申请
	OrderReversePushApplyRefuse      = 20 // 拒绝
	OrderReversePushApplyArbitration = 30 // 仲裁
	OrderReversePushApplyClose       = 40 // 关闭
	OrderReversePushApplySuccess     = 50 // 成功
	OrderReversePushApplyFail        = 60 // 失败

	// 订单下行 - order.user.cancel-用户申请订单取消/退款
	OrderUserCancelApply           = 10 // 发起申请
	OrderUserCancelCSIntervene     = 20 // 客服介入
	OrderUserCancelCSRefused       = 30 // 客服拒绝
	OrderUserCancelCSAgreed        = 40 // 客服同意
	OrderUserCancelMerchantRefused = 50 // 商户拒绝
	OrderUserCancelMerchantAgreed  = 60 // 商家同意
	OrderUserCancelInvalid         = 70 // 申请失效

	OrderUserCancelTypeBeforeSale = 1 // 表示订单完成前用户全单取消申请流程
	OrderUserCancelTypeAfterSale  = 2 // 表示订单完成后用户全单退款申请流程
)

const (
	OrderFromBaidu = "1"
	OrderFromElm   = "2"

	OrderSkuDiscountTypeZhe    = "g_zhe"
	OrderSkuDiscountTypeReduce = "g_reduce"
	OrderSkuDiscountTypeTe     = "g_te"
	OrderSkuDiscountTypeZeng   = "zeng"
)

const (
	UserApplyCancelWaitMinute = 15 // 用户申请取消订单后待处理的最大等待时间（分钟），超时自动同意
)

const (
	ListOrderPageSize = 100 // order.list的每页条数
)

// 提供给合作方确认订单所用。 注：1、10分钟内未确认的订单系统自动取消。2、确认失败的订单请不要做餐。 2016年7月4号起，将由百度外卖负责完成订单。届时，对接方无需调用完成订单接口，继续调用可能导致订单结算有问题。
func (a *API) OrderConfirm(orderID string) (err error) {
	data, err := a.AccessAPI("order.confirm", map[string]interface{}{
		"order_id": orderID,
	})
	fmt.Println(data)
	return err
}

// 仅择时达和新零售标品服务包的订单，商家可调用此接口将订单置为已拣货完成状态。订单超过预计拣货完成时间未调用此接口，系统会自动更新为已拣货完成状态。
// https://open-be.ele.me/dev/api/doc/v3/#api-Order_Up-order_pickcomplete
func (a *API) OrderPickComplete(orderID string) (err error) {
	_, err = a.AccessAPI("order.pickcomplete", map[string]interface{}{
		"order_id": orderID,
	})
	return err
}

// 蜂鸟众包订单呼叫骑士配送，仅限蜂鸟众包商户调用
func (a *API) OrderCallDelivery(orderID string) (err error) {
	_, err = a.AccessAPI("order.callDelivery", map[string]interface{}{
		"order_id": orderID,
	})
	return err
}

// 蜂鸟众包订单取消呼叫骑士配送，仅限蜂鸟众包商户调用。
func (a *API) OrderCancelDelivery(orderID string) (err error) {
	// 下线
	//_, err = a.AccessAPI("order.cancelDelivery", map[string]interface{}{
	//	"order_id": orderID,
	//})
	//return err
	return a.OrderSwitchselfdelivery(orderID)
}

// 提供给合作方在配送异常或物流拒单后选择自行配送
func (a *API) OrderSwitchselfdelivery(orderID string) (err error) {
	_, err = a.AccessAPI("order.switchselfdelivery", map[string]interface{}{
		"order_id": orderID,
	})
	return err
}

// 查看订单详情
func (a *API) OrderGet(orderID string) (orderMap map[string]interface{}, err error) {
	result, err := a.AccessAPI("order.get", map[string]interface{}{
		"order_id": orderID,
	})
	if err == nil {
		return result.Data.(map[string]interface{}), nil
	}
	return nil, err
}

func (a *API) OrderGet2(orderID string) (order *OrderDetailInfo, err error) {
	result, err := a.AccessAPI("order.get", map[string]interface{}{
		"order_id": orderID,
	})
	if err == nil {
		err = utils.Map2StructByJson(result.Data, &order, true)
	}
	return order, err
}

func (a *API) OrderStatusGet(orderID string) (status int, err error) {
	result, err := a.AccessAPI("order.status.get", map[string]interface{}{
		"order_id": orderID,
	})
	if err == nil {
		status = int(utils.ForceInterface2Int64(result.Data.(map[string]interface{})["status"]))
	}
	return status, err
}

// 设置订单快递单号
func (a *API) OrderExpressCreate(shopID string, expressList []*ExpressInfo) (status int, err error) {
	result, err := a.AccessAPI("order.express.create", map[string]interface{}{
		KeyShopID:      shopID,
		"express_list": expressList,
	})
	if err == nil {
		return int(utils.MustInterface2Int64(result.Data.(map[string]interface{})["status"])), nil
	}
	return 0, err
}

func (a *API) OrderPrivateInfo(orderID string) (mobileInfo *PrivateMobileInfo, err error) {
	result, err := a.AccessAPI("order.privateinfo", map[string]interface{}{
		"order_id": orderID,
	})
	if err == nil {
		mapData := result.Data.(map[string]interface{})
		mobileInfo = &PrivateMobileInfo{
			ShortNumber: mapData["short_number"].(string),
		}
		expireDate := utils.Interface2String(mapData["expire_date"])
		if expireDate != "" {
			tmpTime := utils.Str2Time(expireDate)
			mobileInfo.ExpireDate = &tmpTime
		}
		return mobileInfo, nil
	}
	return nil, err
}

func (a *API) OrderDeliveryGet(orderID string) (deliveryInfo map[string]interface{}, err error) {
	result, err := a.AccessAPI("order.delivery.get", map[string]interface{}{
		"order_id": orderID,
	})
	if err == nil {
		return result.Data.(map[string]interface{}), nil
	}
	return nil, err
}

func (a *API) OrderIdConvert(orderID string, isElemeOrder bool) (convertedOrderID string, err error) {
	key := "order_id"
	resultKey := "eleme_order_id"
	if isElemeOrder {
		key = "eleme_order_id"
		resultKey = "order_id"
	}
	result, err := a.AccessAPI("order.id.convert", map[string]interface{}{
		key: orderID,
	})
	if err == nil {
		return utils.Interface2String(result.Data.(map[string]interface{})[resultKey]), nil
	}
	return "", err
}

// 查看订单列表
// https://open-be.ele.me/dev/api/doc/v3/#api-Order_Up-order_list
// page从1开始
func (a *API) OrderList(shopID string, baiduShopID int64, startTime, endTime int64, status int, page int) (listOrderInfo *ListOrderInfo, err error) {
	params := a.genShopIDParams(shopID, baiduShopID, 0)
	if startTime > 0 {
		params["start_time"] = startTime
	}
	if endTime > 0 {
		params["end_time"] = endTime
	}
	if status > 0 {
		params["status"] = status
	}
	if page > 0 {
		params["page"] = page
	}
	result, err := a.AccessAPI("order.list", params)
	if err == nil {
		err = utils.Map2StructByJson(result.Data, &listOrderInfo, true)
	}
	return listOrderInfo, err
}

func (a *API) OrderListAll(shopID string, baiduShopID int64, startTime, endTime int64, status int) (listOrder []*ListOrderItemInfo, err error) {
	page := 1
	for {
		result, err := a.OrderList(shopID, baiduShopID, startTime, endTime, status, page)
		if err != nil {
			return nil, err
		}
		listOrder = append(listOrder, result.List...)
		// 这个地方暂停是应为接口请求超频
		time.Sleep(1 * time.Second)
		if result.Page >= result.Pages {
			break
		}
		page++
	}
	return listOrder, nil
}

func (a *API) SmartOrderIdConvert(orderID string) (convertedOrderID string, err error) {
	return a.OrderIdConvert(orderID, isOrderIDEleme(orderID))
}

func isOrderIDEleme(orderID string) bool {
	return len(orderID) == len("3026328756122155111")
}

func (a *API) OrderAgreeRefund(param *RefundOrderExamine) (err error) {
	return a.EbaiRefundOrder(param)
	//_, err = a.AccessAPI("order.agreerefund", map[string]interface{}{
	//	"order_id": orderID,
	//})
	//return err
}

func (a *API) OrderDisagreeRefund(param *RefundOrderExamine) (err error) {
	return a.EbaiRefundOrder(param)
	//_, err = a.AccessAPI("order.disagreerefund", map[string]interface{}{
	//	"order_id":      orderID,
	//	"refuse_reason": refuseReason,
	//})
	//return err
}

// 用户多次退商家同意
func (a *API) OrderAgreePartRefund(param *RefundOrderExamine) (err error) {
	return a.EbaiRefundOrder(param)

	//_, err = a.AccessAPI("order.agreepartrefund", map[string]interface{}{
	//	"order_id":  orderID,
	//	"products":  removeSkuList,
	//	"refund_id": refundID,
	//})
	//return err
}

//售后 同意退货退款
func (a *API) OrderAgreeReturnGoods(param *RefundOrderExamine) (err error) {
	return a.EbaiRefundOrder(param)
	//_, err = a.AccessAPI("order.agreereturngoods", map[string]interface{}{
	//	"order_id":        orderID,
	//	"refund_order_id": refundOrderID,
	//})
	//return err
}

//售后 拒绝退货退款
func (a *API) OrderDisagreeReturnGoods(param *RefundOrderExamine) (err error) {
	err = a.EbaiRefundOrder(param)
	return err
	//data, err := a.AccessAPI("order.disagreereturngoods", map[string]interface{}{
	//	"order_id":        orderID,
	//	"refund_order_id": refundOrderID,
	//	"refuse_code":     "5",
	//	"refuse_reason":   reason,
	//})
	//fmt.Println(data)
	//return err
}

func (a *API) OrderCheckout(orderID, pickUpCode string) (err error) {
	_, err = a.AccessAPI("order.checkout", map[string]interface{}{
		"order_id":     orderID,
		"pick_up_code": pickUpCode,
	})
	return err
}

func (a *API) OrderQueryAcceptancecode(orderID string) (err error) {
	_, err = a.AccessAPI("order.query.acceptancecode", map[string]interface{}{
		"order_id": orderID,
	})
	return err
}

// EbaiRefundOrder 同意退款V2.0 上面的舍弃使用2.0
func (a *API) EbaiRefundOrder(param *RefundOrderExamine) error {
	if (param.ActionType == RefundTypeRefuse || param.ActionType == RefundTypeRefuseGoods) && param.ReasonCode == "" {
		param.ReasonCode = "7001"
	}
	if param.ReasonRemarks != "" && param.ReasonRemarks != "同意退款" {
		param.ActionType = "2"
	}
	_, err := a.AccessAPI("order.reverse.process", utils.Struct2MapByJson(param))
	return err
}

// 查看部分退款订单详情(平台已经不再维护这个接口改用下面接口)
func (a *API) OrderPartRefundGet(orderID string) (orderMap map[string]interface{}, err error) {
	result, err := a.AccessAPI("order.reverse.query", map[string]interface{}{
		"order_id": orderID,
	})
	if err == nil {
		return result.Data.(map[string]interface{}), nil
	}
	return nil, err
}

// GetReverseOrder 根据订单号获取详细订单详情
func (a *API) GetReverseOrder(orderId string) ([]interface{}, bool, error) {
	refundOrder, err := a.AccessAPI("order.reverse.query", map[string]interface{}{
		"order_id": orderId,
	})
	if err != nil {
		return nil, false, err
	}
	if len(refundOrder.Data.(map[string]interface{})["reverse_order_list"].([]interface{})) == 0 {
		return nil, false, err
	}
	if len(refundOrder.Data.(map[string]interface{})["reverse_order_list"].([]interface{})[0].(map[string]interface{})) == 0 {
		return nil, false, nil
	}

	data := refundOrder.Data.(map[string]interface{})["reverse_order_list"].([]interface{})[0].(map[string]interface{})
	isAll := utils.MustInterface2Int64(data["is_refund_all"]) == 1
	return data["sub_reverse_order_list"].([]interface{}), isAll, nil
}

// OrderPartRefund 商家主动发起多次部分退
func (a *API) OrderPartRefund(orderID string, removeSkuList []*RefundSku) (err error) {
	//return a.EbaiRefundOrder(param)
	_, err = a.AccessAPI("order.manyTimesPartrefund", map[string]interface{}{
		"order_id": orderID,
		"products": removeSkuList,
	})
	return err
}

// OrderCancel 提供给合作方取消订单所用。 注：1、百度物流配送且已经确认的订单无法取消。
func (a *API) OrderCancel(orderID, cancelType, cancelReason string) (err error) {
	_, err = a.AccessAPI("order.cancel", map[string]interface{}{
		"order_id": orderID,
		"type":     cancelType,
		"reason":   cancelReason,
	})
	return err
}

// OrderReverseApply 商户发起全退和部分退款(整合OrderPartRefund/OrderCancel)
func (a *API) OrderReverseApply(param *OrderReverseApplyParam) error {
	_, err := a.AccessAPI("order.reverse.apply", utils.Struct2MapByJson(param))
	if err != nil {
		globals.SugarLogger.Debugf("OrderReverseApply err : %s --- %v", utils.Format4Output(param, false), err)
	}
	return err
}

// OrderselfDeliveryStateSync2 饿了么自配送订单接入骑手状态
func (a *API) OrderselfDeliveryStateSync2(info *PushRiderInfo) (err error) {
	_, err = a.AccessAPI("order.selfDeliveryStateSync", utils.Struct2MapByJson(info))
	if err != nil {
		globals.SugarLogger.Debugf("OrderReverseApply err : %s --- %v", utils.Format4Output(info, false), err)
	}
	return err
}

// SelfDeliveryLocationSync 自配送定时更新骑手坐标信息
func (a *API) SelfDeliveryLocationSync(param *OrderSelfDeliveryLocationSync) (err error) {
	_, err = a.AccessAPI("order.selfDeliveryLocationSync", utils.Struct2MapByJson(param))
	if err != nil {
		globals.SugarLogger.Debugf("OrderReverseApply err : %s --- %v", utils.Format4Output(param, false), err)
	}
	return err
}
