package models

import (
	"database/sql"
	"errors"
	"log"
	"strconv"

	_ "github.com/go-sql-driver/mysql"
)

type MysqlConnection struct {
	db *sql.DB
}

// 初始化数据库连接
func (m *MysqlConnection) Init() (err error) {
	viper := Viper // 从 models/config.go 中获取 viper 对象
	user := viper.Get("mysql.user").(string)
	password := viper.Get("mysql.password").(string)
	host := viper.Get("mysql.host").(string)
	port := viper.Get("mysql.port").(int)
	database := viper.Get("mysql.database").(string)
	sqlconf := user + ":" + password + "@tcp(" + host + ":" + strconv.Itoa(port) + ")/" + database + "?charset=utf8mb4&parseTime=True&loc=Local"
	m.db, err = sql.Open("mysql", sqlconf) // 连接数据库
	if err != nil {
		log.Println("连接数据库失败", err)
		return
	}
	return
}

// 根据图片 id 获取图片的 content
func (m *MysqlConnection) GetImageContent(group string, id string) (content string, err error) {
	switch group {
	case "article":
		err = m.db.QueryRow("SELECT image FROM web_article WHERE id=" + id).Scan(&content)
	case "article_attribute":
		err = m.db.QueryRow("SELECT image FROM web_article_attribute WHERE id=" + id).Scan(&content)
	case "ad":
		err = m.db.QueryRow("SELECT image FROM web_ad WHERE id=" + id).Scan(&content)
	case "user":
		err = m.db.QueryRow("SELECT avatar FROM web_member WHERE id=" + id).Scan(&content)
	case "image":
		err = m.db.QueryRow("SELECT content FROM web_images WHERE id=" + id).Scan(&content)
	default:
		err = errors.New("group 参数错误")
	}
	return content, err
}
