package weimobapi

import (
	"fmt"
	"io/ioutil"
	"net/http"

	"git.rosy.net.cn/baseapi/platformapi"
	"git.rosy.net.cn/baseapi/utils"
)

const (
	DeductStockTypePlaceOrder = 1
	DeductStockTypePay        = 2
)

const (
	GoodsTypeNormal  = 0
	GoodsTypeOversea = 1
)

type PendingSaveB2CGoodsVo struct {
	FreightTemplateId  int64   `json:"freightTemplateId"`
	DeliveryTypeIdList []int64 `json:"deliveryTypeIdList"`
	B2cGoodsType       int     `json:"b2cGoodsType"`
}

type PendingSaveB2CSkuVo struct {
	Weight float32 `json:"weight"`
	Volume float32 `json:"volume"`
}

type PendingSaveSkuVo struct {
	OuterSkuCode  string               `json:"outerSkuCode"`
	ImageURL      string               `json:"imageUrl,omitempty"`
	SalePrice     float64              `json:"salePrice"`
	OriginalPrice float64              `json:"originalPrice,omitempty"`
	CostPrice     float64              `json:"costPrice"`
	EditStockNum  int                  `json:"editStockNum"`
	B2cSku        *PendingSaveB2CSkuVo `json:"b2cSku"`
}

type PendingSaveGoodsVo struct {
	Title           string                   `json:"title"`
	OuterGoodsCode  string                   `json:"outerGoodsCode,omitempty"`
	IsMultiSku      int                      `json:"isMultiSku"`
	GoodsImageURL   []string                 `json:"goodsImageUrl"`
	GoodsDesc       string                   `json:"goodsDesc"`
	InitialSales    int                      `json:"initialSales,omitempty"`
	DeductStockType int                      `json:"deductStockType"`
	IsPutAway       int                      `json:"isPutAway"`
	Sort            int                      `json:"Sort,omitempty"`
	CategoryID      int64                    `json:"categoryId"`
	B2cGoods        []*PendingSaveB2CGoodsVo `json:"b2cGoods"`
	SkuList         []*PendingSaveSkuVo      `json:"skuList"`
}

type Category struct {
	CategoryID int64  `json:"categoryId"`
	Title      string `json:"title"`
	Level      int    `json:"level"`
	ParentID   int64  `json:"parentId"`
}

type GoodsClassify struct {
	ClassifyID       int64            `json:"classifyId"`
	ImageURL         string           `json:"imageUrl"`
	Title            string           `json:"title"`
	Level            int              `json:"level"`
	ChildrenClassify []*GoodsClassify `json:"childrenClassify"`
}

type DeliveryType struct {
	DeliveryID       int64  `json:"deliveryId"`
	DeliveryTypeName string `json:"deliveryTypeName"`
	DeliveryType     int    `json:"deliveryType"`
	Selected         bool   `json:"selected"`
}

type GoodsInfo struct {
	AvaliableStockNum int              `json:"avaliableStockNum"`
	DefaultImageURL   string           `json:"defaultImageUrl"`
	ExistEmptyStock   bool             `json:"existEmptyStock"`
	GoodsID           int64            `json:"goodsId"`
	IsAllStockEmpty   bool             `json:"isAllStockEmpty"`
	IsCanSell         bool             `json:"isCanSell"`
	IsExistEmptyStock bool             `json:"isExistEmptyStock"`
	IsMultiSku        int              `json:"isMultiSku"`
	IsPutAway         int              `json:"isPutAway"`
	MaxPrice          float64          `json:"maxPrice"`
	MinPrice          float64          `json:"minPrice"`
	PutAwayDate       int64            `json:"putAwayDate"`
	PutAwayForBackend int              `json:"putAwayForBackend"`
	SalesNum          int              `json:"salesNum"`
	SortNum           int              `json:"sortNum"`
	Title             string           `json:"title"`
	GoodsDetailInfo   *GoodsDetailInfo `json:"goodsDetailInfo"`
}

