package dada

import (
	"errors"
	"fmt"
	"time"

	tao "git.rosy.net.cn/baseapi/platformapi/tao_vegetable"
	"git.rosy.net.cn/jx-callback/business/jxcallback/orderman"
	"git.rosy.net.cn/jx-callback/business/partner/purchase/tao_vegetable"

	"git.rosy.net.cn/baseapi/platformapi/dadaapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/business/partner/delivery"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
	beego "github.com/astaxie/beego/server/web"
)

const (
	maxOrderPrice  = 50000 // 单位为分，达达最大价格，超过这个价格配送费会增加,2020-11-25改为50000，之前是6399
	maxOrderWeight = 5000  // 5公斤
)

var (
	ErrCanNotFindDadaCityCode = errors.New("不能找到美团配送站点配置")
	ErrExceedMaxDiffFee2Mtps  = errors.New("与美团配送超价太多")
)

var (
	CurDeliveryHandler *DeliveryHandler

	dadaDistrictMap = map[string]string{
		"苏州工业园区": "工业园区",
		"郫都区":    "郫县",
		"管城回族区":  "管城区",
		"昆山市":    "1",
		"常熟市":    "1",
		"太仓市":    "1",
		"虞山街道":   "虞山镇",
		"常福街道":   "虞山镇",
	}
	complaintReasonsMap = map[int]string{
		1:  "骑手态度恶劣",
		2:  "骑手接单后未取货",
		3:  "骑手取货太慢",
		4:  "骑手送货太慢",
		5:  "货品未送达",
		6:  "货品有损坏",
		7:  "骑手违规收取顾客其他费用",
		69: "骑手恶意取消订单",
		71: "骑手提前点击取货/送达",
	}
)

type DeliveryHandler struct {
}

func init() {
	CurDeliveryHandler = new(DeliveryHandler)
	partner.RegisterDeliveryPlatform(CurDeliveryHandler, true)
}

func OnWaybillMsg(msg *dadaapi.CallbackMsg) (retVal *dadaapi.CallbackResponse) {
	return CurDeliveryHandler.OnWaybillMsg(msg)
}

func (c *DeliveryHandler) GetVendorID() int {
	return model.VendorIDDada
}

func (c *DeliveryHandler) OnWaybillMsg(msg *dadaapi.CallbackMsg) (retVal *dadaapi.CallbackResponse) {
	jxutils.CallMsgHandler(func() {
		retVal = c.onWaybillMsg(msg)
	}, jxutils.ComposeUniversalOrderID(msg.OrderID, model.VendorIDDada))
	return retVal
}

func (c *DeliveryHandler) onWaybillMsg(msg *dadaapi.CallbackMsg) (retVal *dadaapi.CallbackResponse) {
	order, goodsOrder := c.callbackMsg2Waybill(msg)
	store, _ := dao.GetStoreDetail(dao.GetDB(), goodsOrder.JxStoreID, goodsOrder.VendorID, goodsOrder.VendorOrgCode)

	switch msg.OrderStatus {
	case dadaapi.OrderStatusWaitingForAccept:
		if dadaOrder, err2 := api.DadaAPI.QueryOrderInfo(msg.OrderID); err2 == nil {
			order.ActualFee = jxutils.StandardPrice2Int(dadaOrder.ActualFee)
			order.DesiredFee = jxutils.StandardPrice2Int(dadaOrder.DeliveryFee) + int64(store.FreightMarkup)
		}
		order.Status = model.WaybillStatusNew
	case dadaapi.OrderStatusAccepted:
		order.Status = model.WaybillStatusCourierAssigned
		order.Remark = order.CourierName + "，" + order.CourierMobile
		if dadaOrder, err2 := api.DadaAPI.QueryOrderInfo(msg.OrderID); err2 == nil {
			order.ActualFee = jxutils.StandardPrice2Int(dadaOrder.ActualFee)
			order.DesiredFee = jxutils.StandardPrice2Int(dadaOrder.DeliveryFee) + int64(store.FreightMarkup)
		}
	case dadaapi.OrderStatusReturningInOrder:
		order.Status = model.WaybillStatusCourierArrived
	case dadaapi.OrderStatusDelivering:
		order.Status = model.WaybillStatusDelivering
	case dadaapi.OrderStatusFinished:
		order.Status = model.WaybillStatusDelivered
	case dadaapi.OrderStatusCanceled:
		order.Status = model.WaybillStatusCanceled
	case dadaapi.OrderStatusAddOrderFailed:
		order.Status = model.WaybillStatusFailed
	default:
		order.Status = model.WaybillStatusUnknown
	}

	err := dadaapi.Err2CallbackResponse(partner.CurOrderManager.OnWaybillStatusChanged(order), utils.Int2Str(order.Status))

	switch order.OrderVendorID {
	case model.VendorIDDD:
		Lng, Lat, _ := partner.GetRidderPositionGetter(order.WaybillVendorID).GetRidderPosition(nil, order.VendorOrderID, order.VendorOrderID, order.VendorWaybillID, order.VendorWaybillID2)
		tiktokStatusPush(order, msg.OrderStatus, utils.Float64ToStr(Lng), utils.Float64ToStr(Lat), goodsOrder.VendorOrgCode)
	case model.VendorIDMTWM, model.VendorIDTaoVegetable, model.VendorIDEBAI, model.VendorIDJD:
		delivery.GetOrderRiderInfoToPlatform(order.VendorOrderID, order.Status) // 骑手位置更新
		if goodsOrder.VendorID == model.VendorIDTaoVegetable && msg.OrderStatus == dadaapi.OrderStatusAccepted {
			tao_vegetable.PushDelivererChangeInfo(goodsOrder, order, tao.TaoDeliveryTypeDD)
		}
	}

	return err
}

