package db

import (
	"context"
	"github.com/sirupsen/logrus"
	"youngee_b_api/consts"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"

	"gorm.io/gorm"
)

func CreateProduct(ctx context.Context, product gorm_model.YounggeeProduct) (*int64, error) {
	db := GetReadDB(ctx)
	err := db.Create(&product).Error
	if err != nil {
		return nil, err
	}
	return &product.ProductID, nil
}

func UpdateProduct(ctx context.Context, product gorm_model.YounggeeProduct) (*int64, error) {
	db := GetReadDB(ctx)
	err := db.Model(&product).Updates(product).Error
	if err != nil {
		return nil, err
	}
	return &product.ProductID, nil
}

func GetProductByEnterpriseID(ctx context.Context, enterpriseID string) ([]gorm_model.YounggeeProduct, error) {
	db := GetReadDB(ctx)
	products := []gorm_model.YounggeeProduct{}
	err := db.Where("enterprise_id = ?", enterpriseID).Find(&products).Error
	if err != nil {
		return nil, err
	}
	return products, nil
}

func GetProductByID(ctx context.Context, productID int64) (*gorm_model.YounggeeProduct, error) {
	db := GetReadDB(ctx)
	product := &gorm_model.YounggeeProduct{}
	err := db.First(&product, productID).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return product, nil
}

func GetProductIDByName(ctx context.Context, brandName string, productName string) (*int64, error) {
	db := GetReadDB(ctx)
	product := &gorm_model.YounggeeProduct{}
	err := db.Where("product_name = ? AND brand_name = ?", productName, brandName).First(&product).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &product.ProductID, nil
}

func GetProductInfoBySelectionId(ctx context.Context, selectionId string) (*gorm_model.YounggeeProduct, error) {
	db := GetReadDB(ctx)
	productId := 0
	err := db.Model(gorm_model.YounggeeSelectionInfo{}).Select("product_id").Where("selection_id = ?", selectionId).Find(&productId).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProductInfo] error query mysql, err:%+v", err)
		return nil, err
	}
	productInfo := gorm_model.YounggeeProduct{}
	err = db.Model(gorm_model.YounggeeProduct{}).Where("product_id = ?", productId).Find(&productInfo).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProductInfo] error query mysql, err:%+v", err)
		return nil, err
	}
	return &productInfo, nil
}

func GetProductPhotoInfoBySelectionId(ctx context.Context, selectionId string) ([]*gorm_model.YounggeeProductPhoto, error) {
	db := GetReadDB(ctx)
	productId := 0
	err := db.Model(gorm_model.YounggeeSelectionInfo{}).Select("product_id").Where("selection_id = ?", selectionId).Find(&productId).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProductInfo] error query mysql, err:%+v", err)
		return nil, err
	}
	var productPhotoInfo []*gorm_model.YounggeeProductPhoto
	err = db.Model(gorm_model.YounggeeProductPhoto{}).Where("product_id = ?", productId).Find(&productPhotoInfo).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProductInfo] error query mysql, err:%+v", err)
		return nil, err
	}
	return productPhotoInfo, nil
}

