package yunzmall

import (
	"context"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/util/gconv"
)

type orderLogic struct {
}

type OrderAddress struct {
	Area        string `json:"area"`
	City        string `json:"city"`
	Consignee   string `json:"consignee"`
	Description string `json:"description"`
	Phone       string `json:"phone"`
	Province    string `json:"province"`
	Street      string `json:"street"`
}

type OrderSpu struct {
	Number int `json:"number"`
	Sku    int `json:"sku"`
}

type OrderBeforeReq struct {
	Address OrderAddress `json:"address"`
	Spu     []OrderSpu   `json:"spu"`
}

type OrderBeforeRes struct {
	CommonRes
	Data struct {
		Desc    string `json:"desc"`
		Freight string `json:"freight"`
	} `json:"data"`
}

// OrderBefore 前置校验
func (s *Client) OrderBefore(ctx context.Context, req OrderBeforeReq) (res *OrderBeforeRes, err error) {
	var method = "/app/order/beforeCheck"
	result, err := s.post(ctx, method, gconv.Map(req))
	if err != nil {
		return
	}
	err = gjson.New(result).Scan(&res)
	return
}

type OrderCreateReq struct {
	OrderSn string       `json:"order_sn"`
	Spu     []*OrderSpu  `json:"spu"`
	Address OrderAddress `json:"address"`
}
type OrderCreateRes struct {
	CommonRes
	Data struct {
		Code     int      `json:"code"`
		Messages []string `json:"messages"`
		Orders   []struct {
			Id                   int         `json:"id"`
			CreatedAt            int         `json:"created_at"`
			UpdatedAt            int         `json:"updated_at"`
			OrderSn              int64       `json:"order_sn"`
			ThirdOrderSn         string      `json:"third_order_sn"`
			GatherSupplySn       string      `json:"gather_supply_sn"`
			GatherSupplyMsg      string      `json:"gather_supply_msg"`
			GatherSupplyType     int         `json:"gather_supply_type"`
			Key                  string      `json:"key"`
			Title                string      `json:"title"`
			Status               int         `json:"status"`
			Amount               int         `json:"amount"`
			RefundAmount         int         `json:"refund_amount"`
			ItemAmount           int         `json:"item_amount"`
			SupplyAmount         int         `json:"supply_amount"`
			CostAmount           int         `json:"cost_amount"`
			Freight              int         `json:"freight"`
			ServiceFee           int         `json:"service_fee"`
			GoodsCount           int         `json:"goods_count"`
			SendStatus           int         `json:"send_status"`
			RefundStatus         int         `json:"refund_status"`
			Remark               string      `json:"remark"`
			Note                 string      `json:"note"`
			TechnicalServicesFee int         `json:"technical_services_fee"`
			PaidAt               interface{} `json:"paid_at"`
			SentAt               interface{} `json:"sent_at"`
			ReceivedAt           interface{} `json:"received_at"`
			ClosedAt             interface{} `json:"closed_at"`
			UserId               int         `json:"user_id"`
			SupplierId           int         `json:"supplier_id"`
			GatherSupplyId       int         `json:"gather_supply_id"`
			ApplicationId        int         `json:"application_id"`
			TradeId              int         `json:"trade_id"`
			PayTypeId            int         `json:"pay_type_id"`
			PayInfoId            int         `json:"pay_info_id"`
			ShippingMethodId     int         `json:"shipping_method_id"`
			ShippingAddressId    int         `json:"shipping_address_id"`
			SendTypeId           int         `json:"send_type_id"`
			CommentStatus        int         `json:"comment_status"`
			CanRefund            int         `json:"can_refund"`
			Lock                 int         `json:"lock"`
			IsConnection         int         `json:"is_connection"`
			AmountDetail         struct {
				Title       string `json:"title"`
				Amount      int    `json:"amount"`
				Qty         int    `json:"qty"`
				Desc        string `json:"desc"`
				AmountItems []struct {
					Title       string      `json:"title"`
					Amount      int         `json:"amount"`
					Qty         int         `json:"qty"`
					Desc        string      `json:"desc"`
					AmountItems interface{} `json:"amount_items"`
				} `json:"amount_items"`
			} `json:"amount_detail"`
			OrderItems []struct {
				Id              int    `json:"id"`
				CreatedAt       int    `json:"created_at"`
				UpdatedAt       int    `json:"updated_at"`
				Key             string `json:"key"`
				Title           string `json:"title"`
				SkuTitle        string `json:"sku_title"`
				Unit            string `json:"unit"`
				Qty             int    `json:"qty"`
				Amount          int    `json:"amount"`
				RefundAmount    int    `json:"refund_amount"`
				DiscountAmount  int    `json:"discount_amount"`
				DeductionAmount int    `json:"deduction_amount"`
				CostAmount      int    `json:"cost_amount"`
				PaymentAmount   int    `json:"payment_amount"`
				SupplyAmount    int    `json:"supply_amount"`
				ImageUrl        string `json:"image_url"`
				SendStatus      int    `json:"send_status"`
				RefundStatus    int    `json:"refund_status"`
				TradeId         int    `json:"trade_id"`
				SupplierId      int    `json:"supplier_id"`
				UserId          int    `json:"user_id"`
				OrderId         int    `json:"order_id"`
				ProductId       int    `json:"product_id"`
				SkuId           int    `json:"sku_id"`
				OriginalSkuId   int    `json:"original_sku_id"`
				CanRefund       int    `json:"can_refund"`
				CommentStatus   int    `json:"comment_status"`
				AmountDetail    struct {
					Title       string `json:"title"`
					Amount      int    `json:"amount"`
					Qty         int    `json:"qty"`
					Desc        string `json:"desc"`
					AmountItems []struct {
						Title       string        `json:"title"`
						Amount      int           `json:"amount"`
						Qty         int           `json:"qty"`
						Desc        string        `json:"desc"`
						AmountItems []interface{} `json:"amount_items"`
					} `json:"amount_items"`
				} `json:"amount_detail"`
				Options []struct {
					SpecName     string `json:"spec_name"`
					SpecItemName string `json:"spec_item_name"`
				} `json:"options"`
				Sku struct {
					Id                int         `json:"id"`
					CreatedAt         interface{} `json:"created_at"`
					UpdatedAt         interface{} `json:"updated_at"`
					Title             string      `json:"title"`
					Price             int         `json:"price"`
					CostPrice         int         `json:"cost_price"`
					OriginPrice       int         `json:"origin_price"`
					GuidePrice        int         `json:"guide_price"`
					ActivityPrice     int         `json:"activity_price"`
					Stock             int         `json:"stock"`
					Weight            int         `json:"weight"`
					IsDisplay         int         `json:"is_display"`
					ProductId         int         `json:"product_id"`
					SupplierId        int         `json:"supplier_id"`
					Code              string      `json:"code"`
					Sn                string      `json:"sn"`
					Barcode           string      `json:"barcode"`
					ImageUrl          string      `json:"image_url"`
					Options           interface{} `json:"options"`
					OriginalSkuId     int         `json:"original_sku_id"`
					Describe          string      `json:"describe"`
					TaxCode           string      `json:"tax_code"`
					TaxProductName    string      `json:"tax_product_name"`
					TaxShortName      string      `json:"tax_short_name"`
					TaxOption         string      `json:"tax_option"`
					TaxUnit           string      `json:"tax_unit"`
					FavorablePolicy   string      `json:"favorable_policy"`
					IsFavorablePolicy int         `json:"is_favorable_policy"`
					FreeOfTax         int         `json:"free_of_tax"`
					ShortCode         string      `json:"short_code"`
					TaxMeasurePrice   int         `json:"tax_measure_price"`
					TaxRate           int         `json:"tax_rate"`
					IsTaxLogo         int         `json:"is_tax_logo"`
				} `json:"sku"`
				Product struct {
					Id             int         `json:"id"`
					CreatedAt      interface{} `json:"created_at"`
					UpdatedAt      interface{} `json:"updated_at"`
					Title          string      `json:"title"`
					OriginPrice    int         `json:"origin_price"`
					GuidePrice     int         `json:"guide_price"`
					Price          int         `json:"price"`
					CostPrice      int         `json:"cost_price"`
					ActivityPrice  int         `json:"activity_price"`
					MinBuyQty      int         `json:"min_buy_qty"`
					Stock          int         `json:"stock"`
					Sales          int         `json:"sales"`
					FeedbackRate   int         `json:"feedback_rate"`
					Sn             string      `json:"sn"`
					Code           string      `json:"code"`
					IsNew          int         `json:"is_new"`
					IsRecommend    int         `json:"is_recommend"`
					IsHot          int         `json:"is_hot"`
					IsPromotion    int         `json:"is_promotion"`
					IsDisplay      int         `json:"is_display"`
					StatusLock     int         `json:"status_lock"`
					SingleOption   int         `json:"single_option"`
					Desc           string      `json:"desc"`
					ImageUrl       string      `json:"image_url"`
					VideoUrl       string      `json:"video_url"`
					Unit           string      `json:"unit"`
					Barcode        string      `json:"barcode"`
					Long           int         `json:"long"`
					Wide           int         `json:"wide"`
					High           int         `json:"high"`
					Volume         int         `json:"volume"`
					Freight        int         `json:"freight"`
					FreightType    int         `json:"freight_type"`
					MaxPrice       int         `json:"maxPrice"`
					MinPrice       int         `json:"minPrice"`
					MaxCostPrice   int         `json:"maxCostPrice"`
					MinCostPrice   int         `json:"minCostPrice"`
					MaxOriginPrice int         `json:"maxOriginPrice"`
					MinOriginPrice int         `json:"minOriginPrice"`
					Gallery        interface{} `json:"gallery"`
					Qualifications interface{} `json:"qualifications"`
					DetailImages   string      `json:"detail_images"`
					Attrs          interface{} `json:"attrs"`
					Supplier       struct {
						Id   int    `json:"id"`
						Name string `json:"name"`
					} `json:"supplier"`
					GatherSupply struct {
						Id         int    `json:"id"`
						Name       string `json:"name"`
						Key        string `json:"key"`
						CategoryId int    `json:"category_id"`
					} `json:"gather_supply"`
					AliProduct struct {
						Id           int         `json:"id"`
						CreatedAt    interface{} `json:"created_at"`
						UpdatedAt    interface{} `json:"updated_at"`
						ProductId    int         `json:"product_id"`
						SkuId        int         `json:"sku_id"`
						AliSkuId     string      `json:"ali_sku_id"`
						AliProductId int         `json:"ali_product_id"`
						ShopId       string      `json:"shop_id"`
					} `json:"ali_product"`
					BrandId int `json:"brand_id"`
					Brand   struct {
						Id        int         `json:"id"`
						CreatedAt interface{} `json:"created_at"`
						UpdatedAt interface{} `json:"updated_at"`
						Name      string      `json:"name"`
					} `json:"brand"`
					SupplierId        int    `json:"supplier_id"`
					GatherSupplyId    int    `json:"gather_supply_id"`
					Category1Id       int    `json:"category1_id"`
					Category2Id       int    `json:"category2_id"`
					Category3Id       int    `json:"category3_id"`
					FreightTemplateId int    `json:"freight_template_id"`
					Source            int    `json:"source"`
					Sort              int    `json:"sort"`
					SourceGoodsId     int    `json:"source_goods_id"`
					LocationId        int    `json:"location_id"`
					Freeze            int    `json:"freeze"`
					ShopLevel         int    `json:"shop_level"`
					DesLevel          int    `json:"des_level"`
					ExpressLevel      int    `json:"express_level"`
					Level             int    `json:"level"`
					ChildTitle        string `json:"child_title"`
					BillPosition      int    `json:"bill_position"`
					Md5               string `json:"md5"`
					TaxCode           string `json:"tax_code"`
					TaxProductName    string `json:"tax_product_name"`
					TaxShortName      string `json:"tax_short_name"`
					TaxOption         string `json:"tax_option"`
					TaxUnit           string `json:"tax_unit"`
					FavorablePolicy   string `json:"favorable_policy"`
					IsFavorablePolicy int    `json:"is_favorable_policy"`
					FreeOfTax         int    `json:"free_of_tax"`
					ShortCode         string `json:"short_code"`
					TaxMeasurePrice   int    `json:"tax_measure_price"`
					TaxRate           int    `json:"tax_rate"`
					IsTaxLogo         int    `json:"is_tax_logo"`
					ProductVerify     struct {
						Id         int         `json:"id"`
						CreatedAt  interface{} `json:"created_at"`
						UpdatedAt  interface{} `json:"updated_at"`
						ProductId  int         `json:"product_id"`
						SupplierId int         `json:"supplier_id"`
						Status     int         `json:"status"`
						IsDisplay  int         `json:"is_display"`
					} `json:"product_verify"`
					IsPlugin                 int `json:"is_plugin"`
					IsSingleOrder            int `json:"is_single_order"`
					SupplierSourceId         int `json:"supplier_source_id"`
					SupplierSourceCategoryId int `json:"supplier_source_category_id"`
				} `json:"product"`
				AfterSales struct {
					Id                   int         `json:"id"`
					CreatedAt            interface{} `json:"created_at"`
					UpdatedAt            interface{} `json:"updated_at"`
					AfterSaleSn          string      `json:"after_sale_sn"`
					UserId               int         `json:"user_id"`
					Amount               int         `json:"amount"`
					TechnicalServicesFee int         `json:"technical_services_fee"`
					Freight              int         `json:"freight"`
					PracticalAmount      int         `json:"practical_amount"`
					ReasonType           int         `json:"reason_type"`
					Reason               string      `json:"reason"`
					Description          string      `json:"description"`
					OrderId              int         `json:"order_id"`
					OrderItemId          int         `json:"order_item_id"`
					SkuId                int         `json:"sku_id"`
					ProductId            int         `json:"product_id"`
					ShippingAddressId    int         `json:"shipping_address_id"`
					IsReceived           int         `json:"is_received"`
					PayMethod            int         `json:"pay_method"`
					ReturnOrderExpressId int         `json:"return_order_express_id"`
					Status               int         `json:"status"`
					Type                 int         `json:"type"`
					DetailImages         interface{} `json:"detail_images"`
					Logs                 interface{} `json:"logs"`
					AfterSalesAudit      struct {
						Id           int         `json:"id"`
						CreatedAt    interface{} `json:"created_at"`
						UpdatedAt    interface{} `json:"updated_at"`
						AfterSalesId int         `json:"after_sales_id"`
						AdminId      int         `json:"admin_id"`
						ReasonType   int         `json:"reason_type"`
						Reason       string      `json:"reason"`
						Status       int         `json:"status"`
						Cause        string      `json:"cause"`
						StatusName   string      `json:"status_name"`
						RefundName   string      `json:"refund_name"`
					} `json:"after_sales_audit"`
					ReturnOrderExpress struct {
						Id           int         `json:"id"`
						CreatedAt    interface{} `json:"created_at"`
						UpdatedAt    interface{} `json:"updated_at"`
						AfterSalesId int         `json:"after_sales_id"`
						CompanyName  string      `json:"company_name"`
						CompanyCode  string      `json:"company_code"`
						ExpressNo    string      `json:"express_no"`
					} `json:"return_order_express"`
					RefundReasonName string      `json:"refund_reason_name"`
					SuccessAt        interface{} `json:"success_at"`
					StatusName       string      `json:"status_name"`
				} `json:"after_sales"`
			} `json:"order_items"`
			OrderExpress struct {
				Id          int         `json:"id"`
				CreatedAt   interface{} `json:"created_at"`
				UpdatedAt   interface{} `json:"updated_at"`
				OrderId     int         `json:"order_id"`
				CompanyCode string      `json:"company_code"`
				ExpressNo   string      `json:"express_no"`
				OrderItems  interface{} `json:"order_items"`
				IsEmpty     int         `json:"is_empty"`
				FinalSend   int         `json:"final_send"`
			} `json:"order_express"`
			ShippingAddress struct {
				Id         int    `json:"id"`
				Realname   string `json:"realname"`
				Mobile     string `json:"mobile"`
				CountryId  int    `json:"country_id"`
				ProvinceId int    `json:"province_id"`
				CityId     int    `json:"city_id"`
				CountyId   int    `json:"county_id"`
				TownId     int    `json:"town_id"`
				Province   string `json:"province"`
				City       string `json:"city"`
				County     string `json:"county"`
				Town       string `json:"town"`
				Detail     string `json:"detail"`
				Lng        string `json:"lng"`
				Lat        string `json:"lat"`
			} `json:"shipping_address"`
			OrderBill struct {
				Id          int         `json:"id"`
				CreatedAt   interface{} `json:"created_at"`
				UpdatedAt   interface{} `json:"updated_at"`
				Type        int         `json:"type"`
				AccountType int         `json:"account_type"`
				PersonName  string      `json:"person_name"`
				Mobile      string      `json:"mobile"`
				CompanyName string      `json:"company_name"`
				CompanyCode string      `json:"company_code"`
				Email       string      `json:"email"`
				SignAddress string      `json:"sign_address"`
				SignMobile  string      `json:"sign_mobile"`
				OpeningBank string      `json:"opening_bank"`
				BankAccount string      `json:"bank_account"`
				DetailType  int         `json:"detail_type"`
				Amount      int         `json:"amount"`
				AddressId   int         `json:"address_id"`
				Applicant   string      `json:"applicant"`
				OrderId     int         `json:"order_id"`
				BillId      int         `json:"bill_id"`
				Status      int         `json:"status"`
				Drawer      int         `json:"drawer"`
			} `json:"order_bill"`
			TechnologyFeeBill struct {
				Id        int         `json:"id"`
				CreatedAt interface{} `json:"created_at"`
				UpdatedAt interface{} `json:"updated_at"`
				OrderId   int         `json:"order_id"`
				BillId    int         `json:"bill_id"`
				Amount    int         `json:"amount"`
				Status    int         `json:"status"`
			} `json:"technology_fee_bill"`
			IsUpdateShippingAddress int `json:"is_update_shipping_address"`
			IsCps                   int `json:"is_cps"`
		} `json:"Orders"`
	} `json:"data"`
}

// OrderCreate 下单
func (s *Client) OrderCreate(ctx context.Context, req OrderCreateReq) (res *OrderCreateRes, err error) {
	var method = "/app/order"
	result, err := s.post(ctx, method, gconv.Map(req))
	if err != nil {
		return
	}
	err = gjson.New(result).Scan(&res)
	return
}

type OrderAvailableReq struct {
	Spu     []*OrderSpu  `json:"spu"`
	Address OrderAddress `json:"address"`
}

type OrderAvailableRes struct {
	Code int `json:"code"`
	Data struct {
		Available []int `json:"available"`
		Ban       []int `json:"ban"`
	} `json:"data"`
	Msg string `json:"msg"`
}

// OrderAvailable 可售检测
func (s *Client) OrderAvailable(ctx context.Context, req OrderAvailableReq) (res *OrderAvailableRes, err error) {
	var method = "/app/order/availableCheck"
	result, err := s.post(ctx, method, gconv.Map(req))
	if err != nil {
		return
	}
	err = gjson.New(result).Scan(&res)
	return
}