type QueryGoodsListParam struct {
	PageNum        int                      `json:"pageNum"`
	PageSize       int                      `json:"pageSize"`
	OrderBy        *OrderByInfo             `json:"orderBy,omitempty"`
	QueryParameter *QueryGoodsListRequestVo `json:"queryParameter,omitempty"`
}

type OrderByInfo struct {
	Field string `json:"field"` //排序字段名： sortNum：按照sort字段排序 putAwayDate：按照上下架时间排序 salesNum：按照销量排序 availableStockNum：按照库存排序 price：按照价格排序
	Sort  string `json:"sort"`  //升降/降序 DESC/ASC，只能是这两个值，不区分大小写
}

type QueryGoodsListRequestVo struct {
	GoodsStatus     int    `json:"goodsStatus"`     //商品状态：0-上架中 1-下架中 2-已售罄
	GoodsClassifyID int    `json:"goodsClassifyId"` //分组id
	Search          string `json:"search"`          //搜索框输入内容商品名称
}

type GoodsDetailInfo struct {
	ArchivesTemplate               interface{}            `json:"archivesTemplate"`
	B2CGoods                       *B2CGoods              `json:"b2cGoods"`
	CategoryList                   []*CategoryList        `json:"categoryList"`
	DeductStockType                int                    `json:"deductStockType"`
	DefaultImageURL                interface{}            `json:"defaultImageUrl"`
	GoodsDesc                      string                 `json:"goodsDesc"`
	GoodsID                        int64                  `json:"goodsId"`
	GoodsImageURL                  []string               `json:"goodsImageUrl"`
	GoodsSlogan                    interface{}            `json:"goodsSlogan"`
	GoodsVideoImageURL             interface{}            `json:"goodsVideoImageUrl"`
	GoodsVideoURL                  interface{}            `json:"goodsVideoUrl"`
	InitialSales                   int                    `json:"initialSales"`
	IsAllowOversold                interface{}            `json:"isAllowOversold"`
	IsAssignStore                  interface{}            `json:"isAssignStore"`
	IsAutoCanSell                  interface{}            `json:"isAutoCanSell"`
	IsAutoForbidSell               interface{}            `json:"isAutoForbidSell"`
	IsCanSell                      interface{}            `json:"isCanSell"`
	IsDeleted                      bool                   `json:"isDeleted"`
	IsMemberShipDiscount           int                    `json:"isMemberShipDiscount"`
	IsMultiSku                     int                    `json:"isMultiSku"`
	IsPreSell                      interface{}            `json:"isPreSell"`
	IsPutAway                      int                    `json:"isPutAway"`
	IsStorePreSell                 int                    `json:"isStorePreSell"`
	LimitBuyNum                    int                    `json:"limitBuyNum"`
	MaxSalePrice                   interface{}            `json:"maxSalePrice"`
	MinSalePrice                   interface{}            `json:"minSalePrice"`
	OuterGoodsCode                 string                 `json:"outerGoodsCode"`
	PointDeductRatio               int                    `json:"pointDeductRatio"`
	PresellGoods                   interface{}            `json:"presellGoods"`
	SaleChannelType                interface{}            `json:"saleChannelType"`
	SelectedClassifyList           []SelectedClassifyList `json:"selectedClassifyList"`
	SelectedGoodsAttrInfoList      interface{}            `json:"selectedGoodsAttrInfoList"`
	SelectedGoodsAttrList          SelectedGoodsAttrList  `json:"selectedGoodsAttrList"`
	SelectedGoodsPropInfoList      interface{}            `json:"selectedGoodsPropInfoList"`
	SelectedGoodsRightsInfoList    interface{}            `json:"selectedGoodsRightsInfoList"`
	SelectedInnerGoodsPropInfoList interface{}            `json:"selectedInnerGoodsPropInfoList"`
	SelectedSaleAttrIDList         interface{}            `json:"selectedSaleAttrIdList"`
	SelectedSaleAttrInfoList       interface{}            `json:"selectedSaleAttrInfoList"`
	SelectedSaleAttrList           SelectedSaleAttrList   `json:"selectedSaleAttrList"`
	SelectedTag                    interface{}            `json:"selectedTag"`
	SellModelType                  int                    `json:"sellModelType"`
	SkuList                        []SkuList              `json:"skuList"`
	SkuMap                         SkuMap                 `json:"skuMap"`
	Sort                           int                    `json:"sort"`
	Source                         int                    `json:"source"`
	StartForbidTime                interface{}            `json:"startForbidTime"`
	StartPutAwayTime               interface{}            `json:"startPutAwayTime"`
	StartSellTime                  interface{}            `json:"startSellTime"`
	Title                          string                 `json:"title"`
}
type B2CGoods struct {
	B2CGoodsType            int         `json:"b2cGoodsType"`
	DeliveryTypeIDList      interface{} `json:"deliveryTypeIdList"`
	FreightTemplateID       interface{} `json:"freightTemplateId"`
	SelectedFreightTemplate interface{} `json:"selectedFreightTemplate"`
}
type CategoryList struct {
	CategoryID           int         `json:"categoryId"`
	ChildrenCategoryList interface{} `json:"childrenCategoryList"`
	EnableCustom         interface{} `json:"enableCustom"`
	IsLeaf               interface{} `json:"isLeaf"`
	Title                string      `json:"title"`
}
type ChildrenClassify struct {
	ChildrenClassify interface{} `json:"childrenClassify"`
	ClassifyID       int64       `json:"classifyId"`
	GoodsNum         interface{} `json:"goodsNum"`
	ImageURL         interface{} `json:"imageUrl"`
	IsHot            interface{} `json:"isHot"`
	Level            interface{} `json:"level"`
	ParentID         interface{} `json:"parentId"`
	Title            string      `json:"title"`
}
type SelectedClassifyList struct {
	ChildrenClassify []ChildrenClassify `json:"childrenClassify"`
	ClassifyID       int64              `json:"classifyId"`
	GoodsNum         interface{}        `json:"goodsNum"`
	ImageURL         interface{}        `json:"imageUrl"`
	IsHot            int                `json:"isHot"`
	Level            interface{}        `json:"level"`
	ParentID         interface{}        `json:"parentId"`
	Title            string             `json:"title"`
}
type SelectedGoodsAttrList struct {
}
type SelectedSaleAttrList struct {
}
type B2CSku struct {
	Volume float64 `json:"volume"`
	Weight float64 `json:"weight"`
}
type SkuList struct {
	AdviseSalePriceMax    interface{} `json:"adviseSalePriceMax"`
	AdviseSalePriceMin    interface{} `json:"adviseSalePriceMin"`
	AvailableStockNum     int         `json:"availableStockNum"`
	B2CSku                *B2CSku     `json:"b2cSku"`
	ChangeGoodsLimitNum   int         `json:"changeGoodsLimitNum"`
	ChangeStockNum        int         `json:"changeStockNum"`
	CombineProduct        interface{} `json:"combineProduct"`
	CombineProductID      interface{} `json:"combineProductId"`
	CostPrice             float64     `json:"costPrice"`
	DistributorLimitStock interface{} `json:"distributorLimitStock"`
	GoodsID               int64       `json:"goodsId"`
	GoodsLimitNum         int         `json:"goodsLimitNum"`
	ImageURL              interface{} `json:"imageUrl"`
	InStock               bool        `json:"inStock"`
	IsDeleted             bool        `json:"isDeleted"`
	IsDisabled            bool        `json:"isDisabled"`
	LockPriceStatus       int         `json:"lockPriceStatus"`
	MerchantSalePrice     interface{} `json:"merchantSalePrice"`
	OriginalPrice         float64     `json:"originalPrice"`
	OuterSkuCode          string      `json:"outerSkuCode"`
	ProductCode           string      `json:"productCode"`
	ProductTitle          string      `json:"productTitle"`
	ProductType           int         `json:"productType"`
	SalePrice             float64     `json:"salePrice"`
	SingleProduct         interface{} `json:"singleProduct"`
	SingleProductID       interface{} `json:"singleProductId"`
	SingleProductTitle    interface{} `json:"singleProductTitle"`
	SkuAttrKey            interface{} `json:"skuAttrKey"`
	SkuAttrMap            interface{} `json:"skuAttrMap"`
	SkuAttrValueNameList  interface{} `json:"skuAttrValueNameList"`
	SkuID                 int64       `json:"skuId"`
	SkuInfoMap            interface{} `json:"skuInfoMap"`
	SupplierStockMax      interface{} `json:"supplierStockMax"`
	EditStockNum          int         `json:"editStockNum"`
}
type SingleSku struct {
	AdviseSalePriceMax    interface{} `json:"adviseSalePriceMax"`
	AdviseSalePriceMin    interface{} `json:"adviseSalePriceMin"`
	AvailableStockNum     int         `json:"availableStockNum"`
	B2CSku                B2CSku      `json:"b2cSku"`
	ChangeGoodsLimitNum   int         `json:"changeGoodsLimitNum"`
	ChangeStockNum        int         `json:"changeStockNum"`
	CombineProduct        interface{} `json:"combineProduct"`
	CombineProductID      interface{} `json:"combineProductId"`
	CostPrice             float64     `json:"costPrice"`
	DistributorLimitStock interface{} `json:"distributorLimitStock"`
	GoodsID               int64       `json:"goodsId"`
	GoodsLimitNum         int         `json:"goodsLimitNum"`
	ImageURL              interface{} `json:"imageUrl"`
	InStock               bool        `json:"inStock"`
	IsDeleted             bool        `json:"isDeleted"`
	IsDisabled            bool        `json:"isDisabled"`
	LockPriceStatus       int         `json:"lockPriceStatus"`
	MerchantSalePrice     interface{} `json:"merchantSalePrice"`
	OriginalPrice         float64     `json:"originalPrice"`
	OuterSkuCode          string      `json:"outerSkuCode"`
	ProductCode           string      `json:"productCode"`
	ProductTitle          string      `json:"productTitle"`
	ProductType           int         `json:"productType"`
	SalePrice             float64     `json:"salePrice"`
	SingleProduct         interface{} `json:"singleProduct"`
	SingleProductID       interface{} `json:"singleProductId"`
	SingleProductTitle    interface{} `json:"singleProductTitle"`
	SkuAttrKey            interface{} `json:"skuAttrKey"`
	SkuAttrMap            interface{} `json:"skuAttrMap"`
	SkuAttrValueNameList  interface{} `json:"skuAttrValueNameList"`
	SkuID                 int64       `json:"skuId"`
	SkuInfoMap            interface{} `json:"skuInfoMap"`
	SupplierStockMax      interface{} `json:"supplierStockMax"`
}
type SkuMap struct {
	SingleSku SingleSku `json:"singleSku"`
}

