package db

import (
	"context"
	"fmt"
	"github.com/sirupsen/logrus"
	"reflect"
	"youngee_b_api/model/common_model"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"
	"youngee_b_api/util"
)

// CreateSProject 新建服务商加入商单后的种草任务
func CreateSProject(ctx context.Context, newSProject gorm_model.SProjectInfo) (int, error) {
	db := GetWriteDB(ctx)
	err := db.Create(&newSProject).Error
	if err != nil {
		return 0, err
	}
	return newSProject.SProjectId, nil
}

// GetSProjectList 根据服务商ID和其他附加条件查询种草任务列表
func GetSProjectList(ctx context.Context, supplierId int, pageSize, pageNum int32, condition *common_model.SProjectCondition) ([]*gorm_model.SProjectInfo, int64, error) {
	db := GetReadDB(ctx)

	// 1. 根据服务商id过滤
	db = db.Debug().Model(gorm_model.SProjectInfo{}).Where("supplier_id = ? and project_status <> 1", supplierId)

	// 2. 根据SProjectCondition条件过滤
	conditionType := reflect.TypeOf(condition).Elem()
	conditionValue := reflect.ValueOf(condition).Elem()
	for i := 0; i < conditionType.NumField(); i++ {
		field := conditionType.Field(i)
		tag := field.Tag.Get("condition")
		value := conditionValue.FieldByName(field.Name)
		if (tag == "project_id" || tag == "project_name") && !util.IsBlank(value) {
			db = db.Where(fmt.Sprintf("project_id like '%%%v%%' or project_name like '%%%v%%'", value.Interface(), value.Interface()))
		} else if !util.IsBlank(value) && tag != "updated_at" {
			db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
		}
	}

	// 3. 确定查询总数和返回当前页数据
	var total int64
	var SProjects []*gorm_model.SProjectInfo
	if err := db.Count(&total).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetFullProjectList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	limit := pageSize
	offset := pageSize * pageNum // assert pageNum start with 0
	err := db.Order("s_project_id desc").Limit(int(limit)).Offset(int(offset)).Find(&SProjects).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetFullProjectList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	return SProjects, total, nil
}

// GetSProjectDetail 查询服务商种草任务详情
func GetSProjectDetail(ctx context.Context, sProjectId int) (*gorm_model.SProjectInfo, error) {
	db := GetReadDB(ctx)
	var sProjectInfo *gorm_model.SProjectInfo
	// 1. 根据服务商种草任务id过滤
	err := db.Model(gorm_model.SProjectInfo{}).Where("s_project_id = ?", sProjectId).Find(&sProjectInfo).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetSProjectDetail] error query mysql, err:%+v", err)
		return nil, err
	}
	return sProjectInfo, nil
}

// GetSpecialProjectList 根据服务商ID和其他附加条件查询定向种草任务列表
func GetSpecialProjectList(ctx context.Context, supplierId int, pageSize, pageNum int32, condition *common_model.SSpecialProjectCondition) ([]*gorm_model.SProjectInfo, int64, error) {
	db := GetReadDB(ctx)

	// 1. 根据服务商id过滤
	db = db.Debug().Model(gorm_model.SProjectInfo{}).Where("supplier_id = ? and project_status = 4 and project_type = 2", supplierId)

	// 2. 根据SProjectCondition条件过滤
	conditionType := reflect.TypeOf(condition).Elem()
	conditionValue := reflect.ValueOf(condition).Elem()
	for i := 0; i < conditionType.NumField(); i++ {
		field := conditionType.Field(i)
		tag := field.Tag.Get("condition")
		value := conditionValue.FieldByName(field.Name)
		if (tag == "project_id" || tag == "project_name") && !util.IsBlank(value) {
			db = db.Where(fmt.Sprintf("project_id like '%%%v%%' or project_name like '%%%v%%'", value.Interface(), value.Interface()))
		} else if !util.IsBlank(value) && tag != "updated_at" {
			db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
		}
	}

	// 3. 确定查询总数和返回当前页数据
	var total int64
	var SProjects []*gorm_model.SProjectInfo
	if err := db.Count(&total).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetFullProjectList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	limit := pageSize
	offset := pageSize * pageNum // assert pageNum start with 0
	err := db.Order("s_project_id desc").Limit(int(limit)).Offset(int(offset)).Find(&SProjects).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetFullProjectList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	return SProjects, total, nil
}

