package pposRequest

import (
	"PPOSUtils/utils"
	"errors"
	"log"
	"net/url"
	"time"
)

//参数：子系统ID
func (that *PPOSClient) NewRefundCreateRequest(sysID int64, businessType int64) (*RefundCreateRequest, error) {
	switch sysID {
	case 11:
		return that.NewMemberRefundCreateRequest(), nil //会员
	case 12:
		return that.NewTicketRefundCreateRequest(), nil //门票
	case 13:
		return that.NewFieldRefundCreateRequest(), nil //场地
	case 14:
		return that.NewGoodsRefundCreateRequest(), nil //商品
	case 15:
		return that.NewCosRefundCreateRequest(), nil //通用收款
	case 16:
		return that.NewEventsRefundCreateRequest(), nil //赛事
	case 17:
		if businessType == 1702 || businessType == 1706 || businessType == 1708 {
			return that.NewCourseRefundCreateRequest(), nil //课程、续课
		}
		if businessType == 1704 {
			return that.NewClassRefundCreateRequest(), nil //课时
		}
		return nil, errors.New("not this businessType")
	case 18:
		return that.NewLeaseRefundCreateRequest(), nil //租赁
	case 20:
		return that.NewJointgoodsRefundCreateRequest(), nil //组合产品
	case 30:
		return that.NewActivityRefundCreateRequest(), nil //活动平台
	case 40:
		return that.NewMmpCashOrderRefundCreateRequest(), nil //会员中台
	default:
		return nil, errors.New("not this type request")
	}
}

//退单创建（门票订单）
func (that *PPOSClient) NewTicketRefundCreateRequest() *RefundCreateRequest {
	return &RefundCreateRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/ticket/orderRefund/refundCreate",
		},
		SysID: 12,
		bT:    time.Now(),
	}
}

//退单创建（组合产品订单）
func (that *PPOSClient) NewJointgoodsRefundCreateRequest() *RefundCreateRequest {
	return &RefundCreateRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/marketing/orderRefund/refundCreate",
		},
		SysID: 12,
		bT:    time.Now(),
	}
}

//退单创建（通用收款订单）
func (that *PPOSClient) NewCosRefundCreateRequest() *RefundCreateRequest {
	return &RefundCreateRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/cos/orderRefund/refundCreate",
		},
		SysID: 15,
		bT:    time.Now(),
	}
}

//退单创建 (商品订单)
func (that *PPOSClient) NewGoodsRefundCreateRequest() *RefundCreateRequest {
	return &RefundCreateRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/goods/goodsOrder/refundCreate",
		},
		SysID: 14,
		bT:    time.Now(),
	}
}

//退单创建（场地订单）
func (that *PPOSClient) NewFieldRefundCreateRequest() *RefundCreateRequest {
	return &RefundCreateRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/field/orderRefund/refundCreate",
		},
		SysID: 13,
		bT:    time.Now(),
	}
}

//退单创建（会员订单）
func (that *PPOSClient) NewMemberRefundCreateRequest() *RefundCreateRequest {
	return &RefundCreateRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/cardWork/memberCard/refundCreate",
		},
		SysID: 11,
		bT:    time.Now(),
	}
}

//退单创建 (赛事订单)
func (that *PPOSClient) NewEventsRefundCreateRequest() *RefundCreateRequest {
	return &RefundCreateRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/events/contestOrder/refundCreate",
		},
		publicParamsSlice: []string{
			"parent_order_no",
			"order_no",
		},
		SysID: 16,
		bT:    time.Now(),
	}
}

//退单创建 (培训课时订单)
func (that *PPOSClient) NewClassRefundCreateRequest() *RefundCreateRequest {
	return &RefundCreateRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/class/classOrder/refundCreate",
		},
		publicParamsSlice: []string{
			"parent_order_no",
			"order_no",
		},
		SysID: 17,
		bT:    time.Now(),
	}
}

