package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"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(c)

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

func startConsume(c config.Config) {
	//svcCtx := svc.NewServiceContext(c)
	go func() {
		for {
			notice := &domain.ObjectNotice{
				CompanyId:         1598224576532189184,
				TableId:           521,
				TableType:         "主表",
				ObjectType:        "导入模块",
				Event:             "table.data.edit",
				TableAffectedList: []int{521},
				DataChanged:       true,
				StructChanged:     true,
				MetaData: domain.ObjectNoticeMetaData{
					Module: 0,
					Status: 0,
				},
			}
			mBytes, _ := json.Marshal(notice)
			err := kq.NewPusher(c.KqConsumerConf.Brokers, c.KqConsumerConf.Topic).Push(string(mBytes))
			fmt.Println(err)
			time.Sleep(10 * 10 * time.Second)
		}
	}()
	//kafka消费队列 处理字库推送事件
	go func() {
		svcCtx := svc.NewServiceContext(c)
		queue, err := kq.NewQueue(c.KqConsumerConf, consumer.NewByteNoticeLogic(svcCtx))
		if err != nil {
			panic(err)
		} else {
			queue.Start()
		}
	}()
	//redis消费队列 处理表数据存储到本地
	go func() {
		for {
			svcCtx := svc.NewServiceContext(c)
			str, err := svcCtx.Redis.Rpop(c.Name + ":table_data")
			if err == nil {
				_ = consumer.NewByteTableDataLogic(svcCtx).Sync(str)
			}
			time.Sleep(3 * time.Second)
		}
	}()
	//kq.MustNewQueue(c.KqConsumerConf, consumer.NewByteNoticeLogic(svcCtx))
	//for {
	//time.Sleep(1 * time.Second)
	//}
}