package weimobapi

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

const (
	OrderStatusWait4Pay   = 0 // 待支付
	OrderStatusPayed      = 1 // 已付款，待发货
	OrderStatusDelivering = 2 // 已发货
	OrderStatusFinished   = 3 // 已完成
	OrderStatusCanceled   = 4 // 已取消
)

const (
	QueryOrdersListPageSize = 10
)

type DeliveryOrderItem struct {
	ItemID int64 `json:"itemId"`
	SkuID  int64 `json:"skuId"`
	SkuNum int   `json:"skuNum"`
}

type DeliveryOrder struct {
	OrderNo               int64                `json:"orderNo"`
	DeliveryNo            string               `json:"deliveryNo"`
	DeliveryCompanyCode   string               `json:"deliveryCompanyCode"`
	DeliveryCompanyName   string               `json:"deliveryCompanyName"`
	IsNeedLogistics       bool                 `json:"isNeedLogistics"`
	IsSplitPackage        bool                 `json:"isSplitPackage"`
	DeliveryRemark        string               `json:"deliveryRemark"`
	DeliveryOrderItemList []*DeliveryOrderItem `json:"deliveryOrderItemList"`
}

type OrderDetail struct {
	AutoCancelTime int `json:"autoCancelTime"`
	BizInfo        struct {
		BizType     int    `json:"bizType"`
		BizTypeName string `json:"bizTypeName"`
	} `json:"bizInfo"`
	BizSourceType int `json:"bizSourceType"`
	BuyerInfo     struct {
		UserNickname string `json:"userNickname"`
		Wid          int    `json:"wid"`
	} `json:"buyerInfo"`
	BuyerRemark     string  `json:"buyerRemark"`
	ChannelTypeName string  `json:"channelTypeName"`
	CreateTime      int64   `json:"createTime"`
	DeliveryAmount  float64 `json:"deliveryAmount"`
	DeliveryDetail  struct {
		DeliveryType            int    `json:"deliveryType"`
		DeliveryTypeName        string `json:"deliveryTypeName"`
		LogisticsDeliveryDetail struct {
			ExpectDeliveryTime string        `json:"expectDeliveryTime"`
			ExpectDeliveryType int           `json:"expectDeliveryType"`
			LogisticsOrderList []interface{} `json:"logisticsOrderList"`
			ReceiverAddress    string        `json:"receiverAddress"`
			ReceiverArea       string        `json:"receiverArea"`
			ReceiverCity       string        `json:"receiverCity"`
			ReceiverCounty     string        `json:"receiverCounty"`
			ReceiverLatitude   string        `json:"receiverLatitude"`
			ReceiverLongitude  string        `json:"receiverLongitude"`
			ReceiverMobile     string        `json:"receiverMobile"`
			ReceiverName       string        `json:"receiverName"`
			ReceiverProvince   string        `json:"receiverProvince"`
			ReceiverZip        string        `json:"receiverZip"`
		} `json:"logisticsDeliveryDetail"`
	} `json:"deliveryDetail"`
	DeliveryPaymentAmount float64 `json:"deliveryPaymentAmount"`
	DiscountInfo          struct {
		MerchantDiscountAmount int `json:"merchantDiscountAmount"`
	} `json:"discountInfo"`
	EnableDelivery  int  `json:"enableDelivery"`
	ExistingInvoice bool `json:"existingInvoice"`
	ExpandLabelInfo struct {
		VirtualWid bool `json:"virtualWid"`
	} `json:"expandLabelInfo"`
	GoodsAmount        float64 `json:"goodsAmount"`
	GoodsPromotionInfo struct {
		CycleOrderInfo struct {
			CyclePackageList []interface{} `json:"cyclePackageList"`
		} `json:"cycleOrderInfo"`
		GoodsDistributionType int `json:"goodsDistributionType"`
		PromotionType         int `json:"promotionType"`
	} `json:"goodsPromotionInfo"`
	GoodsSellMode   int `json:"goodsSellMode"`
	GoodsSourceType int `json:"goodsSourceType"`
	GuideInfo       struct {
		GoodsGuideType int `json:"goodsGuideType"`
	} `json:"guideInfo"`
	InvoiceTexAmount         int `json:"invoiceTexAmount"`
	InvoiceTexDiscountAmount int `json:"invoiceTexDiscountAmount"`
	InvoiceTexPaymentAmount  int `json:"invoiceTexPaymentAmount"`
	ItemList                 []struct {
		BaseDiscountInfo struct {
		} `json:"baseDiscountInfo"`
		BizInfo struct {
		} `json:"bizInfo"`
		CostPrice         float64 `json:"costPrice"`
		GoodsDiscountInfo struct {
		} `json:"goodsDiscountInfo"`
		GoodsCode           string  `json:"goodsCode"`
		GoodsID             int64   `json:"goodsId"`
		GoodsSellMode       int     `json:"goodsSellMode"`
		GoodsSourceType     int     `json:"goodsSourceType"`
		GoodsTitle          string  `json:"goodsTitle"`
		GoodsType           int     `json:"goodsType"`
		HadDeliveryItemNum  int     `json:"hadDeliveryItemNum"`
		ID                  int     `json:"id"`
		ImageURL            string  `json:"imageUrl"`
		OriginalPrice       float64 `json:"originalPrice"`
		PaymentAmount       float64 `json:"paymentAmount"`
		PointDeductRatio    int     `json:"pointDeductRatio"`
		Price               float64 `json:"price"`
		PrimaryCategory     string  `json:"primaryCategory"`
		SecondaryCategory   string  `json:"secondaryCategory"`
		ShouldPaymentAmount float64 `json:"shouldPaymentAmount"`
		SkuAmount           float64 `json:"skuAmount"`
		SkuCode             string  `json:"skuCode"`
		SkuID               int64   `json:"skuId"`
		SkuNum              int     `json:"skuNum"`
		TagInfo             struct {
			ActivityTag []interface{} `json:"activityTag"`
			GoodsBizTag []interface{} `json:"goodsBizTag"`
		} `json:"tagInfo"`
		TotalAmount   float64 `json:"totalAmount"`
		WarehouseID   int     `json:"warehouseId"`
		WarehouseName string  `json:"warehouseName"`
		WarehouseType int     `json:"warehouseType"`
	} `json:"itemList"`
	MerchantInfo struct {
		MerchantTitle     string `json:"merchantTitle"`
		Pid               int64  `json:"pid"`
		ProcessStoreID    int    `json:"processStoreId"`
		ProcessStoreTitle string `json:"processStoreTitle"`
		StoreID           int    `json:"storeId"`
		StoreTitle        string `json:"storeTitle"`
	} `json:"merchantInfo"`
	OperationList []struct {
		Name           string `json:"name"`
		OperationType  int    `json:"operationType"`
		PermissionCode string `json:"permissionCode"`
	} `json:"operationList"`
	OrderNo         int64   `json:"orderNo"`
	OrderStatus     int     `json:"orderStatus"`
	OrderStatusName string  `json:"orderStatusName"`
	OrderType       int     `json:"orderType"`
	PaymentAmount   float64 `json:"paymentAmount"`
	PaymentInfo     struct {
		PaymentStatus   int    `json:"paymentStatus"`
		PaymentType     int    `json:"paymentType"`
		PaymentTypeName string `json:"paymentTypeName"`
	} `json:"paymentInfo"`
	ProcessStoreID      int     `json:"processStoreId"`
	ProcessStoreTitle   string  `json:"processStoreTitle"`
	ShouldPaymentAmount float64 `json:"shouldPaymentAmount"`
	StoreTitle          string  `json:"storeTitle"`
	TotalAmount         float64 `json:"totalAmount"`
	TransferStatus      int     `json:"transferStatus"`
	TransferType        int     `json:"transferType"`
	UpdateTime          int64   `json:"updateTime"`
}