// 抖音订单状态回传
func tiktokStatusPush(order *model.Waybill, status int, lng, lat, vendorOrgCode string) {
	result := &utils.RiderInfo{
		OrderId:               order.VendorOrderID,
		ThirdCarrierOrderId:   order.VendorWaybillID,
		CourierName:           order.CourierName,
		CourierPhone:          order.CourierMobile,
		LogisticsStatus:       order.Status,
		OpCode:                "",
		LogisticsProviderCode: utils.DaDaCode,
		Longitude:             lng,
		Latitude:              lat,
	}

	switch status {
	case dadaapi.OrderStatusWaitingForAccept: // 待接单,召唤骑手
		result.LogisticsStatus = model.WaybillStatusNew
		result.LogisticsContext = model.RiderWaitRider
	case dadaapi.OrderStatusAccepted: // 待取货
		result.LogisticsStatus = model.WaybillStatusCourierAssigned // 分配骑手
		result.LogisticsContext = model.RiderWaitGetGoods
	case dadaapi.OrderStatusDelivering: // 配送中
		result.LogisticsStatus = model.WaybillStatusDelivering
		result.LogisticsContext = model.RiderGetOrderDelivering
	case dadaapi.OrderStatusFinished: // 完成
		result.LogisticsStatus = model.WaybillStatusDelivered
		result.LogisticsContext = model.RiderGetOrderDelivered
	case dadaapi.OrderStatusCanceled: // 取消
		result.LogisticsStatus = model.WaybillStatusCanceled
		result.LogisticsContext = model.RiderGetOrderCanceled
	case 8: // 指派单,不处理
		result.LogisticsStatus = 0
		result.LogisticsContext = model.RiderGetOrderDeliverOther
	case 9: // 配送异常返回值
		result.LogisticsStatus = model.WaybillStatusDeliverFailed
		result.LogisticsContext = model.RiderGetOrderDeliverFailed
	case 10: // 妥投异常之物品返回完成 - 不处理
		result.LogisticsStatus = 0
		result.LogisticsContext = model.RiderGetOrderDeliverOther
	case dadaapi.OrderStatusReturningInOrder: // 骑手到店
		result.LogisticsStatus = model.WaybillStatusCourierArrived
		result.LogisticsContext = model.RiderToStore
	case dadaapi.OrderStatusAddOrderFailed: // 创建达达运单失败 - 不处理
		result.LogisticsStatus = model.WaybillStatusFailed
		result.LogisticsContext = model.RiderGetOrderDeliverOther
	default:
		result.LogisticsStatus = 0
		result.LogisticsContext = model.RiderGetOrderDeliverOther
	}
	delivery.PullTiktokRiderInfo(result, vendorOrgCode)
}