type UpdateGoodsParam struct {
	Goods *Goods `json:"goods"`
}
type Num1 struct {
	Key int `json:"key"`
}
type Num3000 struct {
	Key int `json:"key"`
}
type SkuAttrMap struct {
	Num1    Num1    `json:"1"`
	Num3000 Num3000 `json:"3000"`
}

type AttrValueList struct {
	Key int `json:"key"`
}

type Goods struct {
	B2CGoods               *B2CGoods               `json:"b2cGoods"`
	CategoryID             int                     `json:"categoryId"`
	Title                  string                  `json:"title"`
	IsMultiSku             int                     `json:"isMultiSku"`
	GoodsTagID             int                     `json:"goodsTagId,omitempty"`
	GoodsDesc              string                  `json:"goodsDesc"`
	InitialSales           int                     `json:"initialSales,omitempty"`
	DeductStockType        int                     `json:"deductStockType,omitempty"`
	IsPutAway              int                     `json:"isPutAway"`
	IsMemberShipDiscount   int                     `json:"isMemberShipDiscount"`
	SkuList                []*SkuList              `json:"skuList"`
	SelectedGoodsAttrList  []SelectedGoodsAttrList `json:"selectedGoodsAttrList,omitempty"`
	SelectedSaleAttrList   []SelectedSaleAttrList  `json:"selectedSaleAttrList,omitempty"`
	GoodsImageURL          []string                `json:"goodsImageUrl"`
	SelectedClassifyIDList []int64                 `json:"selectedClassifyIdList,omitempty"`
	GoodsID                int64                   `json:"goodsId"`
	OuterGoodsCode         string                  `json:"outerGoodsCode"`
	PointDeductRatio       int                     `json:"pointDeductRatio"`
}
type FindFreightTemplateListInfo struct {
	DefaultFreightTemplate  DefaultFreightTemplate  `json:"defaultFreightTemplate"`
	FreightTemplateList     []FreightTemplateList   `json:"freightTemplateList"`
	SelectedFreightTemplate SelectedFreightTemplate `json:"selectedFreightTemplate"`
}
type TemplateRuleItemList struct {
	BaseAmount         float64     `json:"baseAmount"`
	ExtendAmount       float64     `json:"extendAmount"`
	ExtendNumUnit      int         `json:"extendNumUnit"`
	ExtendVolumeUnit   interface{} `json:"extendVolumeUnit"`
	ExtendWeightUnit   interface{} `json:"extendWeightUnit"`
	IsDefault          int         `json:"isDefault"`
	SupportAreaName    string      `json:"supportAreaName"`
	TemplateRuleItemID int         `json:"templateRuleItemId"`
	UpperNum           int         `json:"upperNum"`
	UpperVolume        interface{} `json:"upperVolume"`
	UpperWeight        interface{} `json:"upperWeight"`
}
type TemplateRuleList struct {
	DeliveryMethodName   string                 `json:"deliveryMethodName"`
	TemplateRuleID       int                    `json:"templateRuleId"`
	TemplateRuleItemList []TemplateRuleItemList `json:"templateRuleItemList"`
}
type DefaultFreightTemplate struct {
	CalculateType    int                `json:"calculateType"`
	IsFree           int                `json:"isFree"`
	TemplateID       int                `json:"templateId"`
	TemplateName     string             `json:"templateName"`
	TemplateRuleList []TemplateRuleList `json:"templateRuleList"`
}
type FreightTemplateList struct {
	CalculateType    int         `json:"calculateType"`
	IsFree           int         `json:"isFree"`
	TemplateID       int         `json:"templateId"`
	TemplateName     string      `json:"templateName"`
	TemplateRuleList interface{} `json:"templateRuleList"`
}
type SelectedFreightTemplate struct {
	CalculateType    int                `json:"calculateType"`
	IsFree           int                `json:"isFree"`
	TemplateID       int                `json:"templateId"`
	TemplateName     string             `json:"templateName"`
	TemplateRuleList []TemplateRuleList `json:"templateRuleList"`
}