// UpdateSProjectStatus 更新SProject信息
func UpdateSProjectStatus(ctx context.Context, newSProject *http_model.SpecialSProjectAddToListRequest) error {
	db := GetWriteDB(ctx)
	whereCondition := gorm_model.SProjectInfo{SProjectId: newSProject.SProjectId}
	sProjectInfo := gorm_model.SProjectInfo{
		SProjectStatus: newSProject.SProjectStatus,
		SubAccountId:   newSProject.SubAccountId,
		OperatorType:   newSProject.OperatorType,
	}
	err := db.Model(&gorm_model.SProjectInfo{}).Where(whereCondition).Updates(sProjectInfo).Error
	if err != nil {
		return err
	}
	return nil
}

// CreateSpecialStrategy 创建定向种草任务服务商修改后的招募策略
func CreateSpecialStrategy(ctx context.Context, recruitStrategy []gorm_model.RecruitStrategy) error {
	db := GetWriteDB(ctx)
	err := db.Create(&recruitStrategy).Error
	if err != nil {
		return err
	}
	return nil
}

// UpdateSProjectStrategyStatus 修改SProject的招募策略修改标志
func UpdateSProjectStrategyStatus(ctx context.Context, req *http_model.SpecialAddStrategyRequest) error {
	db := GetWriteDB(ctx)
	whereCondition := gorm_model.SProjectInfo{SProjectId: req.SProjectId}
	sProjectInfo := gorm_model.SProjectInfo{
		CreateStrategyId:   req.CreateStrategyId,
		StrategyStatus:     1,
		CreateStrategyType: req.CreateStrategyType,
	}
	err := db.Model(&gorm_model.SProjectInfo{}).Where(whereCondition).Updates(sProjectInfo).Error
	if err != nil {
		return err
	}
	return nil
}

// GetFullSProjectBillList 查询公开种草任务账单列表
func GetFullSProjectBillList(ctx context.Context, supplierId int, ProjectPlatform int, projectStatus int, pageSize, pageNum int32) ([]*gorm_model.SProjectInfo, int64, error) {
	db := GetReadDB(ctx)

	// 1. 根据服务商id过滤
	db = db.Debug().Model(gorm_model.SProjectInfo{}).Where("supplier_id = ? and project_status = ? and project_platform = ?", supplierId, projectStatus, ProjectPlatform)

	// 2. 确定查询总数和返回当前页数据
	var total int64
	var SProjects []*gorm_model.SProjectInfo
	if err := db.Count(&total).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetFullProjectList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	limit := pageSize
	offset := pageSize * pageNum // assert pageNum start with 0
	err := db.Order("s_project_id desc").Limit(int(limit)).Offset(int(offset)).Find(&SProjects).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetFullProjectList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	return SProjects, total, nil
}

// FindSProjectByProjectIdAndSupplierId 根据种草任务ID和服务商ID查找种草任务是否加入商单
func FindSProjectByProjectIdAndSupplierId(ctx context.Context, projectId string, supplierId int) (int64, error) {
	db := GetWriteDB(ctx)
	whereCondition := gorm_model.SProjectInfo{
		ProjectId:  projectId,
		SupplierId: supplierId,
	}
	var total int64
	err := db.Debug().Model(gorm_model.SProjectInfo{}).Where(whereCondition).Count(&total).Error
	if err != nil {
		return 0, err
	}
	return total, nil
}
