package sfps2

import (
	"encoding/json"
	"errors"
	"fmt"
	"git.rosy.net.cn/baseapi/utils"
	"time"
)

// PreCreateOrder 预创建订单（店铺）
func (a *API) PreCreateOrder(preOrder *PreCreateOrderReq) (price float64, err error) {
	//补全默认参数
	preOrder.PushTime = time.Now().Unix()
	preOrder.DevId = a.devId

	//preOrder.ShopId = SFShopTestOpenStoreID // 测试用

	resp := a.HttpPostJson("precreateorder", preOrder)
	if resp == nil {
		return 0, fmt.Errorf("PreCreateOrder请求异常")
	}
	if resp.HttpStatusCode != HttpStatusSuccessCode {
		return 0, errors.New("HTTP请求错误，请检查重试")
	}
	if resp.BaseRetVal.ErrorCode != SuccessCode {
		return 0, fmt.Errorf("%s", resp.BaseRetVal.ErrorMsg)
	}
	temp := resp.BaseRetVal.Result.(map[string]interface{})
	temp1 := temp["charge_price_list"].(map[string]interface{})
	return temp1["shop_pay_price"].(float64), nil

}

// CreateOrder 创建订单（店铺）
func (a *API) CreateOrder(order *CreateOrderReq) (sfOrderID, sfBillID string, totalPrice, reallyPayPrice float64, err error) {
	//补全默认参数
	order.PushTime = time.Now().Unix()
	order.Version = DefaultVersion
	order.DevId = a.devId

	//order.ShopId = SFShopTestOpenStoreID // 测试用

	resp := a.HttpPostJson("createorder", order)
	if resp == nil {
		return "", "", 0, 0, fmt.Errorf("CreateOrder请求异常")
	}
	if resp.HttpStatusCode != HttpStatusSuccessCode {
		return "", "", 0, 0, errors.New("HTTP请求错误，请检查重试")
	}
	if resp.BaseRetVal.ErrorCode != SuccessCode {
		return "", "", 0, 0, fmt.Errorf("%s", resp.BaseRetVal.ErrorMsg)
	}
	retVal := CreateOrderResp{}
	s, _ := json.Marshal(resp.BaseRetVal.Result)
	if err = json.Unmarshal(s, &retVal); err == nil {
		return retVal.SFOrderID, retVal.SFBillID, retVal.TotalPrice, retVal.RealPayMoney, nil
	} else {
		return "", "", 0, 0, err
	}
}

// PreCancelOrder 预取消订单
func (a *API) PreCancelOrder(sfOrderID string) (deductionFee float64, err error) {
	param := PreCancelOrderReq{
		DevId:    a.devId,
		OrderID:  sfOrderID,
		PushTime: time.Now().Unix(),
	}
	resp := a.HttpPostJson("precancelorder", param)
	if resp == nil {
		return 0, fmt.Errorf("PreCancelOrder请求异常")
	}
	if resp.HttpStatusCode != HttpStatusSuccessCode {
		return 0, errors.New("HTTP请求错误，请检查重试")
	}
	if resp.BaseRetVal.ErrorCode != SuccessCode {
		return 0, fmt.Errorf("%s", resp.BaseRetVal.ErrorMsg)
	}
	retVal := PreCancelOrderResp{}
	s, _ := json.Marshal(resp.BaseRetVal.Result)
	if err = json.Unmarshal(s, &retVal); err == nil {
		return retVal.DeductionFee, nil
	} else {
		return 0, err
	}
}

// CancelOrder 取消订单
func (a *API) CancelOrder(sfOrderID string) (err error) {
	param := &CancelOrderReq{
		DevId:      a.devId,
		OrderID:    sfOrderID,
		PushTime:   time.Now().Unix(),
		CancelCode: CancelCodeChangePlan,
	}
	resp := a.HttpPostJson("cancelorder", param)
	if resp == nil {
		return fmt.Errorf("CancelOrder请求异常")
	}
	if resp.HttpStatusCode != HttpStatusSuccessCode {
		return errors.New("HTTP请求错误，请检查重试")
	}
	if resp.BaseRetVal.ErrorCode != SuccessCode {
		return fmt.Errorf("%s", resp.BaseRetVal.ErrorMsg)
	}
	return nil
}

