package feishu

import (
	"context"
	"encoding/json"
	"fmt"
	"user-behavior/pkg/model"

	"github.com/larksuite/oapi-sdk-go/core"
	"github.com/larksuite/oapi-sdk-go/core/config"
	"github.com/spf13/viper"

	//contact "github.com/larksuite/oapi-sdk-go/service/contact/v3"
	"github.com/larksuite/oapi-sdk-go/api/core/response"
	"github.com/larksuite/oapi-sdk-go/core/tools"
	im "github.com/larksuite/oapi-sdk-go/service/im/v1"
)

const default_appId = "cli_a2b00226a83dd00c"

const default_appSecret = "1YB8MlkJHc52VYIVpDiJAfwayhVVLwD4"

var token = "t-ee715dae553f06ea196dd3911285920c875df6be"

var token_timestamp = ""

var appSettings *config.AppSettings

func getAppSettings() *config.AppSettings {
	if appSettings == nil {
		appSettings = core.NewInternalAppSettings(
			core.SetAppCredentials(viper.GetString("feishu_bot.app_id"), viper.GetString("feishu_bot.app_secret")), // Required
			core.SetAppEventKey(token, "EncryptKey"), // Not required. Required for event、card subscription
		)
	}
	return appSettings
}

func SendMessageToChat(text string, chatId string) {
	// Currently, you are visiting larksuite, which uses default storage and default log (error level). More optional configurations are as follows: core.NewConfig()
	appSettings := getAppSettings()
	conf := core.NewConfig(core.DomainFeiShu, appSettings, core.SetLoggerLevel(core.LoggerLevelError))

	// The content of the sent message
	imService := im.NewService(conf)
	coreCtx := core.WrapContext(context.Background())
	reqCall := imService.Messages.Create(coreCtx, &im.MessageCreateReqBody{
		ReceiveId: chatId,
		Content:   `{"text":"` + text + `"}`,
		MsgType:   "text",
	})
	reqCall.SetReceiveIdType("chat_id")
	message, err := reqCall.Do()
	// 打印 request_id 方便 oncall 时排查问题
	fmt.Println(coreCtx.GetRequestID())
	fmt.Println(coreCtx.GetHTTPStatusCode())
	if err != nil {
		fmt.Println(tools.Prettify(err))
		e := err.(*response.Error)
		fmt.Println(e.Code)
		fmt.Println(e.Msg)
		return
	}
	fmt.Println(tools.Prettify(message))

}

func SendMessageToURL(text string, url string) {

}

func SendMessageToShiftMessageChat(text string) {
	SendMessageToChat(text, viper.GetString("feishu_chats.shift_message_chat"))
}

func SendMessageToShiftMessageURL(text string) {
	SendMessageToURL(text, viper.GetString("feishu_url.shift_message_url"))
}

func SendMessageToInternalReportChat(text string) {
	SendMessageToChat(text, viper.GetString("feishu_chats.internal_report_chat"))
}

func SendMessageToInternalReportURL(text string) {
	SendMessageToChat(text, viper.GetString("feishu_chats.internal_report_url"))
}

func SendMessageToWarningChat(text string) {
	SendMessageToURL(text, viper.GetString("feishu_url.warning_chat"))
}

func SendMessageToWarningURL(text string) {
	SendMessageToURL(text, viper.GetString("feishu_url.warning_url"))
}

// Card Related
func SendCardToChat(params model.FeishuCardParams, chatId string) {
	appSettings := getAppSettings()
	conf := core.NewConfig(core.DomainFeiShu, appSettings, core.SetLoggerLevel(core.LoggerLevelError))

	// The content of the sent message
	imService := im.NewService(conf)
	coreCtx := core.WrapContext(context.Background())
	reqCall := imService.Messages.Create(coreCtx, &im.MessageCreateReqBody{
		ReceiveId: chatId,
		Content:   generateFeishuCardJsonString(params),
		MsgType:   "interactive",
	})
	reqCall.SetReceiveIdType("chat_id")
	message, err := reqCall.Do()
	// 打印 request_id 方便 oncall 时排查问题
	fmt.Println(coreCtx.GetRequestID())
	fmt.Println(coreCtx.GetHTTPStatusCode())
	if err != nil {
		fmt.Println(tools.Prettify(err))
		e := err.(*response.Error)
		fmt.Println(e.Code)
		fmt.Println(e.Msg)
		return
	}
	fmt.Println(tools.Prettify(message))
}

func generateFeishuCardJsonString(params model.FeishuCardParams) string {
	config := CardConfig{WideScreenMode: true}
	title := CardTitle{Tag: "markdown", Content: params.Title}
	header := CardHeader{ColorTemplate: params.Color, Title: title}
	elements := []CardElement{{Tag: "markdown", Content: params.Text}}
	card := FeishuCard{Config: config, Header: header, Elements: elements}
	b, err := json.Marshal(&card)
	if err != nil {
		panic(err)
	}
	return string(b)
}

func SendCardToShiftMessageChat(params model.FeishuCardParams) {
	SendCardToChat(params, viper.GetString("feishu_chats.shift_message_chat"))
}

func SendCardToInternalReportChat(params model.FeishuCardParams) {
	SendCardToChat(params, viper.GetString("feishu_chats.internal_report_chat"))
}

func SendCardToMonitorChat(params model.FeishuCardParams) {
	SendCardToChat(params, viper.GetString("feishu_chats.monitor_chat"))
}