func (c *DeliveryHandler) callbackMsg2Waybill(msg *dadaapi.CallbackMsg) (retVal *model.Waybill, goods *model.GoodsOrder) {
	retVal = &model.Waybill{
		VendorWaybillID: msg.ClientID,
		WaybillVendorID: model.VendorIDDada,
		CourierName:     msg.DmName,
		CourierMobile:   msg.DmMobile,
		VendorStatus:    utils.Int2Str(msg.OrderStatus),
		Remark:          msg.CancelReason,
		// StatusTime:      utils.Timestamp2Time(int64(msg.UpdateTime)),
	}
	// dada太扯了，不同消息过来的时间格式不一样
	updateTime := int64(msg.UpdateTime)
	if updateTime > 2511789475 {
		updateTime = updateTime / 1000
	}
	retVal.StatusTime = utils.Timestamp2Time(updateTime)
	//retVal.VendorOrderID, retVal.OrderVendorID = jxutils.SplitUniversalOrderID(msg.OrderID)

	sql := `SELECT * FROM goods_order WHERE vendor_order_id = ? ORDER BY order_created_at DESC  LIMIT 1 OFFSET 0`
	sqlParams := []interface{}{msg.OrderID}
	dao.GetRow(dao.GetDB(), &goods, sql, sqlParams)
	retVal.OrderVendorID = goods.VendorID
	retVal.VendorOrderID = goods.VendorOrderID
	return retVal, goods
}

func StoreDetail2ShopInfo(storeDetail *dao.StoreDetail2) (shopInfo *dadaapi.ShopInfo) {
	lng := jxutils.IntCoordinate2Standard(storeDetail.Lng)
	lat := jxutils.IntCoordinate2Standard(storeDetail.Lat)
	cityName := storeDetail.CityName
	districtName := storeDetail.DistrictName
	if dadaDistrictMap[districtName] != "" {
		if dadaDistrictMap[districtName] == "1" { // 区镇信息
			cityName = districtName
			districtName, _ = api.TencentMapAPI.GetCoordinateTownInfo(lng, lat)
		}
		if dadaDistrictMap[districtName] != "" {
			districtName = dadaDistrictMap[storeDetail.DistrictName]
		}
	}
	shopInfo = &dadaapi.ShopInfo{
		OriginShopID:   storeDetail.VendorStoreID,
		StationName:    storeDetail.Name,
		Business:       dadaapi.BusinessTypeConvStore, // 故意设置成这个的
		CityName:       cityName,
		AreaName:       districtName,
		StationAddress: storeDetail.Address,
		Lng:            lng,
		Lat:            lat,
		ContactName:    storeDetail.PayeeName,
		Phone:          storeDetail.Tel1,
	}
	if storeDetail.CourierStatus >= model.StoreStatusClosed {
		shopInfo.Status = dadaapi.ShopStatusOnline
	} else {
		shopInfo.Status = dadaapi.ShopStatusOffline
	}
	return shopInfo
}

func (c *DeliveryHandler) CreateStore(ctx *jxcontext.Context, storeDetail *dao.StoreDetail2) (vendorStoreID string, status int, err error) {
	if globals.EnableStoreWrite {
		vendorStoreID, err = api.DadaAPI.ShopAdd(StoreDetail2ShopInfo(storeDetail))
		if err == nil {
			status = model.StoreAuditStatusOnline
		}
	} else {
		vendorStoreID = utils.Int64ToStr(jxutils.GenFakeID())
		status = model.StoreAuditStatusOnline
	}
	return vendorStoreID, status, err
}

func (c *DeliveryHandler) UpdateStore(ctx *jxcontext.Context, storeDetail *dao.StoreDetail2) (err error) {
	if globals.EnableStoreWrite {
		err = api.DadaAPI.ShopUpdate(StoreDetail2ShopInfo(storeDetail))
	}
	return err
}

func dadaStatus2Jx(dadaStatus int) int {
	if dadaStatus == dadaapi.ShopStatusOnline {
		return model.StoreStatusOpened
	}
	return model.StoreStatusDisabled
}

func (c *DeliveryHandler) GetStore(ctx *jxcontext.Context, storeID int, vendorStoreID string) (storeDetail *dao.StoreDetail2, err error) {
	shopInfo, err := api.DadaAPI.ShopDetail(vendorStoreID)
	if err == nil {
		storeDetail = &dao.StoreDetail2{
			Store: model.Store{
				Name:      shopInfo.StationName,
				Address:   shopInfo.StationAddress,
				Lng:       jxutils.StandardCoordinate2Int(shopInfo.Lng),
				Lat:       jxutils.StandardCoordinate2Int(shopInfo.Lat),
				PayeeName: shopInfo.ContactName,
				Tel1:      shopInfo.Phone,
			},
			VendorID:      model.VendorIDDada,
			VendorStoreID: shopInfo.OriginShopID,
			CourierStatus: dadaStatus2Jx(shopInfo.Status),
			AuditStatus:   model.StoreAuditStatusOnline,
			CityName:      shopInfo.CityName,
			DistrictName:  shopInfo.AreaName,
		}
	}
	return storeDetail, err
}