//退单创建 (培训课程订单)
func (that *PPOSClient) NewCourseRefundCreateRequest() *RefundCreateRequest {
	return &RefundCreateRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/class/courseOrder/refundCreate",
		},
		publicParamsSlice: []string{
			"parent_order_no",
			"order_no",
		},
		SysID: 17,
		bT:    time.Now(),
	}
}

//退单创建 (租赁订单)
func (that *PPOSClient) NewLeaseRefundCreateRequest() *RefundCreateRequest {
	return &RefundCreateRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/lease/orderRefund/refundCreate",
		},
		publicParamsSlice: []string{
			"parent_order_no",
			"order_no",
		},
		SysID: 18,
		bT:    time.Now(),
	}
}

//退单创建 (活动平台皮卡订单)
func (that *PPOSClient) NewActivityRefundCreateRequest() *RefundCreateRequest {
	return &RefundCreateRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/activityPlatform/activity/applyOrderRefundCreate",
		},
		publicParamsSlice: []string{
			"parent_order_no",
			"order_no",
		},
		SysID: 18,
		bT:    time.Now(),
	}
}

//退单创建 (会员中台充值订单)
func (that *PPOSClient) NewMmpCashOrderRefundCreateRequest() *RefundCreateRequest {
	return &RefundCreateRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/memberMiddlePlatform/cashOrder/refundCreate",
		},
		publicParamsSlice: []string{
			"parent_order_no",
			"order_no",
		},
		SysID: 18,
		bT:    time.Now(),
	}
}

//
type RefundCreateRequest struct {
	Request
	SysID             int64     //
	publicParamsSlice []string  //必传参数名
	bT                time.Time //耗时时间
}

func (that *RefundCreateRequest) SetParentOrderNo(value string) *RefundCreateRequest {
	that.initParams()
	that.params.Set("parent_order_no", value) //（订单中心的退单总单），唯一
	return that
}
func (that *RefundCreateRequest) SetOrderNo(value string) *RefundCreateRequest {
	that.initParams()
	that.params.Set("order_no", value) //退单新订单号(业务子系统的订单号)，唯一
	return that
}
func (that *RefundCreateRequest) SetRefundOrderNo(value string) *RefundCreateRequest {
	that.initParams()
	that.params.Set("refund_order_no", value) //需要退单的原订单号(业务子系统的订单号)，唯一
	return that
}
func (that *RefundCreateRequest) SetSysID(value int64) *RefundCreateRequest {
	that.initParams()
	that.params.Set("sys_id", utils.ToString(value)) //业务子系统id
	return that
}
func (that *RefundCreateRequest) SetSkuItems(value string) *RefundCreateRequest {
	that.initParams()
	that.params.Set("sku_items", value) //需要退单的sku,格式sku:num:code-code,若多个，用逗号拼接,即sku:num:code-code,sku:num:code-code,sku:num:code-code
	return that
}
func (that *RefundCreateRequest) SetHandleInfo(value string) *RefundCreateRequest {
	that.initParams()
	that.params.Set("handle_info", value) //扩展备注，json格式 {"reason":"原因"}
	return that
}
func (that *RefundCreateRequest) SetPayScene(value string) *RefundCreateRequest {
	that.initParams()
	that.params.Set("pay_scene", value) //支付场景（wx、bs）
	return that
}
func (that *RefundCreateRequest) SetIsNoServiceFee(value int64) *RefundCreateRequest {
	that.initParams()
	that.params.Set("is_no_service_fee", utils.ToString(value))
	return that
}
func (that *RefundCreateRequest) SetRefundFrom(value int64) *RefundCreateRequest {
	that.initParams()
	that.params.Set("refund_from", utils.ToString(value))
	return that
}

//Params ...
func (that *RefundCreateRequest) Params() (url.Values, error) {
	that.initParams()
	_params := that.params
	//
	for _, _v := range that.publicParamsSlice {
		if _params.Get(_v) == "" {
			return nil, errors.New(that.apiAddress + "缺少参数:" + _v)
		}
	}
	return _params, nil
}

