package services

import (
	"fmt"
	ywtcenter "hello/models/ywtcenter"

	"github.com/astaxie/beego/orm"
)

// list 查询
func QueryList() {

	var j, i int64

	orm.Debug = true
	o := orm.NewOrm()
	o.Using("default") // 默认使用 default，你可以指定为其他数据库

	var users []ywtcenter.MgAdmin
	num, err := o.Raw("SELECT account, id, nick_name, user_id FROM mg_admin WHERE state = ?", 1).QueryRows(&users)
	// fmt.Println(users)

	if err == nil {
		fmt.Println("user nums: ", num)
	}

	i = num
	for j = 0; j < i; j++ {
		// fmt.Printf("Element[%d] = %d, %s, %d\n", j, users[j].Id, users[j].NickName, users[j].UserId)
	}
}

// 根据ID查找一个记录
func FindOneById(id int) ywtcenter.MgAdmin {
	orm.Debug = true
	o := orm.NewOrm()
	o.Using("default") // 默认使用 default，你可以指定为其他数据库
	mgAdmin := ywtcenter.MgAdmin{Id: int16(id)}
	err := o.Read(&mgAdmin)
	if err == orm.ErrNoRows {
		fmt.Println("查询不到")
	} else if err == orm.ErrMissPK {
		fmt.Println("找不到主键")
	} else {
		// fmt.Println(mgAdmin.Id, mgAdmin.NickName)
	}
	return mgAdmin
}

// 方式1: 根据ID修改userId
func UpdateUserId1(id, userId int) ywtcenter.MgAdmin {
	o := orm.NewOrm()
	o.Using("default")
	mgAdmin := ywtcenter.MgAdmin{Id: int16(id)}
	if o.Read(&mgAdmin) == nil {
		mgAdmin.UserId = int16(userId)
		if num, err := o.Update(&mgAdmin); err == nil {
			fmt.Println(num)
		}
	}
	return mgAdmin
}

/**
 * 方式2: 根据ID修改userId
 */
func UpdateUserId2(id, userId int) {
	o := orm.NewOrm()
	o.Using("default")
	num, err := o.QueryTable("mg_admin").Filter("id", "1").Update(orm.Params{
		"user_id": int16(userId),
	})
	fmt.Printf("Affected Num: %s, %s", num, err)
}

// 删除对象
func DeleteMgAdminById(id int) {
	o := orm.NewOrm()
	o.Using("default")
	if num, err := o.Delete(&ywtcenter.MgAdmin{Id: int16(id)}); err == nil {
		fmt.Println(num)
	}
}