func (c *DeliveryHandler) IsErrStoreNotExist(err error) bool {
	return dadaapi.IsErrShopNotExist(err)
}

func (c *DeliveryHandler) IsErrStoreExist(err error) bool {
	return dadaapi.IsErrShopExist(err)
}

func (c *DeliveryHandler) GetWaybillFee(order *model.GoodsOrder) (deliveryFeeInfo *partner.WaybillFeeInfo, err error) {
	db := dao.GetDB()
	deliveryFeeInfo = &partner.WaybillFeeInfo{}
	billParams, err := c.getBillParams(db, order)
	if err == nil {
		var result *dadaapi.CreateOrderResponse
		if result, err = api.DadaAPI.QueryDeliverFee(billParams); err != nil {
			return nil, err
		}
		deliveryFeeInfo.DeliveryFee = jxutils.StandardPrice2Int(result.DeliverFee) // jxutils.StandardPrice2Int(result.Fee)
		deliveryFeeInfo.RefDeliveryFee = deliveryFeeInfo.DeliveryFee
		deliveryFeeInfo.RefAddFee = deliveryFeeInfo.DeliveryFee
	}
	return deliveryFeeInfo, err
}

func (c *DeliveryHandler) getBillParams(db *dao.DaoDB, order *model.GoodsOrder) (billParams *dadaapi.OperateOrderParams, err error) {
	billParams = &dadaapi.OperateOrderParams{
		OriginID:        jxutils.ComposeUniversalOrderID(order.VendorOrderID, order.VendorID),
		CargoPrice:      jxutils.IntPrice2Standard(limitOrderPrice(order.ActualPayPrice)),
		IsPrepay:        0,
		ReceiverName:    utils.FilterMb4(order.ConsigneeName),
		ReceiverAddress: utils.FilterMb4(order.ConsigneeAddress),
		ReceiverPhone:   order.ConsigneeMobile,
	}
	if billParams.ShopNo, err = c.getDadaShopID(order, db); err == nil {
		if billParams.CityCode, err = c.getDataCityCodeFromOrder(order, db); err == nil {
			billParams.ReceiverLng, billParams.ReceiverLat, _ = jxutils.IntCoordinate2MarsStandard(order.ConsigneeLng, order.ConsigneeLat, order.CoordinateType)
			billParams.Info = fmt.Sprintf("%s第%d号订单, %s", model.VendorChineseNames[order.VendorID], order.OrderSeq, utils.FilterMb4("客户电话："+order.ConsigneeMobile+","+order.BuyerComment+"配送遇到问题，可联系18048531223取消配送单。"))
			billParams.CargoType = dadaapi.CargoTypeFresh
			billParams.CargoWeight = float64(jxutils.IntWeight2Float(limitOrderWeight(order.Weight)))
			billParams.CargoNum = order.GoodsCount
		}
	}
	return billParams, err
}

