package product

import (
	logger "eta/eta_mini_ht_api/common/component/log"
	"eta/eta_mini_ht_api/common/utils/page"
	"eta/eta_mini_ht_api/domian/merchant"
	"sync"
	"time"
)

type SubscribeDTO struct {
	Title           string   `json:"title"`
	Abstract        string   `json:"abstract"`
	SourceId        int      `json:"sourceId"`
	SourceTitle     string   `json:"sourceTitle"`
	SourceAbstract  string   `json:"sourceAbstract"`
	SourceSrc       string   `json:"sourceSrc"`
	Type            string   `json:"type"`
	RiskLevel       string   `json:"riskLevel"`
	CoverUrl        string   `json:"coverUrl"`
	PermissionNames []string `json:"permissionNames"`
	CreatedDate     string   `json:"createdDate"`
}

func SubscribeList(templateUserId int, productType string, pageInfo page.PageInfo) (list []SubscribeDTO, err error) {
	var subscribeList []merchant.UserAccessDTO
	subscribeList, err = merchant.SubscribeList(templateUserId, productType, pageInfo)
	var wg sync.WaitGroup
	wg.Add(len(subscribeList))
	for _, Subscribe := range subscribeList {
		go func(Subscribe merchant.UserAccessDTO) {
			defer wg.Done()
			product, _ := merchant.GetMerchantProductById(Subscribe.ProductID)
			subscribe := convertToSubscribeDTO(product)
			if err != nil {
				logger.Error("获取风险等级失败[productId:%d]", product.Id)
			}
			switch product.Type {
			case "audio", "video":
				subscribe.RiskLevel, subscribe.SourceTitle, _, subscribe.CoverUrl, subscribe.SourceSrc, subscribe.PermissionNames, _, err = GetProductRiskLevel(product)
			case "report":
				subscribe.RiskLevel, subscribe.SourceTitle, subscribe.SourceAbstract, subscribe.CoverUrl, _, subscribe.PermissionNames, _, err = GetProductRiskLevel(product)
			case "package":
				subscribe.RiskLevel, _, _, subscribe.CoverUrl, _, subscribe.PermissionNames, _, err = GetProductRiskLevel(product)
			default:
				logger.Error("未知产品类型[productType:%s]", product.Type)
				return
			}
			list = append(list, subscribe)
		}(Subscribe)
	}
	wg.Wait()
	return
}

func convertToSubscribeDTO(product merchant.MerchantProductDTO) SubscribeDTO {
	return SubscribeDTO{
		SourceId:    product.SourceId,
		Type:        product.Type,
		Title:       product.Title,
		Abstract:    product.Description,
		CoverUrl:    product.CoverUrl,
		CreatedDate: product.CreatedTime.Format(time.DateOnly),
	}
}
func GetTotalUserPageCountByProductType(productType string, templateUserId int) (int64, int64) {
	return merchant.GetTotalUserPageCountByProductType(productType, templateUserId)
}