package models

import (
	"LAPP_LF_MOM_BACKEND/conf"
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/utils"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"context"
)

//数据库
type Database struct {
	ID         int `bson:"id" json:"database-id"`                 //ID:uuid唯一字符串
	DbName     string `bson:"dbname" json:"database-dbname"`         //数据库名称
	DriverName string `bson:"drivername" json:"database-drivername"` //引擎类型
	Host       string `bson:"host" json:"database-host"`             //链接地址
	Port       int    `bson:"port" json:"database-port"`             //端口号
	User       string `bson:"user" json:"database-user"`             //用户名
	Pwd        string `bson:"pwd" json:"database-pwd"`               //密码
	Sourcetype string `bson:"sourcetype" json:"database-sourcetype"` //主库和从库
}

func (t *Database) TableName() string {
	return "database"
}

func (t *Database) InsertRecord() (insertID primitive.ObjectID) {
	//1.初始化链接
	client := db.MgoDb()
	//2.选择数据库，数据表
	collect := client.Database(conf.DbConfig.Mongdbname).Collection("database")
	insertRest, err := collect.InsertOne(context.TODO(), t)
	if err != nil {
		fmt.Println(err)
		return
	}
	insertID = insertRest.InsertedID.(primitive.ObjectID)
	return insertID
}

func (t *Database) UpdateData() error {
	//1.初始化链接
	client := db.MgoDb()
	//2.选择数据库，数据表
	collect := client.Database(conf.DbConfig.Mongdbname).Collection("database")

	// 修改一条数据，如果不存在则插入
	new := &Database{
		ID:         t.ID,
		DbName:     t.DbName,
		DriverName: t.DriverName,
		Host:       t.Host,
		Port:       t.Port,
		User:       t.User,
		Pwd:        t.Pwd,
		Sourcetype: t.Sourcetype,
	}
	update := bson.M{"$set": new}
	_, err := collect.UpdateOne(context.Background(), bson.M{"dbname": new.DbName,"drivername":new.DriverName}, update)
	if err != nil {
		return err
	}
	return nil
}

func (t *Database) FindList(logred SerchData, skip int64, limit int64) ([]*Database, int64) {
	res := bson.M{}
	// 创建需要过滤的条件
	if logred.Key == "dbname" {
		res = bson.M{"dbname": primitive.Regex{Pattern: logred.Val}}
	}
	if logred.Key == "drivername" {
		res = bson.M{"drivername": primitive.Regex{Pattern: logred.Val}}
	}
	if logred.Key == "host" {
		res = bson.M{"host": primitive.Regex{Pattern: logred.Val}}
	}
	res = bson.M{"sourcetype": primitive.Regex{Pattern: "Slave"}}
	//1.初始化链接
	client := db.MgoDb()
	//2.选择数据库，数据表
	collect := client.Database(conf.DbConfig.Mongdbname).Collection("database")

	//var skip int64 = 0//从那个开始
	//var limit int64 = 2//炼制几个输出字段
	cursor, err := collect.Find(context.TODO(), res, &options.FindOptions{
		Skip:  &skip,
		Limit: &limit,
		Sort:  bson.D{{"id", -1}},
	})

	if err != nil {
		fmt.Println(err)
		return nil, 0
	}
	defer cursor.Close(context.TODO())
	//创建需要反序列化成什么样子的结构体对象
	records := make([]*Database, 0)
	for cursor.Next(context.TODO()) {
		record := &Database{}
		//反序列化
		err = cursor.Decode(record)
		if err != nil {
			fmt.Println(err)
			return nil, 0
		}
		//追加
		records = append(records, record)
	}
	// 获取数据总数
	count, err := collect.CountDocuments(context.Background(), bson.D{})
	if err != nil {
		log.Fatal(count)
	}
	return records, count
}

func (t *Database) FindData() []*Database {
	res := bson.M{}
	// 创建需要过滤的条件
	if !utils.ValueIsEmpty(t.Sourcetype) {
		res = bson.M{"sourcetype": primitive.Regex{Pattern: t.Sourcetype}}
	}
	limit := int64(500)
	skip := int64(0)
	//1.初始化链接
	client := db.MgoDb()
	//2.选择数据库，数据表
	collect := client.Database(conf.DbConfig.Mongdbname).Collection("database")

	//var skip int64 = 0//从那个开始
	//var limit int64 = 2//炼制几个输出字段
	cursor, err := collect.Find(context.TODO(), res, &options.FindOptions{
		Skip:  &skip,
		Limit: &limit,
		Sort:  bson.D{{"id", -1}},
	})
	fmt.Println(cursor)
	if err != nil {
		return nil
	}
	defer cursor.Close(context.TODO())
	//创建需要反序列化成什么样子的结构体对象
	records := make([]*Database, 0)
	for cursor.Next(context.TODO()) {
		record := &Database{}
		//反序列化
		err = cursor.Decode(record)
		if err != nil {
			fmt.Println(err)
			return nil
		}
		//追加
		records = append(records, record)
	}
	return records
}

func (t *Database) FindOne() (Database,error) {
	//1.初始化链接
	client := db.MgoDb()
	//2.选择数据库，数据表
	collect := client.Database(conf.DbConfig.Mongdbname).Collection("database")
	record := Database{}
	err := collect.FindOne(context.Background(), bson.M{"dbname": t.DbName,"drivername":t.DriverName}).Decode(&record)

	if err != nil {
		return record,err
	}

	return record,nil
}

func (t *Database) DelData() error {
	//1.初始化链接
	client := db.MgoDb()
	//2.选择数据库，数据表
	collect := client.Database(conf.DbConfig.Mongdbname).Collection("database")

	// 修改一条数据，如果不存在则插入
	new := &Database{
		DbName:     t.DbName,
		DriverName: t.DriverName,
	}
	// 删除一条数据
	_, err := collect.DeleteOne(context.Background(), bson.M{"dbname": new.DbName,"drivername":new.DriverName})
	if err != nil {
		return err
	}
	return nil
}