type QueryOrdersListParam struct {
	PageNum        int                              `json:"pageNum"`
	PageSize       int                              `json:"pageSize"`
	EcBizStoreId   int64                            `json:"ecBizStoreId,omitempty"`
	QueryParameter *MerchantOrderListQueryParameter `json:"queryParameter,omitempty"`
}

type MerchantOrderListQueryParameter struct {
	CreateStartTime        int64 `json:"createStartTime,omitempty"`        //下单起始时间
	CreateEndTime          int64 `json:"createEndTime,omitempty"`          //下单结束时间
	UpdateStartTime        int64 `json:"updateStartTime,omitempty"`        //更新开始时间
	UpdateEndTime          int64 `json:"updateEndTime,omitempty"`          //更新结束时间
	OrderTypes             []int `json:"orderTypes,omitempty"`             //订单类型： 1、B2C订单 99、充值订单 97、直接消费订单 不传默认为 1 (建议只传一种类型)
	OrderStatuses          []int `json:"orderStatuses"`                    //订单状态 (空为不限,0-待支付,1-待发货,2-已发货,3-已完成,4-已取消)
	ChannelTypes           []int `json:"channelTypes"`                     //渠道类型 (空为不限,0-公众号,1-小程序,2-H5,3-QQ,4-微博,5-头条,6-支付宝,7-线下)
	DeliveryStatuses       []int `json:"deliveryStatuses"`                 //发货状态 (空为不限,0未发货，1为部分发货，2为已发货)
	PaymentTypes           []int `json:"paymentTypes"`                     //支付类型(空为不限,1-线上支付（包括微信、支付宝、银行卡、购物卡等）,2-线下支付（包括现金、欠条等，默认是现金）,3-混合支付（网上支付和线下支付混合）)
	PaymentMethods         []int `json:"paymentMethods"`                   //支付方式 (空为不限,1-支付宝,2-微信,3-银行卡,4-现金,5-货到付款,6-无需支付)
	DeliveryTypes          []int `json:"deliveryTypes"`                    //配送类型 (空为不限,1-物流配送(走快递发货流程),2-同城限时达（走即时物流流程）,3-到店自提（走自提流程）)
	FlagRanks              []int `json:"flagRanks"`                        //订单标记 (空为不限,等级1到5)
	BizTypes               []int `json:"bizTypes"`                         //业务类型 (空为不限,0-普通,3-限时折扣,4-砍价, 5-拼团)
	GoodsDistributionTypes []int `json:"goodsDistributionTypes,omitempty"` //分销类型：1、普通商品，2、分销商品
	TransferStatus         int   `json:"transferStatus,omitempty"`         //转单状态 : 0未转单,1已转单,2转单失败 不传代表全部
	GoodsPromotionTypes    []int `json:"goodsPromotionTypes	,omitempty"`   //商品销售类型，1为普通，2为周期购，3、积分订单
}

