package models

import (
	"fmt"
	"time"
)

type Cdn struct {
	Name         string    `json:"name"`
	Cname        string    `json:"cname"`
	VendorId     int       `json:"vendor_id"`
	Status       string    `json:"status"`
	SourceType   string    `json:"source_type"`
	SourceTarget string    `json:"source_target"`
	IsHttps      bool      `json:"id_https"`
	CertId       int       `json:"cert_id"`
	Owner        string    `json:"owner"`
	Remark       string    `json:"remark"`
	CreateTime   time.Time `json:"create_time"`
	UpdateTime   time.Time `json:"update_time"`
}

func AddCdnDomain(domain interface{}) (err error) {
	err = db.Create(domain).Error
	return
}

func GetCdn(key string, vendorId int, pageNum int, pageSize int) (cdn []Cdn) {
	selectSql := fmt.Sprintf(`SELECT * FROM cdn WHERE id > 0 `)
	if vendorId != 0 {
		selectSql += fmt.Sprintf(` AND vendor_id = %d`, vendorId)
	}
	if key != "" {
		selectSql += fmt.Sprintf(` AND (name LIKE '%%%s%%' OR cname LIKE '%%%s%%' )`, key, key)
	}
	db.Raw(selectSql).Offset(pageNum).Limit(pageSize).Scan(&cdn)
	return
}

func GetCdnTotal(key string, vendorId int) (count int) {
	selectSql := fmt.Sprintf(`SELECT COUNT(*) FROM cdn WHERE id > 0 `)
	if vendorId != 0 {
		selectSql += fmt.Sprintf(` AND vendor_id = %d`, vendorId)
	}
	if key != "" {
		selectSql += fmt.Sprintf(` AND (name LIKE '%%%s%%' OR cname LIKE '%%%s%%' )`, key, key)
	}
	db.Raw(selectSql).Count(&count)
	return
}
