package db

import (
	"context"
	"github.com/issue9/conv"
	"gorm.io/gorm"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"
)

func GetGoodstalentList(ctx context.Context, request http_model.GetGoodsTalentRequest) (*http_model.GetGoodsTalentListData, error) {
	db := GetReadDB(ctx)

	// 存储达人信息
	var etcoopinfo []gorm_model.EnterpriseTalentCooperate
	query := db.Model(&gorm_model.EnterpriseTalentCooperate{}).Where("enterprise_id = ? AND cooperate_type = ?", request.EnterpriseId, 1)

	// 根据平台筛选
	if request.Platform != nil {
		query.Where("platform = ?", request.Platform)
	}

	// 根据达人名称筛选
	if request.TalentName != "" {
		query = query.Where("talent_name LIKE ?", "%"+request.TalentName+"%")
	}

	if request.Productcategory != nil {
		query = query.Where("FIND_IN_SET(?, product_category) > 0", request.Productcategory)
	}
	// 获取相关的销量信息，可以通过join连接platform_kuaishou_user_info表
	query = query.Joins("JOIN platform_kuaishou_user_info pkui ON pkui.id = enterprise_talent_cooperate.platform_user_id")

	// 根据30天销量区间筛选
	if request.SalesRange != nil {
		if *request.SalesRange == "0-30" {
			query = query.Where("pkui.sale_num_30day BETWEEN ? AND ?", 0, 30)
		} else if *request.SalesRange == "30-100" {
			query = query.Where("pkui.sale_num_30day BETWEEN ? AND ?", 30, 100)
		} else if *request.SalesRange == "100+" {
			query = query.Where("pkui.sale_num_30day > ?", 100)
		}
	}

	// 根据排序字段和排序顺序进行排序
	if len(request.SortField) > 0 && len(request.SortOrder) > 0 && len(request.SortField) == len(request.SortOrder) {
		for i := 0; i < len(request.SortField); i++ {
			sortField := request.SortField[i]
			sortOrder := request.SortOrder[i]
			switch sortField {
			case "fan":
				if sortOrder == "asc" {
					query = query.Order("fan asc")
				} else {
					query = query.Order("fan desc")
				}

			case "sale_num_30day":
				if sortOrder == "asc" {
					query = query.Order("sale_num_30day asc")
				} else {
					query = query.Order("sale_num_30day desc")
				}

			case "sale_num_total":
				if sortOrder == "asc" {
					query = query.Order("sale_num_total asc")
				} else {
					query = query.Order("sale_num_total desc")
				}

			case "cooperate_num":
				if sortOrder == "asc" {
					query = query.Order("cooperate_num asc")
				} else {
					query = query.Order("cooperate_num desc")
				}
			}

		}
	} else {
		// Default sorting if no valid sort parameters
		query = query.Order("create_at asc")
	}

	// 分页查询
	offset := (request.PageNum - 1) * request.PageSize
	query = query.Limit(request.PageSize).Offset(offset)

	// 执行查询
	if err := query.Find(&etcoopinfo).Error; err != nil {
		return nil, err
	}

	// 生成返回的数据
	result := &http_model.GetGoodsTalentListData{
		Total:      conv.MustString(len(etcoopinfo), ""),
		TalentList: make([]*http_model.GoodsTalentInfo, 0),
	}

	for _, item := range etcoopinfo {

		var salesInfo gorm_model.PlatformKuaishouUserInfo
		if err := db.Where("id = ?", item.PlatformUserID).First(&salesInfo).Error; err != nil {
			return nil, err
		}
		fans, _ := conv.Int(salesInfo.Fan)
		result.TalentList = append(result.TalentList, &http_model.GoodsTalentInfo{
			TalentId:    item.TalentId,
			Nickname:    item.TalentName,
			City:        salesInfo.City,
			HeadUrl:     salesInfo.HeadUri,
			FansNum:     fans,
			ThirtySales: salesInfo.SaleNum30Day,
			AccSales:    salesInfo.SaleNumTotal,
			ActualSales: GetActualSales(db, salesInfo.OpenId), //open_id sec_task sale_actual
			AccCoopTime: item.CooperateNum,
			FirCoopFrom: "公海",
		})
	}

	return result, nil
}

func GetActualSales(db *gorm.DB, openid string) int {
	var sectaskinfo []gorm_model.YounggeeSecTaskInfo
	if err := db.Where("open_id = ?", openid).Find(&sectaskinfo).Error; err != nil {
		return 0
	}

	var total int
	for _, item := range sectaskinfo {
		total += item.SaleActual
	}
	return total
}

