package schema

import (
	"gorm.io/gorm"
	"strconv"

	"git.nspix.com/golang/micro/gateway/http"
)

func routes(db *gorm.DB, httpSvr *http.Server) {

	indexAction := func(ctx *http.Context) (err error) {
		var (
			tableName  string
			moduleName string
		)
		moduleName = ctx.FormValue("module_name")
		if moduleName == "" {
			moduleName = ctx.FormValue("module")
		}
		tableName = ctx.FormValue("table_name")
		if tableName == "" {
			tableName = ctx.FormValue("table")
		}
		return ctx.Success(VisibleField(moduleName, tableName, ""))
	}

	queryAction := func(ctx *http.Context) (err error) {
		var (
			tableName  string
			moduleName string
		)
		moduleName = ctx.ParamValue("module")
		tableName = ctx.ParamValue("table")
		fields := VisibleField(moduleName, tableName, "")
		values := make([]*Field, 0)
		for _, field := range fields {
			if field.Enable {
				values = append(values, &Field{
					Column:   field.Column,
					Label:    field.Label,
					Type:     field.Type,
					Format:   field.Format,
					Scenario: field.Scenario,
					Rules:    field.Rules,
					Options:  field.Options,
				})
			}
		}
		return ctx.Success(values)
	}

	type direct struct {
		Module string `json:"module_name" gorm:"column:module_name"`
		Table  string `json:"table_name" gorm:"column:table_name"`
	}

	//directAction := func(ctx *http.Context) (err error) {
	//	var vs []direct
	//	db.Table("schemas").Select("module_name,table_name").Where("table_name <> ''").Group("module_name,table_name").Find(&vs)
	//	return ctx.Success(vs)
	//}
	saveAction := func(ctx *http.Context) (err error) {
		vs := make([]*Schema, 0)
		if err = ctx.Bind(&vs); err != nil {
			return ctx.Error(1000, err.Error())
		}
		for _, v := range vs {
			if err2 := driver.SaveColumn(v); err2 != nil {
				return ctx.Error(8004, err2.Error())
			}
		}
		return ctx.Success(map[string]interface{}{
			"state": "success",
		})
	}
	
	deleteAction := func(ctx *http.Context) (err error) {
		idStr := ctx.ParamValue("id")
		id, _ := strconv.Atoi(idStr)
		if err = driver.DeleteColumn(id); err == nil {
			return ctx.Success(map[string]interface{}{
				"id":    ctx.ParamValue("id"),
				"state": "success",
			})
		} else {
			return ctx.Error(8006, err.Error())
		}
	}

	//获取数据
	httpSvr.Handle("GET", "/schemas", indexAction)
	httpSvr.Handle("GET", "/schema/:module/:table", queryAction)

	//更新数据
	httpSvr.Handle("POST", "/schema", saveAction)
	httpSvr.Handle("POST", "/schema/save", saveAction)

	//删除数据
	httpSvr.Handle("DELETE", "/schema/:id", deleteAction)
}
