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

package gen_table

import (
	"gfast/app/model/admin/gen_table_column"
	"gfast/library/service"
	"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/text/gstr"
	"github.com/gogf/gf/util/gconv"
)

//分页请求参数
type SelectPageReq struct {
	TableName    string `p:"tableName"`    //表名称
	TableComment string `p:"tableComment"` //表描述
	BeginTime    string `p:"beginTime"`    //开始时间
	EndTime      string `p:"endTime"`      //结束时间
	PageNum      int    `p:"pageNum"`      //当前页码
	PageSize     int    `p:"pageSize"`     //每页数
}

//实体扩展
type EntityExtend struct {
	TableId        int64                      `orm:"table_id,primary" json:"table_id"`        // 编号
	TableName      string                     `orm:"table_name"       json:"table_name"`      // 表名称
	TableComment   string                     `orm:"table_comment"    json:"table_comment"`   // 表描述
	ClassName      string                     `orm:"class_name"       json:"class_name"`      // 实体类名称
	TplCategory    string                     `orm:"tpl_category"     json:"tpl_category"`    // 使用的模板（crud单表操作 tree树表操作）
	PackageName    string                     `orm:"package_name"     json:"package_name"`    // 生成包路径
	ModuleName     string                     `orm:"module_name"      json:"module_name"`     // 生成模块名
	BusinessName   string                     `orm:"business_name"    json:"business_name"`   // 生成业务名
	FunctionName   string                     `orm:"function_name"    json:"function_name"`   // 生成功能名
	FunctionAuthor string                     `orm:"function_author"  json:"function_author"` // 生成功能作者
	Options        string                     `orm:"options"          json:"options"`         // 其它生成选项
	CreateBy       string                     `orm:"create_by"        json:"create_by"`       // 创建者
	CreateTime     *gtime.Time                `orm:"create_time"      json:"create_time"`     // 创建时间
	UpdateBy       string                     `orm:"update_by"        json:"update_by"`       // 更新者
	UpdateTime     *gtime.Time                `orm:"update_time"      json:"update_time"`     // 更新时间
	Remark         string                     `orm:"remark"           json:"remark"`          // 备注
	TreeCode       string                     `json:"tree_code"`                              // 树编码字段
	TreeParentCode string                     `json:"tree_parent_code"`                       // 树父编码字段
	TreeName       string                     `json:"tree_name"`                              // 树名称字段
	Columns        []*gen_table_column.Entity `json:"columns"`                                // 表列信息
	PkColumn       *gen_table_column.Entity   `json:"pkColumn"`                               // 表列信息
}

//查询据库列表
func SelectDbTableList(param *SelectPageReq) (total int, list []*Entity, err error) {
	db := g.DB()
	sql := " from information_schema.tables where table_schema = (select database())" +
		" and table_name NOT LIKE 'qrtz_%' AND table_name NOT LIKE 'gen_%' and table_name NOT IN (select table_name from gen_table) "
	if param != nil {
		if param.TableName != "" {
			sql += gdb.FormatSqlWithArgs(" and lower(table_name) like lower(?)", []interface{}{"%" + param.TableName + "%"})
		}

		if param.TableComment != "" {
			sql += gdb.FormatSqlWithArgs(" and lower(table_comment) like lower(?)", []interface{}{"%" + param.TableComment + "%"})
		}

		if param.BeginTime != "" {
			sql += gdb.FormatSqlWithArgs(" and date_format(create_time,'%y%m%d') >= date_format(?,'%y%m%d') ", []interface{}{param.BeginTime})
		}

		if param.EndTime != "" {
			sql += gdb.FormatSqlWithArgs(" and date_format(create_time,'%y%m%d') <= date_format(?,'%y%m%d') ", []interface{}{param.EndTime})
		}
	}
	countSql := "select count(1) " + sql
	total, err = db.GetCount(countSql)
	if err != nil {
		g.Log().Error(err)
		err = gerror.New("读取总表数失败")
		return
	}
	sql = "table_name, table_comment, create_time, update_time " + sql

	if param.PageNum == 0 {
		param.PageNum = 1
	}

	if param.PageSize == 0 {
		param.PageSize = service.AdminPageNum
	}
	page := (param.PageNum - 1) * param.PageSize
	sql += " order by create_time desc,table_name asc limit  " + gconv.String(page) + "," + gconv.String(param.PageSize)
	var res gdb.Result
	res, err = db.GetAll("select " + sql)
	res.Structs(&list)
	if err != nil {
		g.Log().Error(err)
		err = gerror.New("读取数据失败")
	}
	return
}

//根据条件分页查询数据
func SelectListByPage(param *SelectPageReq) (total int, list []*Entity, err error) {
	model := Model
	if param != nil {
		if param.TableName != "" {
			model = model.Where(Columns.TableName+" like ?", "%"+param.TableName+"%")
		}
		if param.TableComment != "" {
			model = model.Where(Columns.TableComment+"like ?", "%"+param.TableComment+"%")
		}
		if param.BeginTime != "" {
			model = model.Where(Columns.CreateTime+" >= ", param.BeginTime)
		}
		if param.EndTime != "" {
			model = model.Where(Columns.CreateTime+" <= ", param.EndTime)
		}
		total, err = model.Count()
		if err != nil {
			g.Log().Error(err)
			err = gerror.New("获取总行数失败")
			return
		}
		if param.PageNum == 0 {
			param.PageNum = 1
		}
		if param.PageSize == 0 {
			param.PageSize = service.AdminPageNum
		}
		list, err = model.Page(param.PageNum, param.PageSize).Order(Columns.TableId + " asc").All()
		if err != nil {
			g.Log().Error(err)
			err = gerror.New("获取数据失败")
			return
		}
	}
	return
}

//查询据库列表
func SelectDbTableListByNames(tableNames []string) ([]*Entity, error) {
	db := g.DB()
	sql := "select * from information_schema.tables where table_name NOT LIKE 'qrtz_%' and table_name NOT LIKE 'gen_%' " +
		" and table_schema = (select database()) "
	if len(tableNames) > 0 {
		in := gstr.TrimRight(gstr.Repeat("?,", len(tableNames)), ",")
		sql += " and " + gdb.FormatSqlWithArgs("table_name in ("+in+")", gconv.SliceAny(tableNames))
	}
	var result []*Entity
	res, err := db.GetAll(sql)
	if err != nil {
		g.Log().Error(err)
		return nil, gerror.New("获取表格信息失败")
	}
	err = res.Structs(&result)
	if err != nil {
		g.Log().Error(err)
		return nil, gerror.New("表格信息转换失败")
	}
	return result, err
}

//通过表格ID获取表格信息
func GetInfoById(tableId int64) (entity *Entity, err error) {
	entity, err = Model.FindOne(tableId)
	if err != nil {
		g.Log().Error(err)
		err = gerror.New("获取表格信息出错")
	}
	return
}

func SelectRecordById(tableId int64) (entityExtend *EntityExtend, err error) {
	var entity *Entity
	entity, err = GetInfoById(tableId)
	if err != nil {
		return
	}
	m := gconv.Map(entity)
	gconv.Struct(m, &entityExtend)

	//表字段数据
	var columns []*gen_table_column.Entity
	columns, err = gen_table_column.SelectGenTableColumnListByTableId(tableId)
	if err != nil {
		return
	}
	entityExtend.Columns = columns
	return
}
