// ============================================================================
// This is auto-generated by gf cli tool only once. Fill this file as you wish.
// ============================================================================

package model_info

import (
	"fmt"
	"gfast/app/model/admin/model_category"

	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
)

// AddReq 用于存储新增请求的请求参数
type AddReq struct {
	ModelCategoryId uint   `p:"modelCategoryId" v:"required|min:1#模型分类id不能为空|模型分类id不能为空"`
	ModelName       string `p:"modelName" v:"required#模型标识不能为空"`
	ModelTitle      string `p:"modelTitle"  v:"required#模型名称不能为空"`
	ModelStatus     uint   `p:"modelStatus" v:"required#状态不能为空"`
	ModelEngine     string `p:"modelEngine" `
	CreateBy        uint64 //添加人
}

// EditReq 用于存储修改请求参数
type EditReq struct {
	ModelId         int    `p:"modelId" v:"required#主键ID不能为空"`
	ModelCategoryId int    `p:"modelCategoryId" `
	ModelName       string `p:"modelName" v:"required#模型标识不能为空"`
	ModelTitle      string `p:"modelTitle" `
	ModelStatus     int    `p:"modelStatus" v:"required#状态不能为空"`
	ModelEngine     string `p:"modelEngine" `
	UpdateBy        uint64
}

//模型字段属性修改请求参数
type FieldsAttrReq struct {
	ModelId      int    `p:"modelId" v:"required#主键ID不能为空"`
	ModelPk      string `p:"modelPk" `
	ModelOrder   string `p:"modelOrder" `
	ModelSort    string `p:"modelSort" `
	ModelList    string `p:"modelList" `
	ModelEdit    string `p:"modelEdit" `
	ModelIndexes string `p:"modelIndexes" `
	SearchList   string `p:"searchList" `
}

type ListEntity struct {
	Entity
	CName string `orm:"c_name"      json:"c_name" `
}

type StatusSetReq struct {
	ModelId     uint `p:"modelId" v:"required#模型ID不能为空"`
	ModelStatus int  `p:"modelStatus" v:"required#状态不能为空"`
}

// SelectPageReq 用于存储分页查询的请求参数
type SelectPageReq struct {
	ModelName       string `p:"modelName"`      //模型标识
	ModelTitle      string `p:"modelTitle"`     //模型名称
	ModelStatus     string `p"modelStatus"`     //模型状态
	ModelCategoryId string `p"modelCategoryId"` //模型分类
	BeginTime       string `p:"beginTime"`      //开始时间
	EndTime         string `p:"endTime"`        //结束时间
	PageNum         int    `p:"pageNum"`        //当前页码
	PageSize        int    `p:"pageSize"`       //每页数
}

type RemoveReq struct {
	Ids []int `p:"ids"` //删除id
}

// GetByID 根据ID查询记录
func GetByID(id int64) (*Entity, error) {
	entity, err := Model.FindOne(id)
	if err != nil {
		g.Log().Error(err)
		return nil, gerror.New("根据ID查询记录出错")
	}
	if entity == nil {
		return nil, gerror.New("根据ID未能查询到记录")
	}
	return entity, nil
}

// AddSave 添加
func AddSave(req *AddReq) error {
	if err := ModelExists(req.ModelName, 0); err != nil {
		return err
	}
	entity := new(Entity)
	entity.ModelCategoryId = req.ModelCategoryId
	entity.ModelName = req.ModelName
	entity.ModelTitle = req.ModelTitle
	entity.ModelStatus = req.ModelStatus
	entity.ModelEngine = req.ModelEngine
	entity.CreateBy = gconv.Uint64(req.CreateBy)
	time := gconv.Uint64(gtime.Timestamp())
	entity.CreateTime = time
	entity.UpdateTime = time

	result, err := entity.Insert()
	if err != nil {
		return err
	}
	_, err = result.LastInsertId()
	if err != nil {
		return err
	}
	return nil
}

//判断模型是否存在
func ModelExists(name string, id int) error {
	var res *Entity
	if id != 0 {
		res, _ = Model.Where(Columns.ModelName, name).And(Columns.ModelId+" != ", id).One()
	} else {
		res, _ = Model.Where(Columns.ModelName, name).One()
	}
	if res != nil {
		return gerror.New("模型标识已经存在")
	}
	return nil
}