// GetOrderStatus 订单实时信息查询
func (a *API) GetOrderStatus(sfOrderID string) (retVal *GetOrderStatusResp, err error) {
	param := &GetOrderStatusReq{
		DevId:    a.devId,
		OrderID:  sfOrderID,
		PushTime: time.Now().Unix(),
		//OrderType: orderType,
	}
	resp := a.HttpPostJson("getorderstatus", param)
	if resp == nil {
		return nil, fmt.Errorf("GetOrderStatus请求异常")
	}
	if resp.HttpStatusCode != HttpStatusSuccessCode {
		return nil, errors.New("HTTP请求错误，请检查重试")
	}
	if resp.BaseRetVal.ErrorCode != SuccessCode {
		return nil, fmt.Errorf("%s", resp.BaseRetVal.ErrorMsg)
	}
	s, _ := json.Marshal(resp.BaseRetVal.Result)
	if err = json.Unmarshal(s, &retVal); err == nil {
		retVal.TotalPrice += utils.Int2Float64(utils.WayBillDeliveryMarkUp)
		return retVal, nil
	} else {
		return nil, err
	}
}

// GetRiderLatestPosition 获取骑手实时坐标
func (a *API) GetRiderLatestPosition(sfOrderID string) (retVal *RiderLatestPositionResp, err error) {
	param := &RiderLatestPositionReq{
		DevId:     a.devId,
		OrderID:   sfOrderID,
		PushTime:  time.Now().Unix(),
		OrderType: OrderTypeSF, //暂时默认
	}
	resp := a.HttpPostJson("riderlatestposition", param)
	if resp == nil {
		return nil, fmt.Errorf("GetRiderLatestPosition请求异常")
	}
	if resp.HttpStatusCode != HttpStatusSuccessCode {
		return nil, errors.New("HTTP请求错误，请检查重试")
	}
	if resp.BaseRetVal.ErrorCode != SuccessCode {
		return nil, fmt.Errorf("%s", resp.BaseRetVal.ErrorMsg)
	}
	s, _ := json.Marshal(resp.BaseRetVal.Result)
	if err = json.Unmarshal(s, &retVal); err == nil {
		return retVal, nil
	} else {
		return nil, err
	}
}

// 添加小费
func (a *API) AddTipFee(deliveryId string, fee int64) error {
	param := &Addordergratuityfee{
		DevId:        a.devId,
		OrderId:      deliveryId,
		PushTime:     time.Now().Unix(),
		GratuityFee:  fee,
		OrderType:    0,
		ShopId:       0,
		ShopType:     0,
		serialNumber: "",
	}
	resp := a.HttpPostJson("addordergratuityfee", param)
	if resp == nil {
		return fmt.Errorf("AddTipFee请求异常")
	}
	if resp.HttpStatusCode != HttpStatusSuccessCode {
		return errors.New("HTTP请求错误，请检查重试")
	}
	if resp.BaseRetVal.ErrorCode != SuccessCode {
		return fmt.Errorf("%s", resp.BaseRetVal.ErrorMsg)
	}
	var retVal *AddordergratuityfeeResp
	s, _ := json.Marshal(resp.BaseRetVal.Result)
	if err := json.Unmarshal(s, &retVal); err == nil {
		return nil
	} else {
		return err
	}
}

// 获取运单小费
func (a *API) QueryTipFee(sfOrderId string) (int64, error) {
	resp := a.HttpPostJson("getordergratuityfee", map[string]interface{}{
		"dev_id":    a.devId,
		"order_id":  sfOrderId,
		"push_time": time.Now().Unix()},
	)
	if resp == nil {
		return 0, fmt.Errorf("QueryTipFee请求异常")
	}
	if resp.HttpStatusCode != HttpStatusSuccessCode {
		return 0, errors.New("HTTP请求错误，请检查重试")
	}
	if resp.BaseRetVal.ErrorCode != SuccessCode {
		return 0, fmt.Errorf("%s", resp.BaseRetVal.ErrorMsg)
	}
	var retVal *QueryOrderTipFee
	s, _ := json.Marshal(resp.BaseRetVal.Result)
	if err := json.Unmarshal(s, &retVal); err == nil {
		return retVal.TotalGratuityFee, nil
	} else {
		return 0, err
	}
}

type QueryOrderTipFee struct {
	SfOrderId          string      //顺丰订单号，新版本V1.9+升级为JS开头的15位字符串类型, 老版本为int类型
	ShopOrderId        string      //商家订单号
	TotalGratuityFee   int64       //该订单总的加小费金额
	TotalGratuityTimes int64       //该订单总的加小费次数
	GratuityFeeList    interface{} // 加小费列表，未加则是空数组
	PushTime           string      //推送时间
}
