package api

import (
	"encoding/hex"
	"fmt"
	"reflect"
	"work-device/db/repo"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type CreateModel func(c *gin.Context) interface{}
type CreateModel2 func(c *gin.Context, apictx *ApiSession) (interface{}, error)
type SearchFilterFn func(c *gin.Context, apictx *ApiSession, query map[string]interface{}) map[string]interface{}
type Update func(c *gin.Context, apictx *ApiSession, entity interface{}, id string)
type SearchPostFn func(page *repo.PageResult, c *gin.Context, apictx *ApiSession, query map[string]interface{}) (interface{}, error)
type RemoveFn func(c *gin.Context, apictx *ApiSession, id string) (interface{}, error)

type CRUDOption struct {
	Collection        string
	NewModel          CreateModel
	NewModel2         CreateModel2
	EmtyModel         CreateModel
	SearchFilter      SearchFilterFn
	SearchPostProcess SearchPostFn
	SearchSort        interface{}
	Remove            RemoveFn
	JWT               bool
	SearchProject     []string
	DetailProject     []string
	DetailProjectAll  bool
	Update            Update
	noUpdate          bool
}

func CreateCRUD(router *GinRouter, prefix string, option *CRUDOption) {

	//创建
	creatpath := fmt.Sprintf("%s/create", prefix)
	router.POSTJWT(creatpath, func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
		var entity interface{} = nil

		if option.NewModel != nil {
			entity = option.NewModel(c)
		} else {
			ent, err := option.NewModel2(c, apictx)
			if err != nil {
				return nil, err
			}
			entity = ent
		}

		if entity == nil {
			return nil, NewError("数据已存在！")
		}
		return repo.RepoAddDoc(apictx.CreateRepoCtx(), option.Collection, entity)
	})

	//更新
	if !option.noUpdate {
		updatePath := fmt.Sprintf("%s/update", prefix)
		router.POSTJWT(updatePath, func(c *gin.Context, apictx *ApiSession) (interface{}, error) {

			m := option.EmtyModel(c)
			err := c.ShouldBindJSON(m)

			if err != nil {
				fmt.Println(err)
				return nil, NewError("参数解析错误")
			}

			v := reflect.ValueOf(m)
			v = v.Elem()

			mid := v.FieldByName("Id")

			if !mid.IsValid() {
				return nil, NewError("ID不能为空")
			}

			slice := mid.Slice(0, mid.Len())
			objId := hex.EncodeToString(slice.Bytes())
			for i := 0; i < 12; i++ {
				mid.Index(i).SetUint(0)
			}

			if option.Update != nil {
				option.Update(c, apictx, m, objId)
			}

			out, err := repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), option.Collection, objId, m)
			if err != nil {
				return nil, err
			}
			if out.MatchedCount != 1 {
				return nil, NewError("文件不存在!")
			}

			return out, nil
		})
	}

	//分页查询
	SearchPath := fmt.Sprintf("%s/list", prefix)

	pageSearchFn := func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
		page, size, query := UtilQueryPageSize(c)

		if option.SearchFilter != nil {
			filter := option.SearchFilter(c, apictx, query)
			for k, v := range filter {
				query[k] = v
			}
		}

		pageOption := &repo.PageSearchOptions{
			CollectName: option.Collection,
			Page:        page,
			Size:        size,
			Query:       query,
			Project:     option.SearchProject,
		}
		if option.SearchSort != nil {
			pageOption.Sort = option.SearchSort
		}

		pageResult, err := repo.RepoPageSearch(apictx.CreateRepoCtx(), pageOption)
		if err != nil {
			return nil, err
		}

		if option.SearchPostProcess != nil {
			return option.SearchPostProcess(pageResult, c, apictx, query)
		}

		return pageResult, nil
	}

	if option.JWT {
		router.GETJWT(SearchPath, pageSearchFn)
	} else {
		router.GET(SearchPath, pageSearchFn)
	}
	//删除
	removePath := fmt.Sprintf("%s/delete/:id", prefix)
	router.POSTJWT(removePath, func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
		id := c.Param("id")
		if len(id) < 1 {
			return nil, NewError("参数不能为空")
		}

		if option.Remove != nil {
			return option.Remove(c, apictx, id)
		}

		return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), option.Collection, id)

	})

	//详情
	if len(option.DetailProject) > 0 {
		detailPath := fmt.Sprintf("%s/detail/:id", prefix)
		router.GET(detailPath, func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
			id := c.Param("id")
			if len(id) < 1 {
				return nil, NewError("参数不能为空")
			}
			out := option.EmtyModel(c)

			uid, _ := primitive.ObjectIDFromHex(id)

			proj := option.DetailProject

			if option.DetailProjectAll {
				proj = nil
			}

			ok, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
				CollectName: option.Collection,
				Query:       repo.Map{"_id": uid},
				Project:     proj,
			}, out)

			if err != nil {
				return nil, err
			}
			if !ok {
				return nil, NewError("没有查询到数据")
			}
			return out, nil
		})
	}
}