func GetAllProduct(ctx context.Context, req *http_model.GetAllProductRequest, enterpriseID string) ([]*http_model.ProjectBriefInfo, int64, error) {
	var ProjectBriefInfos []*http_model.ProjectBriefInfo
	db := GetReadDB(ctx)
	var projectInfos []*gorm_model.ProjectInfo
	db = db.Debug().Model(gorm_model.ProjectInfo{}).Where("project_status>2")
	if req.Platform != 0 {
		db = db.Model(gorm_model.ProjectInfo{}).Where("project_platform = ?", req.Platform)
	}
	if req.FeeForm != 0 {
		db = db.Model(gorm_model.ProjectInfo{}).Where("fee_form = ?", req.FeeForm)
	}
	if req.ProjectForm != 0 {
		db = db.Model(gorm_model.ProjectInfo{}).Where("project_form = ?", req.ProjectForm)
	}
	// 查询总数
	var total int64
	if err := db.Count(&total).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetAllProduct] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	// 查询该页数据
	limit := req.PageSize
	offset := req.PageSize * req.PageNum // assert pageNum start with 0
	err := db.Order("submit_at desc").Limit(int(limit)).Offset(int(offset)).Find(&projectInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetSelectionList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	projectIdToRecruitStrategy := make(map[string][]*gorm_model.RecruitStrategy)
	platformToPlatformIcon := make(map[int64]string)
	projectIdToSignNum := make(map[string]int64)
	for _, projectInfo := range projectInfos {
		var RecruitStrategys []*gorm_model.RecruitStrategy
		db1 := GetReadDB(ctx)
		err := db1.Debug().Model(gorm_model.RecruitStrategy{}).Where("project_id = ?", projectInfo.ProjectID).Find(&RecruitStrategys).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[GetAllProduct] error query RecruitStrategys, err:%+v", err)
			return nil, 0, err
		}
		projectIdToRecruitStrategy[projectInfo.ProjectID] = RecruitStrategys
	}
	for _, projectInfo := range projectInfos {
		PlatformIcon := ""
		db1 := GetReadDB(ctx)
		err := db1.Debug().Model(gorm_model.InfoThirdPlatform{}).Select("platform_icon").Where("platform_id = ?", projectInfo.ProjectPlatform).Find(&PlatformIcon).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[GetAllProduct] error query PlatformIcon, err:%+v", err)
			return nil, 0, err
		}
		platformToPlatformIcon[projectInfo.ProjectPlatform] = PlatformIcon
	}
	for _, projectInfo := range projectInfos {
		var SignNum int64
		db1 := GetReadDB(ctx)
		err := db1.Debug().Model(gorm_model.YoungeeTaskInfo{}).Where("project_id = ?", projectInfo.ProjectID).Count(&SignNum).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[GetAllProduct] error query SignNum, err:%+v", err)
			return nil, 0, err
		}
		projectIdToSignNum[projectInfo.ProjectID] = SignNum
	}
	for _, projectInfo := range projectInfos {
		ProjectBriefInfo := new(http_model.ProjectBriefInfo)
		ProjectBriefInfo.ProjectID = projectInfo.ProjectID
		ProjectBriefInfo.ProjectForm = projectInfo.ProjectForm
		ProjectBriefInfo.ProjectName = projectInfo.ProjectName
		ProjectBriefInfo.ProductSnap = projectInfo.ProductSnap
		ProjectBriefInfo.ProductPhotoSnap = projectInfo.ProductPhotoSnap
		ProjectBriefInfo.Platform = consts.GetProjectPlatform(projectInfo.ProjectPlatform)
		ProjectBriefInfo.PlatformIcon = platformToPlatformIcon[projectInfo.ProjectPlatform]
		ProjectBriefInfo.RecruitStrategys = projectIdToRecruitStrategy[projectInfo.ProjectID]
		ProjectBriefInfo.SignNum = projectIdToSignNum[projectInfo.ProjectID]
		ProjectBriefInfos = append(ProjectBriefInfos, ProjectBriefInfo)
	}
	return ProjectBriefInfos, total, nil
}

func GetProductType(ctx context.Context, selectionId string) (*int, error) {
	db := GetReadDB(ctx)
	var productId int
	err := db.Model(gorm_model.YounggeeSelectionInfo{}).Select("product_id").Where("selection_id = ?", selectionId).Find(&productId).Error
	if err != nil || productId == 0 {
		logrus.WithContext(ctx).Errorf("[GetProductType] error query mysql, err:%+v", err)
		return nil, err
	}
	var productType int
	err = db.Model(gorm_model.YounggeeProduct{}).Select("product_type").Where("product_id = ?", productId).Find(&productType).Error
	if err != nil || productType == 0 {
		logrus.WithContext(ctx).Errorf("[GetProductType] error query mysql, err:%+v", err)
		return nil, err
	}
	return &productType, nil
}
