package tao_vegetable

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability587"
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability587/domain"
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability587/request"
)

// GetStoreAllCategory 获取门店所有分类
func (a *API) GetStoreAllCategory() ([]*CategoryInfo, error) {
	// 获取所有的父分类
	parent, err := a.GetStoreCategoryInfo("")
	if err != nil {
		return nil, err
	}

	result := make([]*CategoryInfo, 0)
	for _, v := range parent.ChildCategorys {
		childNode, err := a.GetStoreCategoryInfo(v.Code)
		if err != nil || childNode == nil {
			result = append(result, &CategoryInfo{
				ChildCategorys: nil,
				Code:           v.Code,
				Desc:           v.Desc,
				ForestId:       v.ForestId,
				Leaf:           v.Leaf,
				Name:           v.Name,
				ParentForestId: v.ParentForestId,
				Status:         v.Status,
			})
			continue
		}
		result = append(result, childNode)
	}

	return result, nil
}

// GetStoreCategoryInfo 获取门店指定分类
func (a *API) GetStoreCategoryInfo(code string) (*CategoryInfo, error) {
	storeCategory := ability587.NewAbility587(&a.client)
	resp, _ := storeCategory.AlibabaWdkSkuCategoryQuery(&request.AlibabaWdkSkuCategoryQueryRequest{Param: &domain.AlibabaWdkSkuCategoryQueryCategoryDo{Code: &code}}, a.token)

	if !*resp.Result.Success {
		return nil, fmt.Errorf("requestId:" + resp.RequestId + "msg:" + *resp.Result.ErrMsg)
	}
	var info *CategoryInfo
	if err := json.Unmarshal([]byte(*resp.Result.Model), &info); err != nil {
		return nil, err
	}

	return info, nil
}

// AddStoreCategoryInfo 添加门店分类
func (a *API) AddStoreCategoryInfo(param *request.AlibabaWdkSkuCategoryAddRequest) (string, error) {
	storeCategory := ability587.NewAbility587(&a.client)
	resp, _ := storeCategory.AlibabaWdkSkuCategoryAdd(param, a.token)

	return *resp.Result.Model, nil
}

// DeleteStoreCategoryInfo 删除门店分类
func (a *API) DeleteStoreCategoryInfo(param *request.AlibabaWdkSkuCategoryDeleteRequest) error {
	return fmt.Errorf("暂不支持删除分类")
	storeCategory := ability587.NewAbility587(&a.client)
	resp, _ := storeCategory.AlibabaWdkSkuCategoryDelete(param, a.token)

	if !*resp.Result.Success {
		return fmt.Errorf(*resp.Result.ErrMsg)
	}

	return nil
}

// UpdateStoreCategoryInfo 修改门店分类
func (a *API) UpdateStoreCategoryInfo(param *request.AlibabaWdkSkuCategoryUpdateRequest) error {
	storeCategory := ability587.NewAbility587(&a.client)
	resp, _ := storeCategory.AlibabaWdkSkuCategoryUpdate(param, a.token)

	if !*resp.Result.Success {
		return fmt.Errorf(*resp.Result.ErrMsg)
	}

	return nil
}
