package dao

import (
	"fmt"
	"server/global"
)

type SysApi struct {
	global.GVA_MODEL
	Path        string `json:"path" gorm:"comment:api路径"`             // api路径
	Description string `json:"description" gorm:"comment:api中文描述"`    // api中文描述
	ApiGroup    string `json:"apiGroup" gorm:"comment:api组"`          // api组
	Method      string `json:"method" gorm:"default:POST;comment:方法"` // 方法:创建POST(默认)|查看GET|更新PUT|删除DELETE
}

func (SysApi) TableName() string {
	return "sys_apis"
}

// TODO:Api查询

// QueryApiByPathMethod 查询api 按路径和方法
func QueryApiByPathMethod(path, method string) (sysApi SysApi, err error) {
	err = global.GVA_DB.Where("path = ? AND method = ?", path, method).First(&sysApi).Error
	return
}

// QueryApiById 查询api 按id
func QueryApiById(id uint) (sysApi SysApi, err error) {
	err = global.GVA_DB.First(&sysApi, "id = ?", id).Error
	return
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetAPIInfoList
//@description: 分页获取数据,
//@param: api model.SysApi, info request.PageInfo, order string, desc bool
//@return: list interface{}, total int64, err error

func (api SysApi) GetAPIInfoList(limit, offset int, order string, desc bool) (apiList []SysApi, total int64, err error) {

	db := global.GVA_DB.Model(&SysApi{})

	if api.Path != "" {
		db = db.Where("path LIKE ?", "%"+api.Path+"%")
	}

	if api.Description != "" {
		db = db.Where("description LIKE ?", "%"+api.Description+"%")
	}

	if api.Method != "" {
		db = db.Where("method = ?", api.Method)
	}

	if api.ApiGroup != "" {
		db = db.Where("api_group = ?", api.ApiGroup)
	}

	err = db.Count(&total).Error

	if err != nil {
		return apiList, total, err
	}

	db = db.Limit(limit).Offset(offset)
	OrderStr := "id desc"
	if order != "" {
		orderMap := make(map[string]bool, 5)
		orderMap["id"] = true
		orderMap["path"] = true
		orderMap["api_group"] = true
		orderMap["description"] = true
		orderMap["method"] = true
		if !orderMap[order] {
			err = fmt.Errorf("非法的排序字段: %v", order)
			return apiList, total, err
		}
		OrderStr = order
		if desc {
			OrderStr = order + " desc"
		}
	}
	err = db.Order(OrderStr).Find(&apiList).Error
	return apiList, total, err
}

// GetAllApis 查询所有api
func GetAllApis() (apis []SysApi, err error) {
	err = global.GVA_DB.Find(&apis).Error
	return
}

// TODO:Api新增

// CreateApi 新增api
func (api SysApi) CreateApi() error {
	return global.GVA_DB.Create(&api).Error
}

// TODO:Api修改

// SaveApi 更新api
func (api SysApi) SaveApi() error {
	return global.GVA_DB.Save(&api).Error
}

// TODO:Api删除

// DeleteApi 删除api
func (api SysApi) DeleteApi() error {
	return global.GVA_DB.Delete(&api).Error
}
