package main

import (
	"flag"
	"github.com/golang-jwt/jwt/v4/request"
	"github.com/zeromicro/go-queue/kq"
	"github.com/zeromicro/go-zero/core/logx"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/api/internal/config"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/api/internal/handler"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/api/internal/logic/consumer"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/api/internal/svc"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/db"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/domain"
	"net/http"
	"strings"
	"time"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/core.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	// 默认的token头 Authorization 修改未 x-token
	request.AuthorizationHeaderExtractor = &request.PostExtractionFilter{
		request.HeaderExtractor{"x-mmm-accesstoken"}, func(tok string) (string, error) {
			// Should be a bearer token
			if len(tok) > 6 && strings.ToUpper(tok[0:7]) == "BEARER " {
				return tok[7:], nil
			}
			return tok, nil
		},
	}

	// 初始化Domain里面的配置
	domain.ProjectName = c.Name

	opts := make([]rest.RunOption, 0)
	// cors
	opt := rest.WithCustomCors(func(header http.Header) {
		header.Set("Access-Control-Allow-Headers", "*")
	}, func(writer http.ResponseWriter) {

	})
	opts = append(opts, opt)

	server := rest.MustNewServer(c.RestConf, opts...)
	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	db.Migrate(ctx.DB)
	//启动消费队列
	startConsume(ctx)

	logx.Infof("Starting server at %s:%d...  \n", c.Host, c.Port)
	server.Start()
}

func startConsume(svcCtx *svc.ServiceContext) {
	//kafka消费队列 处理字库推送事件
	go func() {
		queue, err := kq.NewQueue(svcCtx.Config.KqConsumerConf, consumer.NewByteNoticeLogic(svcCtx))
		if err != nil {
			panic(err)
		} else {
			queue.Start()
		}
	}()
	//redis消费队列 处理表数据存储到本地
	go func() {
		for {
			str, err := svcCtx.Redis.Rpop(svcCtx.Config.Name + ":table_data")
			if err == nil {
				_ = consumer.NewByteTableDataLogic(svcCtx).Sync(str)
			}
			time.Sleep(3 * time.Second)
		}
	}()
}