func GetProjecttalentList(ctx context.Context, request http_model.GetProjectTalentRequest) (*http_model.GetProjectTalentListData, error) {
	db := GetReadDB(ctx)
	// 存储达人信息
	var etcoopinfo []gorm_model.EnterpriseTalentCooperate
	query := db.Model(&gorm_model.EnterpriseTalentCooperate{}).Where("enterprise_id = ? AND cooperate_type = ?", request.EnterpriseId, 2)

	// 根据平台筛选
	if request.Platform != nil {
		query.Where("platform = ?", request.Platform)
	}

	// 根据达人名称筛选
	if request.TalentName != "" {
		query = query.Where("talent_name LIKE ?", "%"+request.TalentName+"%")
	}

	// 获取相关的销量信息，可以通过join连接platform_kuaishou_user_info表
	query = query.Joins("JOIN platform_kuaishou_user_info pkui ON pkui.id = enterprise_talent_cooperate.platform_user_id")

	// 根据排序字段和排序顺序进行排序
	if len(request.SortField) > 0 && len(request.SortOrder) > 0 && len(request.SortField) == len(request.SortOrder) {
		for i := 0; i < len(request.SortField); i++ {
			sortField := request.SortField[i]
			sortOrder := request.SortOrder[i]
			switch sortField {
			case "fan":
				if sortOrder == "asc" {
					query = query.Order("fan asc")
				} else {
					query = query.Order("fan desc")
				}

			case "like_num":
				if sortOrder == "asc" {
					query = query.Order("like_num asc")
				} else {
					query = query.Order("like_num desc")
				}

			case "sale_num_total":
				if sortOrder == "asc" {
					query = query.Order("sale_num_total asc")
				} else {
					query = query.Order("sale_num_total desc")
				}

			case "cooperate_num":
				if sortOrder == "asc" {
					query = query.Order("cooperate_num asc")
				} else {
					query = query.Order("cooperate_num desc")
				}
			}

		}
	} else {
		// Default sorting if no valid sort parameters
		query = query.Order("create_at asc")
	}

	// 分页查询
	offset := (request.PageNum - 1) * request.PageSize
	query = query.Limit(request.PageSize).Offset(offset)

	// 执行查询
	if err := query.Find(&etcoopinfo).Error; err != nil {
		return nil, err
	}

	// 生成返回的数据
	result := &http_model.GetProjectTalentListData{
		Total:      conv.MustString(len(etcoopinfo), ""),
		TalentList: make([]*http_model.ProjectTalentInfo, 0),
	}

	for _, item := range etcoopinfo {

		var salesInfo gorm_model.PlatformKuaishouUserInfo
		if err := db.Where("id = ?", item.PlatformUserID).First(&salesInfo).Error; err != nil {
			return nil, err
		}
		fans, _ := conv.Int(salesInfo.Fan)
		var taskinfo gorm_model.YoungeeTaskInfo
		if err := db.Where(gorm_model.YoungeeTaskInfo{TaskID: item.ProjectTaskID}).First(&taskinfo).Error; err != nil {
			return nil, err
		}
		var projectinfo gorm_model.ProjectInfo
		err := db.Model(&gorm_model.ProjectInfo{}).Where("project_id = ?", taskinfo.ProjectID).First(&projectinfo).Error
		if err != nil {
			return nil, err
		}
		s_type, s_name := stype(db, taskinfo.SupplierId, taskinfo.SupplierStatus, projectinfo.ProjectType)
		result.TalentList = append(result.TalentList, &http_model.ProjectTalentInfo{
			TalentId:     item.TalentId,
			Nickname:     item.TalentName,
			City:         salesInfo.City,
			HeadUrl:      salesInfo.HeadUri,
			FansNum:      fans,
			AccInteract:  0,
			AccPlay:      0,
			AvgCollected: 0,
			AvgComments:  0,
			AvgLikes:     0,
			AccCoopTime:  item.CooperateNum,
			FirCoopFrom:  s_name,
			Stype:        s_type,
		})
	}

	return result, nil
}

