package merchant

import (
	"errors"
	logger "eta/eta_mini_ht_api/common/component/log"
	"eta/eta_mini_ht_api/common/utils/page"
	stringUtils "eta/eta_mini_ht_api/common/utils/string"
	reportDomain "eta/eta_mini_ht_api/domian/report"
	merchantDao "eta/eta_mini_ht_api/models/merchant"
	"gorm.io/gorm"
	"strings"
	"sync/atomic"
	"time"
)

var (
	typeTransfer = map[merchantDao.MerchantProductType]string{
		merchantDao.Report:  "单篇报告",
		merchantDao.Video:   "单个视频",
		merchantDao.Audio:   "单个音频",
		merchantDao.Package: "套餐",
	}
	typeKindTransfer = map[string]merchantDao.MerchantProductType{
		"report":  merchantDao.Report,
		"video":   merchantDao.Video,
		"audio":   merchantDao.Audio,
		"package": merchantDao.Package,
	}
)

type MerchantProductDTO struct {
	Id          int
	Title       string
	CoverSrc    int
	CoverUrl    string
	Description string
	Price       string
	ProductTile string
	RiskLevel   string
	Type        string
	TypeCN      string
	IsPermanent bool
	ValidDays   int
	SaleStatus  string
	SourceId    int
	CreatedTime time.Time
}

func GetMerchantProductById(id int) (productDTO MerchantProductDTO, err error) {
	product, err := merchantDao.GetMerchantProductById(id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			logger.Error("商品信息不存在[productId:%d]", id)
		} else {
			logger.Error("获取商品信息失败[productId:%d],err:", id, err)
		}
	}
	productDTO = convertToDTO(product)
	return
}
func convertToDTO(product merchantDao.MerchantProduct) MerchantProductDTO {
	return MerchantProductDTO{
		Id:          product.ID,
		Title:       product.Title,
		CoverSrc:    product.CoverSrc,
		CoverUrl:    product.CoverUrl,
		Description: product.Description,
		ProductTile: product.Title,
		Price:       product.Price,
		RiskLevel:   "",
		Type:        string(product.Type),
		TypeCN:      typeTransfer[product.Type],
		IsPermanent: product.IsPermanent,
		ValidDays:   product.ValidDays,
		SourceId:    product.SourceID,
		CreatedTime: product.CreatedTime,
	}
}

func GetProductBySourceId(id int, productType merchantDao.MerchantProductType) (product MerchantProductDTO, err error) {
	productDao, err := merchantDao.GetMerchantProductBySourceId(id, productType)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			logger.Error("商品信息不存在[sourceId:%d,type:%v]", id, productType)
		} else {
			logger.Error("获取商品信息失败[sourceId:%d,type:%v],err:%v", id, productType, err)
		}
		return
	}
	product = convertToDTO(productDao)
	return
}

func GetProductListBySourceIds(ids []int, productType string) (productDTOS []MerchantProductDTO, err error) {
	productList, err := merchantDao.GetProductListBySourceIds(ids, true, typeKindTransfer[productType])
	if err != nil {
		logger.Error("获取商品列表失败[sourceIds:%v,type:%v],err:%v", ids, productType, err)
		return
	}
	for _, product := range productList {
		productDTO := convertToDTO(product)
		productDTOS = append(productDTOS, productDTO)
	}
	return
}

func GetProductListByProductType(productType string) (list []MerchantProductDTO, err error) {
	productList, err := merchantDao.GetProductListByProductType(typeKindTransfer[productType], true)
	for _, product := range productList {
		productDTO := convertToDTO(product)
		list = append(list, productDTO)
	}
	return
}

func GetProductPageByProductType(productIds []int, info page.PageInfo) (dtoList []MerchantProductDTO, err error) {
	offset := page.StartIndex(info.Current, info.PageSize)
	productList, err := merchantDao.GetProductPageByProductType(productIds, info.LatestId, offset, info.PageSize)
	if err != nil {
		logger.Error("获取商品列表失败[productIds:%v,pageInfo:%v],err:%v", productIds, info, err)
		return
	}
	for _, productInfo := range productList {
		productDTO := convertToDTO(productInfo)
		dtoList = append(dtoList, productDTO)
	}
	return
}

func GetProductByProductType() (productIdMap map[string][]int, err error) {
	productMap, err := merchantDao.GetProductByProductType()
	if err != nil {
		logger.Error("根据类型分类获取商品ID失败,err:%v", err)
		return
	}
	productIdMap = make(map[string][]int, len(productMap))
	for productType, productIds := range productMap {
		idStr := strings.Split(productIds, ",")
		productIdMap[productType], _ = stringUtils.StringToIntSlice(idStr)
	}
	return
}

func LatestId() (latestId int64) {

	return merchantDao.LatestId()
}

func ProductListBySort(isSignal bool, list []reportDomain.ProductSearchDTO, weightMap map[int]*atomic.Int32, info page.PageInfo) (productDTOS []MerchantProductDTO, err error) {
	offset := page.StartIndex(info.Current, info.PageSize)
	var productList []merchantDao.MerchantProduct
	if isSignal {
		var searchList []merchantDao.ProductDTO
		for _, product := range list {
			searchList = append(searchList, merchantDao.ProductDTO{
				SourceId:   product.SourceId,
				SourceType: product.SourceType,
				Score:      product.Score,
			})
		}
		productList, err = merchantDao.ProductListBySort(searchList, info.LatestId, offset, info.PageSize)
		if err != nil {
			return
		}

	} else {
		productList, err = merchantDao.PackageListBySort(weightMap, info.LatestId, offset, info.PageSize)
		if err != nil {
			return
		}
	}
	for _, productInfo := range productList {
		productDTOS = append(productDTOS, convertToDTO(productInfo))
	}
	return
}

func GetOffSaleProducts(productTypeList []string) (dtoList []MerchantProductDTO, err error) {
	var productTypeQuery []merchantDao.MerchantProductType
	for _, productType := range productTypeList {
		productTypeQuery = append(productTypeQuery, typeKindTransfer[productType])
	}
	list, err := merchantDao.GetOffSaleProducts(productTypeQuery)
	for _, product := range list {
		dtoList = append(dtoList, convertToDTO(product))
	}
	return
}