func (a *API) QueryGoodsList(queryParam *QueryGoodsListParam) (goodsList []*GoodsInfo, totalCount int, err error) {
	param := make(map[string]interface{})
	if queryParam != nil {
		param = utils.Struct2FlatMap(queryParam)
	}
	result, err := a.AccessAPI("goods/queryGoodsList", param)
	if err == nil {
		data := result.(map[string]interface{})
		totalCount = int(utils.MustInterface2Int64(data["totalCount"]))
		err = utils.Map2StructByJson(data["pageList"], &goodsList, false)
	}
	return goodsList, totalCount, err
}

func (a *API) QueryGoodsDetail(goodsId int64) (goodsDetailInfo *GoodsDetailInfo, err error) {
	apiParams := map[string]interface{}{
		"goodsId": goodsId,
	}
	result, err := a.AccessAPI("goods/queryGoodsDetail", apiParams)
	if err == nil {
		data := result.(map[string]interface{})
		err = utils.Map2StructByJson(data["goods"], &goodsDetailInfo, false)
		return goodsDetailInfo, nil
		// return result.(map[string]interface{})["goods"].(map[string]interface{}), nil
	}
	return nil, err
}

func (a *API) QueryCategoryTree() (retVal []*Category, err error) {
	result, err := a.AccessAPI("category/queryCategoryTree", nil)
	if err == nil {
		categoryList := result.(map[string]interface{})["categoryList"].([]interface{})
		retVal = make([]*Category, len(categoryList))
		for k, v := range categoryList {
			retVal[k] = map2Category(1, 0, v.(map[string]interface{}))
		}
		return retVal, nil
	}
	return nil, err
}

