package init

import (
	"context"
	"flag"
	"fmt"
	"jyBXCore/entity"
	"jyBXCore/rpc/internal/config"
	"time"

	"app.yhyue.com/moapp/jypkg/middleground"
	_ "github.com/go-sql-driver/mysql"
	"github.com/zeromicro/go-zero/core/conf"
)

var (
	configFile     = flag.String("cf", "etc/bxcore.yaml", "the config file")
	C              config.Config
	dbFile         = flag.String("df", "etc/db.yaml", "the db file")
	DB             config.Db
	logFile        = flag.String("lf", "etc/logs.yaml", "the logs file")
	logc           entity.Logc
	SearchLimitKey = "jy_limitSearchText_new" // 全文或附件搜索限制
	Middleground   *middleground.Middleground
	Search_Thread  chan bool
	ReqLimitInit   *ReqLimit
)

type ReqLimit struct {
	DoPool   chan struct{}
	WaitPool chan struct{}
}

// -2 等待池已满
// -1 超时
// 1：可以执行查询
func (r *ReqLimit) Limit(ctx context.Context) int {
	ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
	defer cancel()
	select {
	case <-r.WaitPool:
		defer func() {
			r.WaitPool <- struct{}{}
		}()
		select {
		case <-r.DoPool:
			return 1
		case <-ctx.Done(): //超时
			return -1
		}
	default:
		return -2
	}
}

func (r *ReqLimit) Release() {
	r.DoPool <- struct{}{}
}
func init() {
	//基本配置
	conf.MustLoad(*configFile, &C)
	//数据库配置
	conf.MustLoad(*dbFile, &DB)
	//初始mongodb
	MongoDBInit(&DB.Mongo)
	//初始化msyql
	MysqlInit(&DB.Mysql)
	//初始redis
	RedisInit(&DB.Redis)
	//初始es
	EsInit(&DB.Es)
	NoLoginEsInit(&DB.EsNoLogin)
	EsFreeInit(&DB.EsFree)
	Search_Thread = make(chan bool, C.SearchConcurrency)
	NoLoginPoolInit(C.NoLoginSearch.Switch, C.NoLoginSearch.ExecutionNum, C.NoLoginSearch.Wait)
	//初始化标签
	LabelInit()
	//
	SearchLimitKey = fmt.Sprintf(C.LimitSearchText.LimitKey, "jy_limitSearchText")
	//初始化中台相关
	Middleground = middleground.NewMiddleground(C.Middleground.Etcd.Hosts).
		RegUserCenter(C.Middleground.UserCenterKey).
		RegPowerCheckCenter(C.Middleground.PowerCheckCenterKey).
		RegResourceCenter(C.Middleground.ResourceCenterKey)
}
