package model

import (
	"database/sql"
	"errors"
	"fmt"
	"strings"
)

type SysCfg struct {
	Model
}

type SysCfgRow struct {
	Id       int64
	CfgKey   string
	CfgValue string
}

func NewSysCfg(db *sql.DB) *SysCfg {
	return &SysCfg{
		Model{
			db: db,
		},
	}
}

func (m *SysCfg) Insert(key, value string) (int64, error) {
	if key == "" {
		return 0, errors.New("KEY不能为空")
	}
	ret, err := m.db.Exec("INSERT INTO syscfg(cfg_key,cfg_value) VALUES(?,?)", key, value)
	if err != nil {
		return 0, err
	} else {
		return ret.LastInsertId()
	}
}

func (m *SysCfg) Delete(id int64) (int64, error) {
	if id <= 0 {
		return 0, errors.New("ID必须是正整数")
	}
	ret, err := m.db.Exec("DELETE FROM syscfg WHERE id=?", id)
	if err != nil {
		return 0, err
	} else {
		return ret.RowsAffected()
	}
}

func (m *SysCfg) DeleteByKey(key string) (int64, error) {
	if key == "" {
		return 0, errors.New("KEY不能为空")
	}
	ret, err := m.db.Exec("DELETE FROM syscfg WHERE cfg_key=?", key)
	if err != nil {
		return 0, err
	} else {
		return ret.RowsAffected()
	}
}

func (m *SysCfg) Update(id int64, value string) (int64, error) {
	if id <= 0 {
		return 0, errors.New("ID必须是正整数")
	}
	ret, err := m.db.Exec("UPDATE syscfg SET cfg_value=? WHERE id=?", value, id)
	if err != nil {
		return 0, err
	} else {
		return ret.RowsAffected()
	}
}

func (m *SysCfg) UpdateByKey(key, value string) (int64, error) {
	if key == "" {
		return 0, errors.New("KEY不能为空")
	}
	ret, err := m.db.Exec("UPDATE syscfg SET cfg_value=? WHERE cfg_key=?", value, key)
	if err != nil {
		return 0, err
	} else {
		return ret.RowsAffected()
	}
}

func (m *SysCfg) Get(id int64) (*SysCfgRow, error) {
	if id <= 0 {
		return nil, errors.New("ID必须是正整数")
	}
	result := m.db.QueryRow("SELECT id,cfg_key,cfg_value FROM syscfg WHERE id=?", id)
	row := SysCfgRow{}
	err := result.Scan(&row.Id, &row.CfgKey, &row.CfgValue)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, errors.New("记录不存在")
		} else {
			return nil, err
		}
	} else {
		return &row, nil
	}
}

func (m *SysCfg) GetByKey(key string) (*SysCfgRow, error) {
	if key == "" {
		return nil, errors.New("KEY不能为空")
	}
	result := m.db.QueryRow("SELECT id,cfg_key,cfg_value FROM syscfg WHERE cfg_key=?", key)
	row := SysCfgRow{}
	err := result.Scan(&row.Id, &row.CfgKey, &row.CfgValue)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, errors.New("记录不存在")
		} else {
			return nil, err
		}
	} else {
		return &row, nil
	}
}

func (m *SysCfg) GetByKeys(keys []string) (map[string]string, error) {
	l := len(keys)
	if l == 0 {
		return nil, errors.New("KEY列表不能为空")
	}
	keysArgs := make([]interface{}, l)
	for i := 0; i < l; i++ {
		keysArgs[i] = keys[i]
	}
	placeholders := strings.Join(strings.Split(strings.Repeat("?", l), ""), ",")
	sql := fmt.Sprintf("SELECT cfg_key,cfg_value FROM syscfg WHERE cfg_key IN(%s)", placeholders)
	result, err := m.db.Query(sql, keysArgs...)
	if err != nil {
		return nil, err
	} else {
		values := make(map[string]string)
		for result.Next() {
			var k, v string
			result.Scan(&k, &v)
			values[k] = v
		}
		return values, nil
	}
}

func (m *SysCfg) GetAll() ([]*SysCfgRow, error) {
	result, err := m.db.Query("SELECT id,cfg_key,cfg_value FROM syscfg ORDER BY id")
	if err != nil {
		return nil, err
	}
	rows := make([]*SysCfgRow, 0)
	for result.Next() {
		row := SysCfgRow{}
		err = result.Scan(&row.Id, &row.CfgKey, &row.CfgValue)
		if err != nil {
			continue
		}
		rows = append(rows, &row)
	}
	return rows, nil
}

func (m *SysCfg) Set(key, value string) (int64, error) {
	if key == "" {
		return 0, errors.New("KEY不能为空")
	}
	ret, err := m.db.Exec("REPLACE INTO syscfg(cfg_key,cfg_value) VALUES(?,?)", key, value)
	if err != nil {
		return 0, err
	} else {
		return ret.RowsAffected()
	}
}