// CreateWaybill IDeliveryPlatformHandler
func (c *DeliveryHandler) CreateWaybill(order *model.GoodsOrder, maxDeliveryFee int64) (bill *model.Waybill, err error) {
	db := dao.GetDB()

	// 判断配送平台是否被关闭
	vendorOrgCode, err := dao.GetVendorOrgCode(db, model.VendorIDDada, "", model.VendorOrgTypeDelivery)
	if err != nil {
		return nil, err
	}

	if len(vendorOrgCode) > 0 && vendorOrgCode[0].IsOpen == model.YES {
		return nil, fmt.Errorf("此平台配送已被系统关闭，暂不发配送 [%v]", vendorOrgCode[0].Comment)
	}

	// 获取达达第三方订单参数
	billParams, err := c.getBillParams(db, order)
	if err != nil {
		return nil, err
	}

	// 达达要求第二次创建运单，调用函数不同。所以查找两天内有无相同订单号的运单
	var waybillList []*model.Waybill
	err = dao.GetRows(db, &waybillList, `
					SELECT *
					FROM waybill
					WHERE waybill_created_at > DATE_ADD(NOW(), interval -2 day)
					AND vendor_order_id = ?
					AND waybill_vendor_id = ?
					ORDER BY id DESC
					`, jxutils.ComposeUniversalOrderID(order.VendorOrderID, order.VendorID), model.VendorIDDada)
	if err != nil {
		return nil, err
	}

	// 检查两天内是否有订单
	var result *dadaapi.CreateOrderResponse
	if len(waybillList) > 0 && waybillList[0].Status != model.WaybillStatusFailed {
		// 检索达达配送费阀值
		if err = delivery.CallCreateWaybillPolicy(waybillList[0].ActualFee, maxDeliveryFee, order, model.VendorIDDada); err != nil {
			return nil, err
		}
		// 重新发送订单
		result, err = api.DadaAPI.ReaddOrder(billParams)
		if err != nil {
			return nil, err
		}
	} else {
		// 第一次发布订单(预发布,先查询订单运费获取平台订单号,在调用查询订单后接口发布订单)
		// 查询达达订单费用
		if result, err = api.DadaAPI.QueryDeliverFee(billParams); err != nil {
			return nil, err
		}
		// 阀值警报
		if err = delivery.CallCreateWaybillPolicy(jxutils.StandardPrice2Int(result.Fee), maxDeliveryFee, order, model.VendorIDDada); err != nil {
			return nil, err
		}
		// 真实发布订单
		if err = api.DadaAPI.AddOrderAfterQuery(result.DeliveryNo); err != nil {
			return nil, err
		}
	}
	if result == nil {
		return nil, errors.New("达达配送,平台调用错误,无订单数据返回")
	}

	bill = &model.Waybill{
		VendorOrderID:   order.VendorOrderID,
		OrderVendorID:   order.VendorID,
		WaybillVendorID: model.VendorIDDada,
		DesiredFee:      jxutils.StandardPrice2Int(result.DeliverFee),
		ActualFee:       jxutils.StandardPrice2Int(result.DeliverFee),
	}
	delivery.OnWaybillCreated(bill)
	return bill, err
}

func (c *DeliveryHandler) CancelWaybill(bill *model.Waybill, cancelReasonID int, cancelReason string) (err error) {
	switch cancelReasonID {
	case partner.CancelWaybillReasonNotAcceptIntime:
		cancelReasonID = dadaapi.ReasonIDNobodyAccept
	case partner.CancelWaybillReasonSwitch2SelfFailed:
		cancelReasonID = dadaapi.ReasonIDClientDontWantItAnymore
	default:
		cancelReasonID = dadaapi.ReasonIDOther
	}
	_, err = api.DadaAPI.CancelOrder(bill.VendorOrderID, cancelReasonID, cancelReason)
	return err
}

func (c *DeliveryHandler) getDataCityCodeFromOrder(order *model.GoodsOrder, db *dao.DaoDB) (retVal string, err error) {
	jxStoreID := jxutils.GetSaleStoreIDFromOrder(order)
	sql := `
		SELECT t2.tel_code
		FROM store t1
		JOIN place t2 on t1.city_code = t2.code
		WHERE t1.id = ?
		`
	codeInfo := &struct {
		TelCode string
	}{}
	if err = dao.GetRow(db, codeInfo, sql, jxStoreID); err != nil {
		if err == nil {
			err = ErrCanNotFindDadaCityCode
		}
		return "", err
	}
	return codeInfo.TelCode, nil
}

func (c *DeliveryHandler) getDadaShopID(order *model.GoodsOrder, db *dao.DaoDB) (retVal string, err error) {
	saleStoreID := jxutils.GetSaleStoreIDFromOrder(order)
	storeCourierList, err2 := dao.GetOpenedStoreCouriersByStoreID(db, saleStoreID, model.VendorIDDada)
	if err = err2; err != nil && !dao.IsNoRowsError(err) {
		return "", err
	}
	if len(storeCourierList) == 0 {
		return "", partner.ErrStoreHaveNoCourier
	}
	retVal = storeCourierList[0].VendorStoreID
	if beego.BConfig.RunMode == "dev" {
		retVal = "test_0001"
	}
	return retVal, nil
}

func limitOrderPrice(price int64) int64 {
	if price > maxOrderPrice {
		return maxOrderPrice
	}
	return price
}

