package tiktok_api

import (
	"errors"
	material_batchUploadImageSync_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/material_batchUploadImageSync/request"
	material_batchUploadImageSync_response "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/material_batchUploadImageSync/response"
	material_createFolder_request "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/material_createFolder/request"
	material_createFolder_response "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/sdk-golang/api/material_createFolder/response"
)

// CreateFolder 创建商品库文件夹(存放商品图片素材)
//1. 文件夹名称最多20个字符
//2. 每个文件夹下最多包含100个子文件夹
//3. 文件夹的最大层级为10层
//4. 一个父文件夹下的子文件夹不允许重名
//5. 累计创建的文件夹数量不能超过10万
func (a *API) CreateFolder(fileName string) (*material_createFolder_response.MaterialCreateFolderResponse, error) {
	request := material_createFolder_request.New()
	param := request.GetParams()
	param.Name = fileName
	if param.Name == "" {
		param.Name = "jxcs_folder2"
	}
	param.ParentFolderId = "0" // 根目录创建文件夹

	result, err := request.Execute(a.accessTokenObj)
	if err != nil {
		return nil, err
	}
	if result.Code != RequestSuccessCode {
		return nil, errors.New(result.SubMsg + ":" + result.LogId)
	}
	return result, nil
}

// BatchUploadImages 批量上传文件到目录
//1. 一次上传的数量限制50张图片；
//2. 图片大小限10M
//3. 素材中心会对素材进行异步审核，对于审核失败的素材，素材中心会在一定时间内将其删除。
func (a *API) BatchUploadImages(imgs []Imgs) (map[string]material_batchUploadImageSync_response.SuccessMapItem, error) {
	request := material_batchUploadImageSync_request.New()
	var param = make([]material_batchUploadImageSync_request.MaterialsItem, 0, len(imgs))

	for i := 0; i < len(imgs); i++ {
		img := material_batchUploadImageSync_request.MaterialsItem{
			RequestId:    imgs[i].Name,
			MaterialType: "photo",
			Name:         imgs[i].Name,
			Url:          imgs[i].Url,
		}
		switch a.accessTokenObj.ShopId {
		case TiktokFloderKeyTestKey:
			img.FolderId = TiktokFolder3
		case TiktokFloderKeyShoppingKey:
			img.FolderId = TiktokShoppingFolder
		case TiktokFloderKeyVegetableKey:
			img.FolderId = TiktokFolder1
		case TiktokFloderKeyBeautifulKey:
			img.FolderId = TiktokFolder4
		case 260477060:
			img.FolderId = "0"
		}
		param = append(param, img)
	}

	imgParam := request.GetParams()
	imgParam.Materials = param
	imgParam.NeedDistinct = true
	result, err := request.Execute(a.accessTokenObj)
	if err != nil {
		return nil, err
	}
	if result.Code != RequestSuccessCode {
		return nil, errors.New("logId" + result.LogId + ":" + result.SubMsg)
	}
	if len(result.Data.SuccessMap) > 0 {
		return result.Data.SuccessMap, nil
	}

	return nil, err
}
