package service

import (
	"context"
	"fmt"
	"github.com/lin-jim-leon/kuaishou"
	"math/rand"
	"strconv"
	"strings"
	"time"
	"youngee_b_api/consts"
	"youngee_b_api/db"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"
)

var Product *product

type product struct {
}

func (*product) Create(ctx context.Context, newProduct http_model.CreateProductRequest, enterpriseID string) (*http_model.CreateProductData, error) {
	product := gorm_model.YounggeeProduct{
		ProductName:   newProduct.ProductName,
		ProductType:   newProduct.ProductType,
		ShopAddress:   newProduct.ShopAddress,
		ProductPrice:  newProduct.ProductPrice,
		ProductDetail: newProduct.ProductDetail,
		ProductUrl:    newProduct.ProductUrl,
		EnterpriseID:  enterpriseID,
		BrandName:     newProduct.BrandName,
	}
	productID, err := db.CreateProduct(ctx, product)
	if err != nil {
		return nil, err
	}
	if newProduct.ProductPhotos != nil {
		productPhotos := []gorm_model.YounggeeProductPhoto{}
		for _, photo := range newProduct.ProductPhotos {
			productPhoto := gorm_model.YounggeeProductPhoto{
				PhotoUrl:  photo.PhotoUrl,
				PhotoUid:  photo.PhotoUid,
				Symbol:    photo.Symbol,
				ProductID: *productID,
			}
			productPhotos = append(productPhotos, productPhoto)
		}
		err = db.CreateProductPhoto(ctx, productPhotos)
		if err != nil {
			return nil, err
		}
	}
	res := &http_model.CreateProductData{
		ProductID: *productID,
	}
	return res, nil
}

func (*product) Update(ctx context.Context, newProduct http_model.CreateProductRequest, enterpriseID string) (*http_model.CreateProductData, error) {
	fmt.Println("newProduct.ProductUrl", newProduct.ProductUrl)
	product := gorm_model.YounggeeProduct{
		ProductID:     newProduct.ProductId,
		ProductName:   newProduct.ProductName,
		ProductType:   newProduct.ProductType,
		ShopAddress:   newProduct.ShopAddress,
		ProductPrice:  newProduct.ProductPrice,
		ProductDetail: newProduct.ProductDetail,
		ProductUrl:    newProduct.ProductUrl,
		EnterpriseID:  enterpriseID,
		BrandName:     newProduct.BrandName,
	}
	productID, err := db.UpdateProduct(ctx, product)
	if err != nil {
		return nil, err
	}
	// 删除该商品之前的所有图片
	err = db.DeleteProductPhotoByProductID(ctx, *productID)
	if err != nil {
		return nil, err
	}
	if newProduct.ProductPhotos != nil {
		// 新增图片
		var productPhotos []gorm_model.YounggeeProductPhoto
		for _, photo := range newProduct.ProductPhotos {
			productPhoto := gorm_model.YounggeeProductPhoto{
				PhotoUrl:  photo.PhotoUrl,
				PhotoUid:  photo.PhotoUid,
				Symbol:    photo.Symbol,
				ProductID: *productID,
			}
			productPhotos = append(productPhotos, productPhoto)
		}
		err = db.CreateProductPhoto(ctx, productPhotos)
		if err != nil {
			return nil, err
		}
	}
	res := &http_model.CreateProductData{
		ProductID: *productID,
	}
	return res, nil
}

func (*product) FindAll(ctx context.Context, enterpriseID string) (*http_model.FindAllProductData, error) {
	products, err := db.GetProductByEnterpriseID(ctx, enterpriseID)
	if err != nil {
		// 数据库查询error
		return nil, err
	}
	findAllProductData := http_model.FindAllProductData{}
	for _, product := range products {
		productData := http_model.ProductInfo{
			ProductID:   product.ProductID,
			BrandName:   product.BrandName,
			ProductName: product.ProductName,
			ProductType: consts.GetProjectTypes(product.ProductType),
		}
		findAllProductData.ProductInfos = append(findAllProductData.ProductInfos, productData)
	}
	return &findAllProductData, nil
}