func map2Category(level int, parentID int64, mapData map[string]interface{}) *Category {
	return &Category{
		CategoryID: utils.MustInterface2Int64(mapData["categoryId"]),
		Title:      utils.Interface2String(mapData["title"]),
		Level:      level,
		ParentID:   parentID,
	}
}

func (a *API) QueryChildrenCategory(categoryId int64) (retVal []*Category, err error) {
	result, err := a.AccessAPI("category/queryChildrenCategory", map[string]interface{}{
		"categoryId": categoryId,
	})
	if err == nil {
		categoryList := result.(map[string]interface{})["categoryList"].([]interface{})
		retVal = make([]*Category, len(categoryList))
		for k, v := range categoryList {
			retVal[k] = map2Category(2, categoryId, v.(map[string]interface{}))
		}
		return retVal, nil
	}
	return nil, err
}

func (a *API) QueryClassifyInfoList() (retVal []*GoodsClassify, err error) {
	result, err := a.AccessAPI("goodsClassify/queryClassifyInfoList", nil)
	if err == nil {
		goodsClassifyList := interface2ClassifyList(result.(map[string]interface{})["goodsClassifyList"], nil)
		return goodsClassifyList, nil
	}
	return nil, err
}

func interface2Classify(data interface{}) (clf *GoodsClassify) {
	mapData, ok := data.(map[string]interface{})
	if ok {
		clf = &GoodsClassify{
			ClassifyID:       utils.MustInterface2Int64(mapData["classifyId"]),
			ImageURL:         utils.Interface2String(mapData["imageUrl"]),
			Title:            utils.Interface2String(mapData["title"]),
			Level:            int(utils.Interface2Int64WithDefault(mapData["level"], 0)),
			ChildrenClassify: interface2ClassifyList(mapData["childrenClassify"], nil),
		}
	}
	return clf
}

