package service

import (
	"fmt"
	"gadmin/config"
	"gadmin/internal/admin/forms"
	"gadmin/internal/gorm/model"
	"gadmin/internal/gorm/query"
	"gadmin/package/gmdata"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// ServerOption 渠道
var ServerOption = new(sServerOption)

type sServerOption struct{}

func (s *sServerOption) GetServerIds() (ids []int) {
	var (
		lists []*model.ServerOption
		err   error
	)

	if err = query.Use(config.DB).ServerOption.Scan(&lists); err != nil {
		logrus.Warnf("GetServerIds 查询出错 lists err:%+v", err)
		return nil
	}

	for _, v := range lists {
		ids = append(ids, int(v.ServerID))
	}

	return
}

func (s *sServerOption) ConfigOption(ctx *gin.Context) (list, simple, json []forms.Option) {
	var (
		q     = query.Use(config.DB).ServerOption
		m     = q.WithContext(ctx)
		lists []*model.ServerOption
		err   error
	)

	// 加载json配置选项
	for _, server := range gmdata.Servers {
		json = append(json, forms.Option{
			Value: server.ServerId,
			Label: fmt.Sprintf("%v(%v)", server.ServerName, server.ServerId),
			Name:  server.ServerName,
		})
	}

	if len(json) == 0 {
		json = make([]forms.Option, 0)
	}

	if err = m.Scan(&lists); err != nil {
		logrus.Warnf("查询出错 lists err:%+v", err)
		return
	}
	list = append(list, forms.Option{
		Value: 0,
		Label: "全服",
		Name:  "全服",
	})
	for _, v := range lists {
		list = append(list, forms.Option{
			Value: v.ServerID,
			Label: fmt.Sprintf("%v(%v)", v.Name, v.ServerID),
			Name:  v.Name,
		})

		simple = append(simple, forms.Option{
			Value: v.ServerID,
			Label: fmt.Sprintf("%v(%v)", v.Name, v.ServerID),
			Name:  v.Name,
		})
	}

	return
}

// Option 选项
func (s *sServerOption) Option(ctx *gin.Context) (list []forms.Option) {
	var (
		q     = query.Use(config.DB).ServerOption
		m     = q.WithContext(ctx)
		lists []*model.ServerOption
		err   error
	)

	if err = m.Scan(&lists); err != nil {
		logrus.Warnf("查询出错 lists err:%+v", err)
		return list
	}
	list = append(list, forms.Option{
		Value: int32(0),
		Label: "全服",
		Name:  "全服",
	})
	for _, v := range lists {
		list = append(list, forms.Option{
			Value: v.ServerID,
			Label: fmt.Sprintf("%v(%v)", v.Name, v.ServerID),
			Name:  v.Name,
		})
	}
	return list
}

func (s *sServerOption) GetName(ctx *gin.Context, serverId int32) (name string, err error) {
	var (
		q      = query.Use(config.DB).ServerOption
		m      = q.WithContext(ctx)
		models *model.ServerOption
	)

	if err = m.Where(q.ServerID.Eq(serverId)).Scan(&models); err != nil {
		logrus.Warnf("GetName 查询出错 models err:%+v", err)
		return
	}

	if models == nil {
		name = "未知"
		return
	}

	name = models.Name
	return
}