type OrderInfo struct {
	BizOrderID          string             `json:"bizOrderId"`
	BizType             int                `json:"bizType"`
	BuyerRemark         string             `json:"buyerRemark"`
	ChannelType         int                `json:"channelType"`
	ChannelTypeName     string             `json:"channelTypeName"`
	ConfirmReceivedTime interface{}        `json:"confirmReceivedTime"`
	CreateTime          int64              `json:"createTime"`
	DeliveryAmount      float64            `json:"deliveryAmount"`
	DeliveryOrderID     interface{}        `json:"deliveryOrderId"`
	DeliveryTime        interface{}        `json:"deliveryTime"`
	DeliveryType        int                `json:"deliveryType"`
	DeliveryTypeName    string             `json:"deliveryTypeName"`
	EnableDelivery      int                `json:"enableDelivery"`
	ExpectDeliveryTime  string             `json:"expectDeliveryTime"`
	FlagContent         interface{}        `json:"flagContent"`
	FlagRank            interface{}        `json:"flagRank"`
	GoodsAmount         float64            `json:"goodsAmount"`
	GoodsPromotionInfo  GoodsPromotionInfo `json:"goodsPromotionInfo"`
	ItemList            []ItemList         `json:"itemList"`
	OrderNo             int64              `json:"orderNo"`
	OrderStatus         int                `json:"orderStatus"`
	OrderStatusName     string             `json:"orderStatusName"`
	PaymentAmount       float64            `json:"paymentAmount"`
	PaymentMethodName   string             `json:"paymentMethodName"`
	PaymentStatus       int                `json:"paymentStatus"`
	PaymentTime         interface{}        `json:"paymentTime"`
	PaymentType         int                `json:"paymentType"`
	PaymentTypeName     string             `json:"paymentTypeName"`
	Pid                 int64              `json:"pid"`
	ProcessStoreID      int                `json:"processStoreId"`
	ProcessStoreTitle   string             `json:"processStoreTitle"`
	ReceiverAddress     string             `json:"receiverAddress"`
	ReceiverArea        string             `json:"receiverArea"`
	ReceiverCity        string             `json:"receiverCity"`
	ReceiverCounty      string             `json:"receiverCounty"`
	ReceiverMobile      string             `json:"receiverMobile"`
	ReceiverName        string             `json:"receiverName"`
	ReceiverProvince    string             `json:"receiverProvince"`
	SelfPickupSiteName  interface{}        `json:"selfPickupSiteName"`
	SelfPickupStatus    interface{}        `json:"selfPickupStatus"`
	StoreID             int                `json:"storeId"`
	StoreTitle          string             `json:"storeTitle"`
	SubBizType          interface{}        `json:"subBizType"`
	TotalPoint          interface{}        `json:"totalPoint"`
	TransferFailReason  interface{}        `json:"transferFailReason"`
	TransferStatus      int                `json:"transferStatus"`
	TransferType        int                `json:"transferType"`
	UpdateTime          int64              `json:"updateTime"`
	UserNickname        string             `json:"userNickname"`
	Wid                 int                `json:"wid"`
}
type CycleOrderInfo struct {
	CurrentCycleNum   interface{} `json:"currentCycleNum"`
	CycleDeliveryTime interface{} `json:"cycleDeliveryTime"`
	CycleItemList     interface{} `json:"cycleItemList"`
	CyclePackageList  interface{} `json:"cyclePackageList"`
	CycleSize         interface{} `json:"cycleSize"`
	CycleType         interface{} `json:"cycleType"`
	CycleTypeName     interface{} `json:"cycleTypeName"`
	FirstTime         interface{} `json:"firstTime"`
}
type GoodsPromotionInfo struct {
	CycleOrderInfo        CycleOrderInfo `json:"cycleOrderInfo"`
	GoodsDistributionType interface{}    `json:"goodsDistributionType"`
	PromotionID           interface{}    `json:"promotionId"`
	PromotionOrderID      interface{}    `json:"promotionOrderId"`
	PromotionType         int            `json:"promotionType"`
}
type BaseDiscountInfo struct {
	BalanceDiscountAmount         interface{} `json:"balanceDiscountAmount"`
	BalanceDiscountDeliveryAmount interface{} `json:"balanceDiscountDeliveryAmount"`
	CouponCodeDiscountAmount      interface{} `json:"couponCodeDiscountAmount"`
	CouponCodeDiscountInfo        interface{} `json:"couponCodeDiscountInfo"`
	CouponDiscountAmount          interface{} `json:"couponDiscountAmount"`
	CouponDiscountInfo            interface{} `json:"couponDiscountInfo"`
	DeliveryUsedPoints            interface{} `json:"deliveryUsedPoints"`
	MemberPointsDiscountAmount    interface{} `json:"memberPointsDiscountAmount"`
	MembershipDiscountAmount      interface{} `json:"membershipDiscountAmount"`
	MembershipDiscountInfo        interface{} `json:"membershipDiscountInfo"`
	MerchantDiscountAmount        interface{} `json:"merchantDiscountAmount"`
	NynjDiscountAmount            interface{} `json:"nynjDiscountAmount"`
	PointsDiscountDeliveryAmount  interface{} `json:"pointsDiscountDeliveryAmount"`
	PromotionDiscountAmount       int         `json:"promotionDiscountAmount"`
	UsedMemberPoints              interface{} `json:"usedMemberPoints"`
}
type BizInfo struct {
	BizID      interface{} `json:"bizId"`
	BizOrderID interface{} `json:"bizOrderId"`
	BizType    interface{} `json:"bizType"`
	SubBizType interface{} `json:"subBizType"`
}
type TagInfo struct {
	ActivityTag             interface{}   `json:"activityTag"`
	AdvancedActivityTagList interface{}   `json:"advancedActivityTagList"`
	AllActivityTagList      interface{}   `json:"allActivityTagList"`
	AllTagList              interface{}   `json:"allTagList"`
	BizTagList              interface{}   `json:"bizTagList"`
	CouponTag               interface{}   `json:"couponTag"`
	CustomizedTag           interface{}   `json:"customizedTag"`
	GeneralActivityTagList  interface{}   `json:"generalActivityTagList"`
	GoodsBizTag             []interface{} `json:"goodsBizTag"`
	GoodsUserTag            interface{}   `json:"goodsUserTag"`
	IndustryTagList         interface{}   `json:"industryTagList"`
	MerchantTag             interface{}   `json:"merchantTag"`
	UserTag                 interface{}   `json:"userTag"`
}
type ItemList struct {
	BaseDiscountInfo    BaseDiscountInfo `json:"baseDiscountInfo"`
	BizInfo             BizInfo          `json:"bizInfo"`
	CommentStatus       interface{}      `json:"commentStatus"`
	GoodsCategoryID     interface{}      `json:"goodsCategoryId"`
	GoodsCode           interface{}      `json:"goodsCode"`
	GoodsID             int64            `json:"goodsId"`
	GoodsTitle          string           `json:"goodsTitle"`
	GoodsType           int              `json:"goodsType"`
	HadDeliveryItemNum  int              `json:"hadDeliveryItemNum"`
	ID                  int              `json:"id"`
	ImageURL            string           `json:"imageUrl"`
	OriginalPrice       float64          `json:"originalPrice"`
	PaymentAmount       float64          `json:"paymentAmount"`
	Point               interface{}      `json:"point"`
	Price               float64          `json:"price"`
	RightsOrderID       interface{}      `json:"rightsOrderId"`
	RightsStatus        interface{}      `json:"rightsStatus"`
	RightsStatusName    interface{}      `json:"rightsStatusName"`
	ShouldPaymentAmount interface{}      `json:"shouldPaymentAmount"`
	SkuAmount           float64          `json:"skuAmount"`
	SkuCode             interface{}      `json:"skuCode"`
	SkuID               int64            `json:"skuId"`
	SkuName             interface{}      `json:"skuName"`
	SkuNum              int              `json:"skuNum"`
	TagInfo             TagInfo          `json:"tagInfo"`
	TotalAmount         float64          `json:"totalAmount"`
	TotalPoint          interface{}      `json:"totalPoint"`
}