//
type OrderRefund struct {
	ParentOrderNo    string `json:"parent_order_no"`
	OrderNo          string `json:"order_no"`
	SrcOrderNo       string `json:"src_order_no"`
	SrcPayPrice      int64  `json:"src_pay_price"`
	RefundTotalPrice int64  `json:"refund_total_price"`
	HandTotalPrice   int64  `json:"hand_total_price"`
	OrderStatus      int64  `json:"order_status"`
	RefundTime       int64  `json:"refund_time"`
	Reason           string `json:"reason"`
}
type OrderItemRefund struct {
	OrderNo     string `json:"order_no"`
	OrderItemNo string `json:"order_item_no"`
	Sku         string `json:"sku"`
	SkuName     string `json:"sku_name"`
	SkuInfo     string `json:"sku_info"`
	SkuImg      string `json:"sku_img"`
	SkuNum      int64  `json:"sku_num"`
	SkuPrice    int64  `json:"sku_price"`
	//BackSubtotalCount int64  `json:"back_subtotal_count"`
	SrcPayPrice      int64 `json:"src_pay_price"`
	SalePrice        int64 `json:"sale_price"`
	ItemPrice        int64 `json:"item_price"`
	PayPrice         int64 `json:"pay_price"`
	RefundNum        int64 `json:"refund_num"`
	RefundTotalPrice int64 `json:"refund_total_price"`
	HandTotalPrice   int64 `json:"hand_total_price"`
	CodeList         []*CodeList
}
type CodeList struct {
	Code        string `json:"code"`
	HandPrice   int64  `json:"hand_price"`
	RefundPrice int64  `json:"refund_price"`
	CanRefund   bool   `json:"can_refund"`
}
type RefundCreateResponse struct {
	OrderRefund     *OrderRefund
	OrderItemRefund []*OrderItemRefund
}

//Do ...
func (that *RefundCreateRequest) Do() (*RefundCreateResponse, error) {
	//返回data
	_data, _err := that.Client.GetData(that.apiAddress, that)
	log.Println(that.apiAddress+" 耗时: ", time.Since(that.bT))
	if _err != nil {
		return nil, _err
	}
	_mp, _ok := _data.(map[string]interface{})
	if !_ok {
		return nil, errors.New(that.apiAddress + "请求响应格式不正确,错误代码01")
	}
	_slice := []string{"order", "item"}
	for _, _v := range _slice {
		if _, _ok := _mp[_v]; !_ok {
			return nil, errors.New(that.apiAddress + "请求响应格式不正确,错误代码02")
		}
	}
	//返回结果
	_rs := new(RefundCreateResponse)
	//
	_orderInfo := new(OrderRefund)
	if _err := that.ParseResponeMp(_orderInfo, _mp["order"]); _err != nil {
		return nil, errors.New(that.apiAddress + "请求响应格式化异常3:" + _err.Error())
	}
	_rs.OrderRefund = _orderInfo
	//
	_itemData, _ok := _mp["item"].([]interface{})
	if !_ok {
		return nil, errors.New(that.apiAddress + "请求响应格式不正确,错误代码01")
	}
	_itemSlice := []*OrderItemRefund{}
	for _k, _v := range _itemData {
		_item := new(OrderItemRefund)
		if _err := that.ParseResponeMp(_item, _v); _err != nil {
			return nil, errors.New(that.apiAddress + "请求响应格式化异常:" + _err.Error())
		}
		_itemSlice = append(_itemSlice, _item)
		_itemSlice[_k].CodeList = []*CodeList{}
		//
		if _value, _ok := _v.(map[string]interface{}); _ok {
			if _codeList, _ok := _value["code_list"].([]interface{}); _ok {
				for _, _v1 := range _codeList {
					_codeValue := new(CodeList)
					if _err := that.ParseResponeMp(_codeValue, _v1); _err != nil {
						return nil, errors.New(that.apiAddress + "请求响应格式化异常:" + _err.Error())
					}
					_itemSlice[_k].CodeList = append(_itemSlice[_k].CodeList, _codeValue)
				}
			}
		}
	}
	_rs.OrderItemRefund = _itemSlice
	//
	return _rs, nil
}