func interface2ClassifyList(data interface{}, interface2CatHandler func(data interface{}) (clf *GoodsClassify)) (clfs []*GoodsClassify) {
	if interface2CatHandler == nil {
		interface2CatHandler = interface2Classify
	}
	maps, ok := data.([]interface{})
	if ok {
		clfs = make([]*GoodsClassify, len(maps))
		for index, v := range maps {
			clfs[index] = interface2CatHandler(v)
		}
	}
	return clfs
}

func (a *API) AddClassify(title string, parentID int64, imageURL string) (goodsClassifyID int64, err error) {
	apiParams := map[string]interface{}{
		"title": title,
	}
	if parentID > 0 {
		apiParams["parentId"] = parentID
	}
	if imageURL != "" {
		apiParams["imageUrl"] = imageURL
	}
	result, err := a.AccessAPI("goodsClassify/addClassify", apiParams)
	if err == nil {
		return utils.MustInterface2Int64(result.(map[string]interface{})["goodsClassifyId"]), nil
	}
	return 0, err
}

func (a *API) UpdateClassify(classifyID int64, title string, imageURL string) (err error) {
	apiParams := map[string]interface{}{
		"title":      title,
		"classifyId": classifyID,
	}
	if imageURL != "" {
		apiParams["imageUrl"] = imageURL
	}
	_, err = a.AccessAPI("goodsClassify/updateClassify", apiParams)
	return err
}

func getDataFromCUGoodsResult(result interface{}) (goodsId int64, skuMap map[string]int64, err error) {
	skuMap = make(map[string]int64)
	skuList := result.(map[string]interface{})["skuList"].([]interface{})
	for _, v := range skuList {
		sku := v.(map[string]interface{})
		skuMap[utils.Interface2String(sku[KeyOuterSkuCode])] = utils.MustInterface2Int64(sku[KeySkuID])
	}
	return utils.MustInterface2Int64(result.(map[string]interface{})["goodsId"]), skuMap, nil
}