//查询微盟订单
func (a *API) QueryOrdersList(queryParam *QueryOrdersListParam) (orderList []*OrderInfo, totalCount int, err error) {
	param := make(map[string]interface{})
	if queryParam != nil {
		param = utils.Struct2FlatMap(queryParam)
	}
	result, err := a.AccessAPI("order/queryOrderList", param)
	if err == nil {
		data := result.(map[string]interface{})
		totalCount = int(utils.MustInterface2Int64(data["totalCount"]))
		err = utils.Map2StructByJson(data["pageList"], &orderList, false)
	}
	return orderList, totalCount, err
}

func (a *API) QueryOrderDetail(orderNo int64, needInvoiceInfo bool) (retVal map[string]interface{}, err error) {
	result, err := a.AccessAPI("order/queryOrderDetail", map[string]interface{}{
		"orderNo":         orderNo,
		"needInvoiceInfo": needInvoiceInfo,
	})
	if err == nil {
		return result.(map[string]interface{}), nil
	}
	return nil, err
}

func (a *API) QueryOrderDetail2(orderNo int64, needInvoiceInfo bool) (order *OrderDetail, err error) {
	result, err := a.AccessAPI("order/queryOrderDetail", map[string]interface{}{
		"orderNo":         orderNo,
		"needInvoiceInfo": needInvoiceInfo,
	})
	if err == nil {
		err = utils.Map2StructByJson(result, &order, false)
	}
	return order, err
}

func (a *API) CancelOrder(orderNo int64, specificCancelReason string) (err error) {
	apiParams := map[string]interface{}{
		"orderNo": orderNo,
	}
	if specificCancelReason != "" {
		apiParams["specificCancelReason"] = specificCancelReason
	}
	_, err = a.AccessAPI("order/cancelOrder", apiParams)
	return err
}

func (a *API) DeliveryOrder(orderDeliveryInfo *DeliveryOrder) (err error) {
	apiParams := utils.Struct2MapByJson(orderDeliveryInfo)
	// baseapi.SugarLogger.Debug(utils.Format4Output(apiParams, false))
	_, err = a.AccessAPI("order/deliveryOrder", apiParams)
	return err
}