func (*product) FindByID(ctx context.Context, productID int64) (*http_model.FindProductData, error) {
	product, err := db.GetProductByID(ctx, productID)
	if err != nil {
		return nil, err
	}
	if product == nil {
		return nil, nil
	}
	productPhotos, err := db.GetProductPhotoByProductID(ctx, productID)
	if err != nil {
		return nil, err
	}
	findProductData := http_model.FindProductData{
		ProductID:     product.ProductID,
		ProductName:   product.ProductName,
		ProductType:   product.ProductType,
		ShopAddress:   product.ShopAddress,
		ProductPrice:  product.ProductPrice,
		ProductDetail: product.ProductDetail,
		ProductUrl:    product.ProductUrl,
		EnterpriseID:  product.EnterpriseID,
		BrandName:     product.BrandName,
	}
	for _, photo := range productPhotos {
		productPhoto := http_model.ProductPhoto{
			PhotoUrl: photo.PhotoUrl,
			PhotoUid: photo.PhotoUid,
			Symbol:   photo.Symbol,
		}
		findProductData.ProductPhotos = append(findProductData.ProductPhotos, productPhoto)
	}
	return &findProductData, nil
}

func (*product) FindByName(ctx context.Context, brandName string, productName string) (*int64, error) {
	productID, err := db.GetProductIDByName(ctx, brandName, productName)
	if err != nil {
		return nil, err
	}
	return productID, nil
}

func (*product) GetAllProduct(ctx context.Context, req *http_model.GetAllProductRequest, enterpriseID string) (*http_model.ProjectBriefInfoPreview, error) {
	ProjectBriefInfo, total, err := db.GetAllProduct(ctx, req, enterpriseID)
	if err != nil {
		return nil, err
	}
	ProjectBriefInfoPreview := new(http_model.ProjectBriefInfoPreview)
	ProjectBriefInfoPreview.ProjectBriefInfo = ProjectBriefInfo
	ProjectBriefInfoPreview.Total = strconv.FormatInt(total, 10)
	return ProjectBriefInfoPreview, nil
}

