package dadaapi

import (
	"fmt"
	"git.rosy.net.cn/baseapi/utils"
)

const (
	ReasonIDNobodyAccept            = 1
	ReasonIDNobodyPickup            = 2
	ReasonIDCourierIsPig            = 3
	ReasonIDClientCanceled          = 4
	ReasonIDOrderIsWrong            = 5
	ReasonIDCourierWantMeCancel     = 34
	ReasonIDCourierDontWantToPickup = 35
	ReasonIDClientDontWantItAnymore = 36
	ReasonIDCourierShirk            = 37
	ReasonIDOther                   = 10000
)

const (
	OrderStatusWaitingForAccept  = 1    // 待接单
	OrderStatusAccepted          = 2    // 待取货
	OrderStatusDelivering        = 3    // 配送中
	OrderStatusFinished          = 4    // 已完成
	OrderStatusCanceled          = 5    // 已取消
	OrderStatusAssignment        = 8    // 指派单
	OrderStatusReturning         = 9    // 妥投异常之物品返回中
	OrderStatusReturningFinished = 10   // 妥投异常之物品返回完成
	OrderStatusReturningInOrder  = 100  // 骑手到店
	OrderStatusAddOrderFailed    = 1000 // ,创建达达运单失败
)

const (
	CargoTypeSnak        = 1  // 食品小吃
	CargoTypeDrink       = 2  // 饮料
	CargoTypeFlower      = 3  // 鲜花
	CargoTypePrint       = 8  // 文印票务
	CargoTypeCVS         = 9  // 便利店
	CargoTypeFresh       = 13 // 水果生鲜
	CargoTypeCityEC      = 19 // 同城电商
	CargoTypeMedicine    = 20 // 医药
	CargoTypeCake        = 21 // 蛋糕
	CargoTypeSwine       = 24 // 酒品
	CargoTypeSmallMarket = 25 // 小商品市场
	CargoTypeClothing    = 26 // 服装
	CargoTypeCarPart     = 27 // 汽修零配
	CargoTypeDigital     = 28 // 数码
	CargoTypeLobster     = 29 // 小龙虾
	CargoTypeOther       = 5  // 其他
)

type OperateOrderParams struct {
	// 以下为必要参数

	ShopNo          string  `json:"shop_no"`
	OriginID        string  `json:"origin_id"`
	CityCode        string  `json:"city_code"`
	CargoPrice      float64 `json:"cargo_price"`
	IsPrepay        int     `json:"is_prepay"`
	ReceiverName    string  `json:"receiver_name"`
	ReceiverAddress string  `json:"receiver_address"`
	ReceiverLat     float64 `json:"receiver_lat"`
	ReceiverLng     float64 `json:"receiver_lng"`
	ReceiverPhone   string  `json:"receiver_phone"`
	ReceiverTel     string  `json:"receiver_tel"`

	// 以下为可选参数

	Tips               float64 `json:"tips,omitempty"`
	Info               string  `json:"info,omitempty"`
	CargoType          int     `json:"cargo_type,omitempty"`
	CargoWeight        float64 `json:"cargo_weight,omitempty"`
	CargoNum           int     `json:"cargo_num,omitempty"`
	InvoiceTitle       string  `json:"invoice_title,omitempty"`
	OriginMark         string  `json:"origin_mark,omitempty"`
	OriginMarkNo       string  `json:"origin_mark_no,omitempty"`
	IsUseInsurance     int     `json:"is_use_insurance"`
	IsFinishCodeNeeded int     `json:"is_finish_code_needed,omitempty"`
	DelayPublishTime   int     `json:"delay_publish_time,omitempty"`
	IsDirectDelivery   int     `json:"is_direct_delivery,omitempty"`
}

type CreateOrderResponse struct {
	DeliveryNo   string  `json:"deliveryNo"`
	Distance     float64 `json:"distance"`
	Fee          float64 `json:"fee"`
	DeliverFee   float64 `json:"deliverFee"`
	CouponFee    float64 `json:"couponFee"`
	Tips         float64 `json:"tips"`
	InsuranceFee float64 `json:"insuranceFee"`
}

type CancelOrderResponse struct {
	DeductFee float64 `json:"deduct_fee"`
}

type ComplaintReason struct {
	ID     int    `json:"id"`
	Reason string `json:"reason"`
}