func (a *API) AddGoods(outerGoodsCode, title string, isMultiSku bool, goodsImageUrl []string, goodsDesc string, isPutAway bool, sort int, categoryId int64, classifyIdList []int64, b2cGoods *PendingSaveB2CGoodsVo, skuList []map[string]interface{}, addParams map[string]interface{}) (goodsId int64, skuMap map[string]int64, err error) {
	goodsInfo := map[string]interface{}{
		"outerGoodsCode":         outerGoodsCode,
		"title":                  title,
		"isMultiSku":             utils.Bool2Int(isMultiSku),
		"goodsImageUrl":          goodsImageUrl,
		"goodsDesc":              goodsDesc,
		"isPutAway":              1 - utils.Bool2Int(isPutAway),
		"sort":                   sort,
		"categoryId":             categoryId,
		"b2cGoods":               b2cGoods,
		"skuList":                skuList,
		"selectedClassifyIdList": classifyIdList,
		"initialSales":           100,
	}
	mergedMap := utils.MergeMaps(addParams, goodsInfo)
	if _, ok := mergedMap["deductStockType"]; !ok {
		mergedMap["deductStockType"] = DeductStockTypePay
	}
	result, err := a.AccessAPI("goods/addGoods", map[string]interface{}{
		"goods": mergedMap,
	})
	if err == nil {
		return getDataFromCUGoodsResult(result)
	}
	return 0, nil, err
}

func (a *API) AddGoods2(goodsInfo *PendingSaveGoodsVo) (goodsId int64, skuMap map[string]int64, err error) {
	if goodsInfo.DeductStockType == 0 {
		goodsInfo.DeductStockType = DeductStockTypePay
	}
	result, err := a.AccessAPI("goods/addGoods", map[string]interface{}{
		"goods": goodsInfo,
	})
	if err == nil {
		return getDataFromCUGoodsResult(result)
	}
	return 0, nil, err
}

func (a *API) UpdateGoods3(updateGoodsParam *UpdateGoodsParam) (goodsId int64, skuMap map[string]int64, err error) {
	if updateGoodsParam.Goods.DeductStockType == 0 {
		updateGoodsParam.Goods.DeductStockType = DeductStockTypePay
	}
	result, err := a.AccessAPI("goods/updateGoods", map[string]interface{}{
		"goods": updateGoodsParam.Goods,
	})
	if err == nil {
		return getDataFromCUGoodsResult(result)
	}
	return 0, nil, err
}

func (a *API) UpdateGoods(goodsID int64, title string, isMultiSku bool, goodsImageUrl []string, goodsDesc string, isPutAway bool, sort int, categoryId int64, classifyIdList []int64, b2cGoods *PendingSaveB2CGoodsVo, skuList []map[string]interface{}, addParams map[string]interface{}) (goodsId int64, skuMap map[string]int64, err error) {
	goodsInfo := map[string]interface{}{
		"goodsId":                goodsID,
		"title":                  title,
		"isMultiSku":             utils.Bool2Int(isMultiSku),
		"goodsImageUrl":          goodsImageUrl,
		"goodsDesc":              goodsDesc,
		"isPutAway":              1 - utils.Bool2Int(isPutAway),
		"sort":                   sort,
		"categoryId":             categoryId,
		"b2cGoods":               b2cGoods,
		"skuList":                skuList,
		"selectedClassifyIdList": classifyIdList,
	}
	mergedMap := utils.MergeMaps(addParams, goodsInfo)
	if _, ok := mergedMap["deductStockType"]; !ok {
		mergedMap["deductStockType"] = DeductStockTypePay
	}
	result, err := a.AccessAPI("goods/updateGoods", map[string]interface{}{
		"goods": mergedMap,
	})
	if err == nil {
		return getDataFromCUGoodsResult(result)
	}
	return 0, nil, err
}

