package financial_analyst

import (
	"errors"
	logger "eta/eta_mini_ht_api/common/component/log"
	"eta/eta_mini_ht_api/models"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"time"
)

type AnalystStatus string

const (
	AnalystStatusEnabled  AnalystStatus = "enabled"
	AnalystStatusDisabled AnalystStatus = "disabled"
	columns                             = "id,eta_id,name,head_img_url,introduction"
)

type CrmFinancialAnalyst struct {
	Id           int           `gorm:"primaryKey;autoIncrement;column:id;comment:主键"`
	ETAId        int           `gorm:"column:eta_id"`
	HTId         int           `gorm:"column:ht_id"`
	Name         string        `gorm:"column:name"`
	HeadImgURL   string        `gorm:"column:head_img_url"`
	Introduction string        `gorm:"column:introduction"`
	Status       AnalystStatus `gorm:"column:status"`
	Deleted      bool          `gorm:"column:deleted"`
	CreatedTime  time.Time     `gorm:"column:created_time;type:timestamps;comment:创建时间"`
	UpdatedTime  time.Time     `gorm:"column:updated_time;type:timestamps;comment:更新时间"`
}

func BatchInsertOrUpdate(list []CrmFinancialAnalyst) (err error) {
	db := models.Main()
	OnConflictFunc := clause.OnConflict{
		Columns:   []clause.Column{{Name: "eta_id"}},
		DoUpdates: clause.AssignmentColumns([]string{"name", "status", "deleted"}),
	}

	// 执行批量插入或更新操作
	err = db.Clauses(OnConflictFunc).Create(&list).Error
	return
}

func (fa *CrmFinancialAnalyst) BeforeCreate(db *gorm.DB) (err error) {
	fa.CreatedTime = time.Now()
	return
}

func GetAnalystById(id int) (analyst CrmFinancialAnalyst, err error) {
	db := models.Main()
	err = db.Select(columns).Where("id = ?", id).First(&analyst).Error
	return
}

func GetAnalystByName(name string) (analyst CrmFinancialAnalyst, err error) {
	db := models.Main()
	err = db.Select(columns).Where("name = ?", name).First(&analyst).Error
	return
}

func GetCount() (total int64) {
	db := models.Main()
	err := db.Model(&CrmFinancialAnalyst{}).Select("count(*) count").Scan(&total).Order("id asc").Error
	if err != nil {
		return 0
	}
	return
}

func GetAnalystList(latestId int64, offset int, limit int) (analysts []CrmFinancialAnalyst, err error) {
	if latestId < 0 {
		err = errors.New("非法的id参数")
		logger.Error("非法的id参数:%d", latestId)
		return
	}
	if limit <= 0 {
		err = errors.New("非法的limit参数")
		logger.Error("非法的limit参数:%d", limit)
	}
	db := models.Main()
	err = db.Select(columns).Where(" id<= ? ", latestId).Offset(offset).Limit(limit).Find(&analysts).Order("create_time desc").Error
	return
}