func limitOrderWeight(weight int) int {
	if weight > maxOrderWeight {
		return maxOrderWeight
	}
	return weight
}

func (c *DeliveryHandler) ComplaintRider(bill *model.Waybill, resonID int, resonContent string) (err error) {
	if globals.EnableStoreWrite {
		err = api.DadaAPI.ComplaintRider(bill.VendorOrderID, resonID)
	}
	return err
}

func (c *DeliveryHandler) GetWaybillTip(ctx *jxcontext.Context, vendorOrgCode, vendorStoreID, vendorOrderID, vendorWaybillID, vendorWaybillID2 string) (tipFee int64, err error) {
	order, err := api.DadaAPI.QueryOrderInfo(vendorOrderID)
	if err == nil {
		tipFee = jxutils.StandardPrice2Int(order.Tips)
	}
	return tipFee, err
}

func (c *DeliveryHandler) UpdateWaybillTip(ctx *jxcontext.Context, vendorOrgCode, vendorStoreID, vendorOrderID, vendorWaybillID, vendorWaybillID2, cityCode string, tipFee int64) (err error) {
	if globals.EnableStoreWrite {
		err = api.DadaAPI.AddTip(vendorOrderID, jxutils.IntPrice2Standard(tipFee), cityCode, "")
	}
	return err
}

func (c *DeliveryHandler) GetRidderPosition(ctx *jxcontext.Context, vendorOrgCode, vendorOrderID, vendorWaybillID, vendorWaybillID2 string) (lng, lat float64, err error) {
	order, err := api.DadaAPI.QueryOrderInfo(vendorOrderID)
	if err == nil {
		lng = utils.Str2Float64WithDefault(order.TransporterLng, 0)
		lat = utils.Str2Float64WithDefault(order.TransporterLat, 0)
	}
	return lng, lat, err
}

// 获取骑手信息(订单详情)
func (c *DeliveryHandler) GetRiderInfo(orderId string, deliveryId int64, mtPeisongId string) (rider *utils.RiderInfo, err error) {
	order, err := api.DadaAPI.QueryOrderInfo(orderId)
	if err != nil {
		return nil, err
	}

	result := &utils.RiderInfo{
		OrderId:               orderId,
		ThirdCarrierOrderId:   mtPeisongId,
		CourierName:           order.TransporterName,
		CourierPhone:          order.TransporterPhone,
		LogisticsProviderCode: utils.DaDaCode,
		LogisticsStatus:       order.StatusCode,
		LogisticsContext:      "",
		Latitude:              order.TransporterLat,
		Longitude:             order.TransporterLng,
	}

	switch order.StatusCode {
	case dadaapi.OrderStatusWaitingForAccept: // 待接单,召唤骑手
		result.LogisticsStatus = model.WaybillStatusNew
		result.LogisticsContext = model.RiderWaitRider
	case dadaapi.OrderStatusAccepted: // 待取货
		result.LogisticsStatus = model.WaybillStatusCourierAssigned // 分配骑手
		result.LogisticsContext = model.RiderWaitGetGoods
	case dadaapi.OrderStatusDelivering: // 配送中
		result.LogisticsStatus = model.WaybillStatusDelivering
		result.LogisticsContext = model.RiderGetOrderDelivering
	case dadaapi.OrderStatusFinished: // 完成
		result.LogisticsStatus = model.WaybillStatusDelivered
		result.LogisticsContext = model.RiderGetOrderDelivered
	case dadaapi.OrderStatusCanceled: // 取消
		result.LogisticsStatus = model.WaybillStatusCanceled
		result.LogisticsContext = model.RiderGetOrderCanceled
	case 8: // 指派单,不处理
		result.LogisticsStatus = 0
		result.LogisticsContext = model.RiderGetOrderDeliverOther
	case 9: // 配送异常返回值
		result.LogisticsStatus = model.WaybillStatusDeliverFailed
		result.LogisticsContext = model.RiderGetOrderDeliverFailed
	case 10: // 妥投异常之物品返回完成 - 不处理
		result.LogisticsStatus = 0
		result.LogisticsContext = model.RiderGetOrderDeliverOther
	case dadaapi.OrderStatusReturningInOrder: // 骑手到店
		result.LogisticsStatus = model.WaybillStatusCourierArrived
		result.LogisticsContext = model.RiderToStore
	case dadaapi.OrderStatusAddOrderFailed: // 创建达达运单失败 - 不处理
		result.LogisticsStatus = model.WaybillStatusFailed
		result.LogisticsContext = model.RiderGetOrderDeliverOther
	default:
		result.LogisticsStatus = 0
		result.LogisticsContext = model.RiderGetOrderDeliverOther
	}
	return result, nil
}

