package service

import (
	"errors"
	"time"
	"youngee_b_api/app/dao"
	"youngee_b_api/app/entity"
	"youngee_b_api/app/vo"
)

type ProductService struct{}

func (p ProductService) GetTaskProductsByUserId(param vo.GetAllProductParam) (vo.ResultVO, error) {
	if param.Page == 0 {
		param.Page = 1
	}
	if param.PageSize == 0 {
		param.PageSize = 10
	}
	var result vo.ResultVO
	var products []entity.Product
	var err error
	var total int64
	//if param.SubAccountId == 0 {
	//	enterpriseId := param.EnterpriseId
	//	if enterpriseId == "" {
	//		return result, errors.New("enterpriseId is empty")
	//	}
	//	products, total, err = (&dao.ProductDAO{}).GetProductsByEnterpriseID(enterpriseId, param.Page, param.PageSize)
	//} else {
	//	products, total, err = (&dao.ProductDAO{}).GetProductsBySubAccountId(param.SubAccountId, param.Page, param.PageSize)
	//}
	enterpriseId := param.EnterpriseId
	if enterpriseId == "" {
		return result, errors.New("enterpriseId is empty")
	}
	products, total, err = (&dao.ProductDAO{}).GetProductsByEnterpriseIDAndTypeTitle(enterpriseId, param.ProductType, param.ProductTitle, param.Page, param.PageSize)
	if err != nil {
		// 数据库查询error
		return result, err
	}
	var reProducts []vo.ReProductPreview
	for _, product := range products {
		var createrName string
		photoUrl, e := dao.ProductPhotoDAO{}.GetMainPhotoByProductID(product.ProductID)
		if e != nil {
			photoUrl = ""
		}
		if product.SubAccountID == 0 {
			enterprise, err := dao.EnterpriseDao{}.GetEnterprise(product.EnterpriseID)
			if err == nil && enterprise != nil {
				createrName = enterprise.BusinessName
			}
		} else {
			subAccount, err := dao.SubAccountDao{}.GetSubAccount(product.SubAccountID)
			if err == nil && subAccount != nil {
				createrName = subAccount.SubAccountName
			}
		}
		reProduct := vo.ReProductPreview{
			ProductID:       product.ProductID,
			ProductName:     product.ProductName,
			ProductType:     product.ProductType,
			ProductCategory: product.ProductCategory,
			ProductPrice:    product.ProductPrice,
			ProductDetail:   product.ProductDetail,
			CreatedAt:       product.CreatedAt.Format("2006-01-02 15:04:05"),
			PhotoUrl:        photoUrl,
			CreateName:      createrName,
		}
		reProducts = append(reProducts, reProduct)
	}
	result = vo.ResultVO{
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    total,
		Data:     reProducts,
	}
	return result, nil
}

func (p ProductService) CreateProduct(productCreateParam *vo.ProductCreateParam) (int64, error) {
	if len(productCreateParam.ProductPhotos) == 0 {
		return 0, errors.New("商品主图不能为空！")
	}
	if productCreateParam.ProductType == 1 {
		count := dao.ProductDAO{}.CheckKuaishouProduct(productCreateParam.EnterpriseId, productCreateParam.ProductId)
		if count > 0 {
			return 0, errors.New("该快手商品已存在！")
		}
	}
	product := entity.Product{
		ProductType:         productCreateParam.ProductType,
		KuaishouProductId:   productCreateParam.ProductId,
		ProductName:         productCreateParam.ProductName,
		ProductCategory:     productCreateParam.ProductCategory,
		ProductPrice:        productCreateParam.ProductPrice,
		ProductDetail:       productCreateParam.ProductDetail,
		EnterpriseID:        productCreateParam.EnterpriseId,
		SubAccountID:        productCreateParam.SubAccountId,
		ExclusiveCommission: productCreateParam.ExclusiveCommission,
		CommissionPrice:     productCreateParam.CommissionPrice,
		PublicCommission:    productCreateParam.PublicCommission,
		ProductUrl:          productCreateParam.ProductUrl,
	}
	productID, err := dao.ProductDAO{}.CreateProduct(product)
	if err != nil {
		return 0, err
	}
	if productCreateParam.ProductPhotos != nil {
		productPhotos := []entity.ProductPhoto{}
		for _, photo := range productCreateParam.ProductPhotos {
			productPhoto := entity.ProductPhoto{
				PhotoUrl:  photo.PhotoUrl,
				PhotoUid:  photo.PhotoUid,
				Symbol:    photo.Symbol,
				ProductID: productID,
				CreatedAt: time.Now(),
			}
			productPhotos = append(productPhotos, productPhoto)
		}
		err = dao.ProductPhotoDAO{}.CreateProductPhoto(productPhotos)
		if err != nil {
			return 0, err
		}
	}
	return productID, nil
}