type OrderInfo struct {
	AcceptTime       string  `json:"acceptTime"`
	ActualFee        float64 `json:"actualFee"`
	CancelTime       string  `json:"cancelTime"`
	CreateTime       string  `json:"createTime"`
	DeductFee        float64 `json:"deductFee"`
	DeliveryFee      float64 `json:"deliveryFee"`
	Distance         float64 `json:"distance"`
	FetchTime        string  `json:"fetchTime"`
	FinishTime       string  `json:"finishTime"`
	InsuranceFee     float64 `json:"insuranceFee"`
	OrderFinishCode  string  `json:"orderFinishCode"`
	OrderID          string  `json:"orderId"`
	ReceiptURL       string  `json:"receiptUrl"`
	StatusCode       int     `json:"statusCode"`
	StatusMsg        string  `json:"statusMsg"`
	SupplierAddress  string  `json:"supplierAddress"`
	SupplierLat      string  `json:"supplierLat"`
	SupplierLng      string  `json:"supplierLng"`
	SupplierName     string  `json:"supplierName"`
	SupplierPhone    string  `json:"supplierPhone"`
	Tips             float64 `json:"tips"`
	TransporterLat   string  `json:"transporterLat"`
	TransporterLng   string  `json:"transporterLng"`
	TransporterName  string  `json:"transporterName"`
	TransporterPhone string  `json:"transporterPhone"`
}

// 订单详情查询
// http://newopen.imdada.cn/#/development/file/statusQuery?_k=7ou2o1
func (a *API) QueryOrderInfo(orderID string) (order *OrderInfo, err error) {
	params := make(map[string]interface{})
	params["order_id"] = orderID
	result, err := a.AccessAPI("api/order/status/query", params)
	if err == nil {
		err = utils.Map2StructByJson(result.Result, &order, false)
	}
	order.DeliveryFee += (utils.Int2Float64(utils.WayBillDeliveryMarkUp) / 100)
	return order, err
}

func (a *API) operateOrder(action string, orderInfo *OperateOrderParams) (retVal *CreateOrderResponse, err error) {
	params := utils.Struct2MapByJson(orderInfo)
	params["callback"] = a.callbackURL
	result, err := a.AccessAPI(action, params)
	if err == nil {
		err = utils.Map2StructByJson(result.Result, &retVal, false)
	}
	return retVal, err
}

func (a *API) AddOrder(orderInfo *OperateOrderParams) (retVal *CreateOrderResponse, err error) {
	return a.operateOrder("api/order/addOrder", orderInfo)
}

func (a *API) ReaddOrder(orderInfo *OperateOrderParams) (retVal *CreateOrderResponse, err error) {
	return a.operateOrder("api/order/reAddOrder", orderInfo)
}

func (a *API) QueryDeliverFee(orderInfo *OperateOrderParams) (retVal *CreateOrderResponse, err error) {
	return a.operateOrder("api/order/queryDeliverFee", orderInfo)
}

func (a *API) AddOrderAfterQuery(deliveryNo string) (err error) {
	_, err = a.AccessAPI("api/order/addAfterQuery", map[string]interface{}{
		"deliveryNo": deliveryNo,
	})
	return err
}

func (a *API) GetAppId() (string, string, string) {
	return a.appKey, a.appSecret, a.sourceID
}

func (a *API) CancelOrder(thirdPartOrderID string, cancelOrderReasonId int, cancelOrderReason string) (retVal *CancelOrderResponse, err error) {
	mapData := utils.Params2Map("order_id", thirdPartOrderID, "cancel_reason_id", cancelOrderReasonId, "cancel_reason", cancelOrderReason)
	result, err := a.AccessAPI("api/order/formalCancel", mapData)
	if err != nil {
		return nil, err
	}
	mapResult := result.Result.(map[string]interface{})
	retVal = new(CancelOrderResponse)
	retVal.DeductFee = utils.MustInterface2Float64(mapResult["deduct_fee"])
	return retVal, nil
}

//获取投诉原因
func (a *API) GetComplaintReasons() (complaintReasonList []*ComplaintReason, err error) {
	result, err := a.AccessAPI("api/complaint/reasons", nil)
	if err != nil {
		return nil, err
	}
	for _, v := range result.Result.([]interface{}) {
		mapResult := v.(map[string]interface{})
		complaintReason := &ComplaintReason{}
		err = utils.Map2StructByJson(mapResult, complaintReason, false)
		complaintReasonList = append(complaintReasonList, complaintReason)
	}
	return complaintReasonList, nil
}

//投诉骑手
func (a *API) ComplaintRider(orderID string, resonID int) (err error) {
	mapData := utils.Params2Map("order_id", orderID, "reason_id", resonID)
	_, err = a.AccessAPI("api/complaint/dada", mapData)
	return err
}

// 获取投诉列表
func (a *API) ComplaintList() {
	data, err := a.AccessAPI("api/complaint/reasons", nil)
	fmt.Println(data)
	fmt.Println(err)
}

// 增加小费
// http://newopen.imdada.cn/#/development/file/addTip?_k=5yerib
func (a *API) AddTip(orderID string, tips float64, cityCode, info string) (err error) {
	mapData := map[string]interface{}{
		"order_id":  orderID,
		"tips":      tips,
		"city_code": cityCode,
	}
	if info != "" {
		mapData["info"] = info
	}
	_, err = a.AccessAPI("api/order/addTip", mapData)
	return err
}