func (a *API) UpdateGoods2(goodsInfo *PendingSaveGoodsVo) (goodsId int64, skuMap map[string]int64, err error) {
	if goodsInfo.DeductStockType == 0 {
		goodsInfo.DeductStockType = DeductStockTypePay
	}
	result, err := a.AccessAPI("goods/updateGoods", map[string]interface{}{
		"goods": goodsInfo,
	})
	if err == nil {
		return getDataFromCUGoodsResult(result)
	}
	return 0, nil, err
}

func (a *API) UpdateGoodsShelfStatus(goodsIDs []int64, isPutAway bool) (err error) {
	_, err = a.AccessAPI("goods/updateGoodsShelfStatus", map[string]interface{}{
		"goodsIdList": goodsIDs,
		"isPutAway":   1 - utils.Bool2Int(isPutAway),
	})
	return err
}

func (a *API) UpdateGoodsTitle(goodsID int64, title string) (err error) {
	_, err = a.AccessAPI("goods/updateGoodsTitle", map[string]interface{}{
		"goodsId": goodsID,
		"title":   title,
	})
	return err
}

func (a *API) FindDeliveryTypeList(goodsID int64) (retVal []*DeliveryType, err error) {
	apiParams := map[string]interface{}{}
	if goodsID > 0 {
		apiParams["goodsId"] = goodsID
	}
	result, err := a.AccessAPI("goods/findDeliveryTypeList", apiParams)
	if err == nil {
		deliveryTypeList := result.(map[string]interface{})["deliveryTypeList"].([]interface{})
		retVal = make([]*DeliveryType, len(deliveryTypeList))
		for k, v := range deliveryTypeList {
			mapData := v.(map[string]interface{})
			retVal[k] = &DeliveryType{
				DeliveryID:       utils.MustInterface2Int64(mapData["deliveryId"]),
				DeliveryType:     int(utils.MustInterface2Int64(mapData["deliveryType"])),
				DeliveryTypeName: utils.Interface2String(mapData["deliveryTypeName"]),
				Selected:         mapData["selected"].(bool),
			}
		}
		return retVal, nil
	}
	return nil, err
}

func (a *API) UploadImg(imgData []byte, name string) (imgURL string, err error) {
	apiParams := map[string]interface{}{
		"file": imgData,
	}
	if name != "" {
		apiParams["name"] = name
	}
	result, err := a.AccessAPI("goodsImage/uploadImg", apiParams)
	if err == nil {
		urlInfo := result.(map[string]interface{})["urlInfo"].([]interface{})
		if len(urlInfo) > 0 {
			urlInfo0 := urlInfo[0].(map[string]interface{})
			if utils.MustInterface2Int64(urlInfo0["legalStatus"]) == 0 {
				return utils.Interface2String(urlInfo0["url"]), nil
			}
			return "", fmt.Errorf("上传的图片:%s不合法", name)
		}
		return "", fmt.Errorf("上传的图片:%s返回为空", name)
	}
	return "", err
}

func (a *API) UploadImgByURL(uploadImgURL string, name string) (imgURL string, err error) {
	response, err := http.Get(uploadImgURL)
	if err == nil {
		defer func() {
			response.Body.Close()
		}()
		if response.StatusCode == http.StatusOK {
			bodyData, err2 := ioutil.ReadAll(response.Body)
			if err = err2; err == nil {
				return a.UploadImg(bodyData, name)
			}
		} else {
			err = platformapi.ErrHTTPCodeIsNot200
		}
	}
	return "", err
}

func (a *API) FindFreightTemplateList(goodsID int64) (freightTemplateListInfo *FindFreightTemplateListInfo, err error) {
	apiParams := map[string]interface{}{}
	if goodsID > 0 {
		apiParams["goodsId"] = goodsID
	}
	result, err := a.AccessAPI("goods/findFreightTemplateList", apiParams)
	if err == nil {
		data := result.(map[string]interface{})
		err = utils.Map2StructByJson(data, &freightTemplateListInfo, false)
		return freightTemplateListInfo, nil
	}
	return nil, err
}