// GetDeliverLiquidatedDamages 获取达达平台扣除配送费
// 待接单,待取货(小于一分钟,大于十五分钟)不扣钱
// 待取货1-15分钟内取消扣两元
func (c *DeliveryHandler) GetDeliverLiquidatedDamages(orderId string, deliverId string) (money int64, err error) {
	orderStatus, err := orderman.FixedOrderManager.GetWayBillStatusList(orderId, deliverId, model.VendorIDDada)
	if err != nil {
		return 0, err
	}

	isMerchantCancel := false
	// 获取发起取消的人员
	for _, v := range orderStatus {
		if v.VendorStatus == utils.Int64ToStr(model.WaybillStatusCancel) {
			isMerchantCancel = true // 商户取消
			break
		}
	}

	dadaOrder, err := api.DadaAPI.QueryOrderInfo(orderId)
	if err != nil {
		return 0, err
	}

	// 本地状态兑换金额
	var localPrice int64 = 0
	for i := len(orderStatus) - 1; i >= 0; i-- {
		if orderStatus[i].VendorStatus == utils.Int2Str(dadaapi.OrderStatusCanceled) {
			continue
		}
		if orderStatus[i].VendorStatus == utils.Int2Str(dadaapi.OrderStatusFinished) || orderStatus[i].VendorStatus == utils.Int2Str(dadaapi.OrderStatusDelivering) || orderStatus[i].VendorStatus == utils.Int2Str(dadaapi.OrderStatusReturningInOrder) {
			if isMerchantCancel {
				localPrice = utils.Float64TwoInt64(dadaOrder.DeliveryFee * float64(100))
			} else {
				localPrice = 0
			}
			break
		}
		if orderStatus[i].VendorStatus == utils.Int2Str(dadaapi.OrderStatusAccepted) {
			nowTime := time.Now().Unix()
			fetchTime := orderStatus[i].StatusTime.Unix()
			timeDiffer := nowTime - fetchTime
			if timeDiffer > 15*60 || timeDiffer < 60 {
				localPrice = 0
			} else {
				localPrice = 200
			}
			break
		}
		if orderStatus[i].VendorStatus == utils.Int2Str(dadaapi.OrderStatusWaitingForAccept) {
			localPrice = 0
			break
		}
	}

	// 直接返回的 原因是,一个订单在达达发布多次运单时,QueryOrderInfo获取到的运单始终是最后一个运单的配送价格!所以直接返回算了!
	return localPrice, nil
	//// 平台状态兑换金额
	//var vendorPrice int64 = 0
	//// 未接单不扣款
	//if dadaOrder.AcceptTime == "" {
	//	vendorPrice = 0
	//}
	//
	//// 有了接单时间,订单变成了待取货
	//if dadaOrder.AcceptTime != "" && dadaOrder.FetchTime == "" {
	//	nowTime := time.Now().Unix()
	//	fetchTime := utils.Str2Time(dadaOrder.AcceptTime).Unix()
	//	timeDiffer := nowTime - fetchTime
	//	if timeDiffer > 15*60 || timeDiffer < 60 {
	//		vendorPrice = 0
	//	}
	//	vendorPrice = 200
	//}
	//
	//// fetchTime 已经有时间了,代表已经取货.次数取消扣除此订单全部金额
	//// 达达存在多个订单的运单违约金额统计在一起的情况
	//if dadaOrder.FetchTime != "" {
	//	vendorPrice = utils.Float64TwoInt64(dadaOrder.DeliveryFee * float64(100))
	//}
	//
	//if localPrice > vendorPrice {
	//	return localPrice, nil
	//}
	//return vendorPrice, nil
}

func (c *DeliveryHandler) GetPlatformBalance() (balance int64, err error) {
	return api.DadaAPI.QueryBillBalance()
}

func (c *DeliveryHandler) BalanceRecharge(param *utils.RechargeBalance) (url string, err error) {
	return api.DadaAPI.BalanceRecharge(&dadaapi.RechargeParam{
		Amount:    param.Amount,
		Category:  param.Category,
		NotifyUrl: param.NotifyUrl,
	})
}