// 删除模型
func DeleteByIds(Ids []int, tx *gdb.TX) error {
	_, err := Model.TX(tx).Delete("model_id in(?)", Ids)
	if err != nil {
		g.Log().Error(err)
		return gerror.New("删除失败")
	}
	return nil
}

// 根据ID来修改信息
func EditSave(req *EditReq) error {
	if err := ModelExists(req.ModelName, req.ModelId); err != nil {
		return err
	}
	// 先根据ID来查询要修改的记录
	entity, err := GetByID(gconv.Int64(req.ModelId))
	if err != nil {
		return err
	}
	// 修改实体
	entity.ModelCategoryId = gconv.Uint(req.ModelCategoryId)
	entity.ModelName = req.ModelName
	entity.ModelTitle = req.ModelTitle
	entity.ModelStatus = gconv.Uint(req.ModelStatus)
	entity.ModelEngine = req.ModelEngine
	entity.UpdateBy = gconv.Uint64(req.UpdateBy)
	entity.UpdateTime = gconv.Uint64(gtime.Timestamp())
	_, err = Model.Save(entity)
	if err != nil {
		g.Log().Error(err)
		return gerror.New("修改失败")
	}
	return nil
}

// 分页查询,返回值total总记录数,page当前页
func SelectListByPage(req *SelectPageReq) (total int, page int, list []*ListEntity, err error) {
	model := g.DB().Table(Table + " info")
	if req != nil {
		if req.ModelName != "" {
			model.Where("info.model_name like ?", "%"+req.ModelName+"%")
		}
		if req.ModelTitle != "" {
			model.Where("info.model_title like ?", "%"+req.ModelTitle+"%")
		}
		if req.ModelStatus != "" {
			model.Where("info.model_status", gconv.Uint(req.ModelStatus))
		}
		if req.ModelCategoryId != "" {
			model.Where("info.model_category_id", gconv.Uint(req.ModelCategoryId))
		}
	}
	model = model.LeftJoin(model_category.Table+" cate", "cate.c_id=info.model_category_id")
	// 查询总记录数(总行数)
	total, err = model.Count()
	if err != nil {
		g.Log().Error(err)
		err = gerror.New("获取总记录数失败")
		return
	}
	if req.PageNum == 0 {
		req.PageNum = 1
	}
	page = req.PageNum
	if req.PageSize == 0 {
		req.PageSize = 10
	}
	// 分页排序查询
	var res gdb.Result
	res, err = model.Fields("info.*,cate.c_name").Page(page, req.PageSize).Order("info.model_id asc").All()
	if err != nil {
		g.Log().Error(err)
		err = gerror.New("查询失败")
		return
	}
	err = res.Structs(&list)
	if err != nil {
		g.Log().Error(err)
		err = gerror.New("查询失败")
		return
	}
	return
}

// 获取所有数据
func SelectListAll(req *SelectPageReq) (list []*Entity, err error) {
	model := Model
	if req != nil {
		if req.ModelName != "" {
			model.Where("model_name like ?", "%"+req.ModelName+"%")
		}
		if req.ModelTitle != "" {
			model.Where("model_title = ?", req.ModelTitle)
		}
	}
	// 查询
	list, err = model.Order("model_id asc").All()
	if err != nil {
		g.Log().Error(err)
		err = gerror.New("查询失败")
		return
	}
	return
}

//设置模型状态
func SetStatus(req *StatusSetReq) error {
	if req != nil {
		entity, err := Model.Where(Columns.ModelId, req.ModelId).One()
		if err != nil {
			g.Log().Error(err)
			return gerror.New("获取模型信息失败")
		}
		entity.ModelStatus = gconv.Uint(req.ModelStatus)
		_, err = Model.Save(entity)
		if err != nil {
			g.Log().Error(err)
			return gerror.New("设置状态失败")
		}
	}
	return nil
}

//通过模型分类ID获取模型
func GetModelsByCateIds(cateIds []int) (models []*Entity, err error) {
	models, err = Model.Fields(fmt.Sprintf("%s,%s,%s", Columns.ModelId, Columns.ModelName, Columns.ModelTitle)).
		Where(Columns.ModelCategoryId+" in(?)", cateIds).
		Order(Columns.ModelId + " ASC ").FindAll()
	if err != nil {
		g.Log().Error(err)
		err = gerror.New("获取模型信息失败")
	}
	return
}
