package mydatabase

import (
	"fmt"
	"log"
	"time"
)

type Emp struct {
	ID         int
	Eno        int // 员工的ID
	Name       string
	Phone      string
	Avatar     string
	Features   string
	Level      int
	Status     int
	UpdateTime string
	CreateTime string
}

func (d *Database) Create() error {
	createTableStmt := `
		CREATE TABLE IF NOT EXISTS staff (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			eno INTEGER,
			name TEXT NOT NULL,
			phone TEXT,
			avatar TEXT,
			level INTEGER,
			status INTEGER DEFAULT 0,
            features TEXT,
			create_time DATETIME,
			update_time DATETIME DEFAULT CURRENT_TIMESTAMP
		);
	`
	_, err := d.db.Exec(createTableStmt)
	if err != nil {
		log.Fatal(err)
	}
	return err
}

func Insert(name string, eno int, phone string, avatar string, features string, level int) error {
	insertStmt := "INSERT INTO staff (name,eno, phone, avatar,features, level, create_time) VALUES (?, ?, ?, ?,?, ?, ?)"
	eventTime := time.Now()
	// 将时间格式化为 SQLite 支持的 DATETIME 格式（"2006-01-02 15:04:05"）
	formattedTime := eventTime.Format("2006-01-02 15:04:05")
	_, err := GetDb().db.Exec(insertStmt, name, eno, phone, avatar, features, level, formattedTime)
	if err != nil {
		log.Fatal(err)
	}
	return err
}

func Update(id int, name string, phone string, avatar string, level int, status int) error {
	updateStmt := "UPDATE staff SET phone = ?, name = ?, avatar = ?, level=?, status=? WHERE id = ?"
	_, err := GetDb().db.Exec(updateStmt, phone, name, avatar, level, status, id)
	if err != nil {
		log.Fatal(err)
	}
	return err
}

func Delete(id int) {
	deleteStmt := "DELETE FROM staff WHERE id = ?"
	_, err := GetDb().db.Exec(deleteStmt, id)
	if err != nil {
		log.Fatal(err)
	}
}

func SoftDelete(id int) error {
	updateStmt := "UPDATE staff SET status=2 WHERE id = ?"
	_, err := GetDb().db.Exec(updateStmt, id)
	if err != nil {
		log.Fatal(err)
	}
	return err
}

func Select(key string) ([]Emp, error) {
	str := "SELECT id, eno, name, phone, avatar,features, level, status, create_time, update_time FROM staff"
	if key != "" {
		str += " WHERE name LIKE '%" + key + "%' or phone LIKE '%" + key + "%'"
	}
	rows, err := GetDb().db.Query(str + " order by status, update_time desc")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	var users []Emp
	for rows.Next() {
		var user Emp
		err := rows.Scan(&user.ID, &user.Eno, &user.Name, &user.Phone, &user.Avatar, &user.Features, &user.Level, &user.Status, &user.CreateTime, &user.UpdateTime)
		if err != nil {
			return nil, err
		}
		users = append(users, user)
	}
	return users, nil
}

func SelectOne(id int) (Emp, error) {
	rows, err := GetDb().db.Query("SELECT id, eno, name, phone, avatar,features, level, status, create_time, update_time FROM staff where id = ? LIMIT 1", id)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	var user Emp
	if rows.Next() {
		err := rows.Scan(&user.ID, &user.Eno, &user.Name, &user.Phone, &user.Avatar, &user.Features, &user.Level, &user.Status, &user.CreateTime, &user.UpdateTime)
		if err != nil {
			return user, err
		}
	}

	if err := rows.Err(); err != nil {
		return user, err
	}
	return user, nil
}

func SelectOneByPhone(phone string) (Emp, error) {
	fmt.Printf("SelectOneByPhone phone:%s\n", phone)
	rows, err := GetDb().db.Query("SELECT id, eno, name, phone, avatar,features, level, status, create_time, update_time FROM staff where phone = ? and status<>2 LIMIT 1", phone)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	var user Emp

	if rows.Next() {
		err := rows.Scan(&user.ID, &user.Eno, &user.Name, &user.Phone, &user.Avatar, &user.Features, &user.Level, &user.Status, &user.CreateTime, &user.UpdateTime)
		if err != nil {
			return user, err
		}
	}

	if err := rows.Err(); err != nil {
		return user, err
	}
	return user, nil
}