// 商品详情
func (s ProductService) GetProductDetail(param *vo.ProductSearchParam) (*vo.ReProductInfo, error) {
	var reProductInfo *vo.ReProductInfo
	product, err := dao.ProductDAO{}.GetProductByID(param.ProductId)
	if err != nil {
		return nil, err
	}
	photoMain, _ := dao.ProductPhotoDAO{}.GetMainPhotoByProductID(param.ProductId)
	photosAll, _ := dao.ProductPhotoDAO{}.GetProductPhotoByProductID(param.ProductId)
	var photoRotates []vo.Photo
	var photoDetails []vo.Photo
	for _, photosOne := range photosAll {
		if photosOne.Symbol == 2 || photosOne.Symbol == 3 {
			photo := vo.Photo{
				PhotoUrl: photosOne.PhotoUrl,
				Symbol:   photosOne.Symbol,
			}
			photoRotates = append(photoRotates, photo)
		} else if photosOne.Symbol == 4 || photosOne.Symbol == 5 {
			photo := vo.Photo{
				PhotoUrl: photosOne.PhotoUrl,
				Symbol:   photosOne.Symbol,
			}
			photoDetails = append(photoDetails, photo)
		}
	}
	reProductInfo = &vo.ReProductInfo{
		ProductID:           product.ProductID,
		ProductName:         product.ProductName,
		ProductCategory:     product.ProductCategory,
		ProductPrice:        product.ProductPrice,
		ExclusiveCommission: product.ExclusiveCommission,
		CommissionPrice:     product.CommissionPrice,
		ProductDetail:       product.ProductDetail,
		ProductUrl:          product.ProductUrl,
		PhotoMain:           photoMain,
		PhotoRotates:        photoRotates,
		PhotoDetails:        photoDetails,
		CreatedAt:           product.CreatedAt.Format("2006-01-02 15:04:05"),
	}

	return reProductInfo, nil
}

// 更新商品
func (p ProductService) UpdateProduct(param *vo.ProductUpdateParam) (int64, error) {
	newProduct := entity.Product{
		ProductID:           param.ProductId,
		ProductName:         param.ProductName,
		ProductCategory:     param.ProductCategory,
		ProductPrice:        param.ProductPrice,
		ExclusiveCommission: param.ExclusiveCommission,
		CommissionPrice:     param.CommissionPrice,
		ProductDetail:       param.ProductDetail,
		ProductUrl:          param.ProductUrl,
		UpdatedAt:           time.Now(),
	}
	productId, err := dao.ProductDAO{}.UpdateProduct(newProduct)
	if err != nil {
		return 0, err
	}
	if param.ProductPhotos != nil {
		productPhotos := []entity.ProductPhoto{}
		for _, photo := range param.ProductPhotos {
			productPhoto := entity.ProductPhoto{
				PhotoUrl:         photo.PhotoUrl,
				PhotoUid:         photo.PhotoUid,
				Symbol:           photo.Symbol,
				StoreID:          productId,
				ProductPhotoType: 1,
				CreatedAt:        time.Now(),
			}
			productPhotos = append(productPhotos, productPhoto)
		}
		err = dao.ProductPhotoDAO{}.CreateProductPhoto(productPhotos)
		if err != nil {
			return 0, err
		}
	}
	return productId, nil
}

// 删除商品
func (p ProductService) DeleteProduct(param *vo.ProductUpdateParam) (int64, error) {
	err := dao.ProductDAO{}.DeleteProduct(param.ProductId)
	if err != nil {
		return 0, err
	}
	return param.ProductId, nil
}

// 商品列表-角标
func (t ProductService) CountProduct(param *vo.GetAllProductParam) map[string]int64 {
	res := make(map[string]int64)
	var commonProduct int64
	var kuaishouProduct int64
	if param.ProductTitle != "" {
		dao.Db.Model(&entity.Product{}).Where("enterprise_id = ? sub_account_id = ? and product_type = ? AND is_deleted = 0 and product_name LIKE ?", param.EnterpriseId, param.SubAccountId, 0, "%"+param.ProductTitle+"%").Count(&commonProduct)
		dao.Db.Model(&entity.Product{}).Where("enterprise_id = ? sub_account_id = ? and product_type = ? AND is_deleted = 0 and product_name LIKE ?", param.EnterpriseId, param.SubAccountId, 1, "%"+param.ProductTitle+"%").Count(&kuaishouProduct)

	} else {
		dao.Db.Model(&entity.Product{}).Where("enterprise_id = ? sub_account_id = ? and product_type = ? AND is_deleted = 0", param.EnterpriseId, param.SubAccountId, 0).Count(&commonProduct)
		dao.Db.Model(&entity.Product{}).Where("enterprise_id = ? sub_account_id = ? and product_type = ? AND is_deleted = 0", param.EnterpriseId, param.SubAccountId, 1).Count(&kuaishouProduct)

	}
	res["commonProduct"] = commonProduct
	res["kuaishouProduct"] = kuaishouProduct

	return res
}

// 获取商品类目
func (p ProductService) GetProductCategorys() ([]string, error) {
	var categorys []string
	productCategorys, err := dao.ProductDAO{}.GetProductCategorys()
	if err != nil {
		return nil, err
	}
	for _, productCategory := range productCategorys {
		categorys = append(categorys, productCategory.ProductCategory)
	}
	return categorys, nil
}
