package models

import (
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/utils"
	"os/exec"
)

type Etcdtab struct {
	Id        int    `xorm:"not null pk comment('编号') autoincr  INT(0)" json:"etcdtab-id"`
	Etcdname  string `xorm:"not null comment('服务名称') VARCHAR(32)" json:"etcdtab-etcdname"`
	Descr     string `xorm:"not null comment('描述') VARCHAR(30)" json:"etcdtab-descr"`
	Health    string `xorm:"not null comment('健康状态') VARCHAR(100)" json:"etcdtab-health"`
	Path      string `xorm:"not null comment('路径') VARCHAR(255)" json:"etcdtab-path"`
	State     int    `xorm:"not null comment('状态') INT" json:"etcdtab-state"`
	Lastmodif string `xorm:"not null comment('上一次更改日期') VARCHAR(14)" json:"etcdtab-lastmodif"`
	Lastuser  string `xorm:"not null comment('最后编辑人员') VARCHAR(20)" json:"etcdtab-lastuser"`
	Credatuz  string `xorm:"not null comment('创建时间') VARCHAR(14)" json:"etcdtab-credatuz"`
}

func (t *Etcdtab) TableName() string {
	return "etcdtab"
}

// 清除string字段的右侧空格
func (t *Etcdtab) Clipped() {
	utils.TrimStruct(t, *t)
}

// exeAdress指完整路径
func(t *Etcdtab) CheckExe2(exeAdress string) error{
	cmd := exec.Command("cmd.exe", "/c", "start "+exeAdress)
	err := cmd.Run()
	if err != nil {
		return err
	} else {
		return nil
	}
}

//增
func (t *Etcdtab) Add() error {
	e := db.Eloquent.Master()
	info := new(Etcdtab)
	info.Etcdname = t.Etcdname
	info.Descr = t.Descr
	info.Path = t.Path
	info.Lastuser = t.Lastuser
	info.Credatuz = t.Credatuz
	info.Lastmodif = t.Lastmodif
	_, err := e.Table("etcdtab").Insert(info)
	if err != nil {
		return err
	}
	return nil
}

//删
func (t *Etcdtab) Del() bool {
	e := db.Eloquent.Master()
	_, err := e.ID(t.Id).Delete(&Etcdtab{})
	if err != nil {
		return false
	}
	return true
}

//改
func (t *Etcdtab) Update() bool {
	e := db.Eloquent.Master()
	_, err := e.ID(t.Id).Update(t)
	if err != nil {
		return false
	}
	return true
}

//查
func (t *Etcdtab) SelectOne() (Etcdtab, error) {
	e := db.Eloquent.Master()
	var data Etcdtab
	_, err := e.ID(t.Id).Get(&data)
	if err != nil {
		return data, err
	}
	return data, nil
}

//分页
func (t *Etcdtab) GetPage(pageSize int, pageIndex int) ([]Etcdtab, int, error) {
	data := make([]Etcdtab, 0)
	e := db.Eloquent.Master()
	table := e.Table("etcdtab").Where("1=1")
	where := "where 1=1 "
	Offset := (pageIndex - 1) * pageSize
	err := e.SQL("SELECT TOP " + utils.ValueToString(pageSize, "") + " etcdtab.* FROM Etcdtab " + where + " AND (convert(varchar(10),id) NOT IN (SELECT TOP " + utils.ValueToString(Offset, "") + " convert(varchar(10),id) FROM Etcdtab " + where + " ORDER BY credatuz DESC)) ORDER BY credatuz DESC").Find(&data)
	pcount := new(Etcdtab)
	count, err := table.Count(pcount)
	if err != nil {
		return data, 0, err
	}
	for k, _ := range data {
		data[k].Clipped()
	}
	return data, int(count), nil
}