func GetLocallifetalentList(ctx context.Context, request http_model.GetLocallifeTalentRequest) (*http_model.GetLocallifeTalentListData, error) {
	db := GetReadDB(ctx)
	// 存储达人信息
	var etcoopinfo []gorm_model.EnterpriseTalentCooperate
	query := db.Model(&gorm_model.EnterpriseTalentCooperate{}).Where("enterprise_id = ? AND cooperate_type = ?", request.EnterpriseId, 2)

	// 根据平台筛选
	if request.Platform != nil {
		query.Where("platform = ?", request.Platform)
	}

	// 根据达人名称筛选
	if request.TalentName != "" {
		query = query.Where("talent_name LIKE ?", "%"+request.TalentName+"%")
	}

	// 获取相关的销量信息，可以通过join连接platform_kuaishou_user_info表
	query = query.Joins("JOIN platform_kuaishou_user_info pkui ON pkui.id = enterprise_talent_cooperate.platform_user_id")

	// 根据排序字段和排序顺序进行排序
	if len(request.SortField) > 0 && len(request.SortOrder) > 0 && len(request.SortField) == len(request.SortOrder) {
		for i := 0; i < len(request.SortField); i++ {
			sortField := request.SortField[i]
			sortOrder := request.SortOrder[i]
			switch sortField {
			case "fan":
				if sortOrder == "asc" {
					query = query.Order("fan asc")
				} else {
					query = query.Order("fan desc")
				}

			case "like_num":
				if sortOrder == "asc" {
					query = query.Order("like_num asc")
				} else {
					query = query.Order("like_num desc")
				}

			case "sale_num_total":
				if sortOrder == "asc" {
					query = query.Order("sale_num_total asc")
				} else {
					query = query.Order("sale_num_total desc")
				}

			case "cooperate_num":
				if sortOrder == "asc" {
					query = query.Order("cooperate_num asc")
				} else {
					query = query.Order("cooperate_num desc")
				}
			}

		}
	} else {
		// Default sorting if no valid sort parameters
		query = query.Order("create_at asc")
	}

	// 分页查询
	offset := (request.PageNum - 1) * request.PageSize
	query = query.Limit(request.PageSize).Offset(offset)

	// 执行查询
	if err := query.Find(&etcoopinfo).Error; err != nil {
		return nil, err
	}

	// 生成返回的数据
	result := &http_model.GetLocallifeTalentListData{
		Total:      conv.MustString(len(etcoopinfo), ""),
		TalentList: make([]*http_model.LocallifeTalentInfo, 0),
	}

	for _, item := range etcoopinfo {

		var salesInfo gorm_model.PlatformKuaishouUserInfo
		if err := db.Where("id = ?", item.PlatformUserID).First(&salesInfo).Error; err != nil {
			return nil, err
		}
		fans, _ := conv.Int(salesInfo.Fan)
		var taskinfo gorm_model.YoungeeLocalTaskInfo
		if err := db.Where(gorm_model.YoungeeLocalTaskInfo{TaskId: item.LocalTaskID}).First(&taskinfo).Error; err != nil {
			return nil, err
		}
		var projectinfo gorm_model.YounggeeLocalLifeInfo
		err := db.Model(&gorm_model.YounggeeLocalLifeInfo{}).Where("local_id = ?", taskinfo.LocalId).First(&projectinfo).Error
		if err != nil {
			return nil, err
		}
		s_type, s_name := stype(db, taskinfo.SupplierId, taskinfo.SupplierStatus, projectinfo.LocalType)
		result.TalentList = append(result.TalentList, &http_model.LocallifeTalentInfo{
			TalentId:     item.TalentId,
			Nickname:     item.TalentName,
			City:         salesInfo.City,
			HeadUrl:      salesInfo.HeadUri,
			FansNum:      fans,
			AccInteract:  0,
			AccPlay:      0,
			AvgCollected: 0,
			AvgComments:  0,
			AvgLikes:     0,
			AccCoopTime:  item.CooperateNum,
			FirCoopFrom:  s_name,
			SType:        s_type,
		})
	}

	return result, nil
}

func GetTalentNum(ctx context.Context, request http_model.GetTalentNumRequest) (*http_model.GetTalentNumResponse, error) {
	db := GetReadDB(ctx)
	var sectalent, projtalent, localtalent int64
	sectalent, _ = GetTalentnum(db, request, 1)
	projtalent, _ = GetTalentnum(db, request, 2)
	localtalent, _ = GetTalentnum(db, request, 3)
	count := &http_model.GetTalentNumResponse{
		SecTalentnum:     sectalent,
		ProjectTalentnum: projtalent,
		LocalTalentnum:   localtalent,
	}
	return count, nil
}

func GetTalentnum(db *gorm.DB, request http_model.GetTalentNumRequest, cooptype int) (int64, error) {
	query := db.Model(&gorm_model.EnterpriseTalentCooperate{}).Where("enterprise_id = ? AND cooperate_type = ?", request.EnterpriseId, cooptype)
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return 0, err
	}
	return total, nil

}