// QueryKuaishouProduct 通过快手商品ID从SDK拉取快手商品信息
func (*product) QueryKuaishouProduct(ctx context.Context, newKuaishouProduct http_model.FindKuaishouProductRequest) (*http_model.FindKuaishouProductData, error) {
	appKey := "ks651333097154138217"
	signSecret := "bf6393dce0a2b669ee348bebb837b0da"
	//var SignSecret string = "dBt0rVRhTpUqcrOYGGpv0A"

	// 1. 拿到快手的AccessToken
	kuaishouUserInfo, userErr := db.FindUserInfoByOpenId(ctx, "f1b0d3a11c24fcde14bf5724d0d1cdfc")
	if userErr != nil {
		return nil, userErr
	}

	// 2. 可能需要刷新Token
	//newAccessToken, Tokenerr := kuaishou.RefreshAccessToken(kuaishouUserInfo.RefreshToken, appKey, SignSecret)
	//if Tokenerr != nil {
	//	return nil, Tokenerr
	//}
	//fmt.Println(newAccessToken.AccessToken)

	// 3. 查找对应的快手商品
	kuaishouProduct, err := kuaishou.Queryselectiondetail(appKey, signSecret, kuaishouUserInfo.AccessToken, newKuaishouProduct.ItemList)
	if err != nil {
		fmt.Println("快手错误信息: ", err)
		return nil, err
	}

	// 4. 组织返回数据
	findKuaishouProductData := http_model.FindKuaishouProductData{
		ProductName:                 kuaishouProduct.ItemList[0].ItemTitle,
		ProductPrice:                float64(kuaishouProduct.ItemList[0].ItemPrice) * 0.01,
		ExclusiveCommission:         float64(kuaishouProduct.ItemList[0].CommissionRate) * 0.1,
		CommissionPrice:             float64(kuaishouProduct.ItemList[0].ProfitAmount) * 0.01,
		KuaishouMainPhoto:           kuaishouProduct.ItemList[0].ItemImgURL,
		KuaishouCarousePhotoList:    kuaishouProduct.ItemList[0].ItemGalleryURLs,
		KuaishouDetailPhotoList:     kuaishouProduct.ItemList[0].ItemDescURLs,
		MerchantSoldCountThirtyDays: kuaishouProduct.ItemList[0].MerchantSoldCountThirtyDays,
		KuaishouProductId:           kuaishouProduct.ItemList[0].ItemID,
	}

	// 5. 图片数据结构化
	// 5.1. 主图
	var currProductMainPhoto *http_model.ProductPhoto
	rand.Seed(time.Now().UnixNano())
	currLastIndex := strings.LastIndex(findKuaishouProductData.KuaishouMainPhoto, "/")
	var currDesiredFileName string
	if currLastIndex != -1 {
		currDesiredFileName = findKuaishouProductData.KuaishouMainPhoto[currLastIndex+1:]
	} else {
		currDesiredFileName = "FileNotFound"
	}
	currProductMainPhoto = &http_model.ProductPhoto{
		PhotoUrl: findKuaishouProductData.KuaishouMainPhoto,
		Name:     currDesiredFileName,
		PhotoUid: generateRandomString(10),
		Symbol:   1,
	}
	findKuaishouProductData.ProductPhotos = append(findKuaishouProductData.ProductPhotos, currProductMainPhoto)

	// 5.2. 轮播图
	for _, url := range findKuaishouProductData.KuaishouCarousePhotoList {
		var currProductPhoto *http_model.ProductPhoto
		rand.Seed(time.Now().UnixNano())
		lastIndex := strings.LastIndex(url, "/")
		var desiredFileName string
		if lastIndex != -1 {
			desiredFileName = url[lastIndex+1:]
		} else {
			desiredFileName = "FileNotFound"
		}
		currProductPhoto = &http_model.ProductPhoto{
			PhotoUrl: url,
			Name:     desiredFileName,
			PhotoUid: generateRandomString(10),
			Symbol:   2,
		}
		findKuaishouProductData.ProductPhotos = append(findKuaishouProductData.ProductPhotos, currProductPhoto)
	}

	// 5.3. 详情图
	for _, url := range findKuaishouProductData.KuaishouDetailPhotoList {
		var currProductPhoto *http_model.ProductPhoto
		rand.Seed(time.Now().UnixNano())
		lastIndex := strings.LastIndex(url, "/")
		var desiredFileName string
		if lastIndex != -1 {
			desiredFileName = url[lastIndex+1:]
		} else {
			desiredFileName = "FileNotFound"
		}
		currProductPhoto = &http_model.ProductPhoto{
			PhotoUrl: url,
			Name:     desiredFileName,
			PhotoUid: generateRandomString(10),
			Symbol:   4,
		}
		findKuaishouProductData.ProductPhotos = append(findKuaishouProductData.ProductPhotos, currProductPhoto)
	}
	return &findKuaishouProductData, err
}

const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

var seededRand *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano()))

func generateRandomString(length int) string {
	b := make([]byte, length)
	for i := range b {
		b[i] = charset[seededRand.Intn(len(charset))]
	}
	return string(b)
}

/*
type T struct {
	CreatedAt           time.Time `json:"CreatedAt"`
	UpdatedAt           time.Time `json:"UpdatedAt"`
	ProductUrl          string    `json:"ProductUrl"`
	SalesCount          string    `json:"SalesCount"`
	ProductId           int       `json:"product_id"`
	ProductName         string    `json:"ProductName"`
	ProductType         int       `json:"ProductType"`
	EnterpriseID        string    `json:"EnterpriseID"`
	ProductPrice        int       `json:"ProductPrice"`
	SubAccountID        int       `json:"SubAccountID"`
	ProductDetail       string    `json:"ProductDetail"`
	CommissionPrice     int       `json:"CommissionPrice"`
	ProductCategory     string    `json:"ProductCategory"`
	PublicCommission    int       `json:"PublicCommission"`
	KuaishouProductId   string    `json:"KuaishouProductId"`
	ExclusiveCommission int       `json:"ExclusiveCommission"`
}


type T struct {
	Symbol           int       `json:"Symbol"`
	StoreID          int       `json:"StoreID"`
	PhotoUid         string    `json:"PhotoUid"`
	PhotoUrl         string    `json:"PhotoUrl"`
	CreatedAt        time.Time `json:"CreatedAt"`
	ProductID        int       `json:"ProductID"`
	TeamBuyingID     int       `json:"TeamBuyingID"`
	ProductPhotoID   int       `json:"ProductPhotoID"`
	ProductPhotoType int       `json:"ProductPhotoType"`
}

*/
