package feishu

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"strings"

	//"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(params FeishuChatParams) *config.AppSettings {
	appSettings := core.NewInternalAppSettings(
		core.SetAppCredentials(params.AppId, params.AppSecret), // Required
		core.SetAppEventKey(token, "EncryptKey"),               // Not required. Required for event、card subscription
	)
	return appSettings
}

func SendMessageToChat(params FeishuChatParams, text string, chatId string) (string, error) {
	// Currently, you are visiting larksuite, which uses default storage and default log (error level). More optional configurations are as follows: core.NewConfig()
	appSettings := getAppSettings(params)
	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",
	})
	if strings.Contains(chatId, "ou_") {
		reqCall.SetReceiveIdType("open_id")
	} else if strings.Contains(chatId, "oc_") {
		reqCall.SetReceiveIdType("chat_id")
	} else if strings.Contains(chatId, "on_") {
		reqCall.SetReceiveIdType("union_id")
	} else if strings.Contains(chatId, "@") {
		reqCall.SetReceiveIdType("email")
	} else {
		reqCall.SetReceiveIdType("user_id")
	}
	message, err := reqCall.Do()
	// 打印 request_id 方便 oncall 时排查问题
	log.Println(coreCtx.GetRequestID())
	log.Println(coreCtx.GetHTTPStatusCode())
	if err != nil {
		//fmt.Println(tools.Prettify(err))
		e := err.(*response.Error)
		log.Println("Feishu messaging error:", e.Code)
		log.Println("Feishu error message:", e.Msg)
		log.Println("Message JSON causing the error:", text)
		log.Println("Receiver Id for the errored message:", chatId)
		return "", err
	}
	log.Println(tools.Prettify(message))
	return message.MessageId, nil
}

func SendMessageToShiftMessageChat(params FeishuChatParams, text string) (string, error) {
	return SendMessageToChat(params, text, viper.GetString("feishu_bot.feishu_chats.shift_message_chat"))
}

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

func SendMessageToInternalReportChat(params FeishuChatParams, text string) (string, error) {
	return SendMessageToChat(params, text, viper.GetString("feishu_bot.default.feishu_chats.internal_report_chat"))
}

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

func SendMessageToWarningChat(params FeishuChatParams, text string) (string, error) {
	return SendMessageToChat(params, text, viper.GetString("feishu_bot.default.feishu_chats.warning_chat"))
}

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

// Card Related
func SendCardToChat(settingParams FeishuChatParams, params FeishuCardParams, chatId string) (string, error) {
	appSettings := getAppSettings(settingParams)
	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())
	content, err := generateFeishuCardJsonString(params)
	if err != nil {
		return "", err
	}
	reqCall := imService.Messages.Create(coreCtx, &im.MessageCreateReqBody{
		ReceiveId: chatId,
		Content:   content,
		MsgType:   "interactive",
	})
	if strings.Contains(chatId, "ou_") {
		reqCall.SetReceiveIdType("open_id")
	} else if strings.Contains(chatId, "oc_") {
		reqCall.SetReceiveIdType("chat_id")
	} else if strings.Contains(chatId, "on_") {
		reqCall.SetReceiveIdType("union_id")
	} else if strings.Contains(chatId, "@") {
		reqCall.SetReceiveIdType("email")
	} else {
		reqCall.SetReceiveIdType("user_id")
	}
	message, err := reqCall.Do()
	// 打印 request_id 方便 oncall 时排查问题
	log.Println(coreCtx.GetRequestID())
	log.Println(coreCtx.GetHTTPStatusCode())
	if err != nil {
		log.Println(tools.Prettify(err))
		e := err.(*response.Error)
		//log.Println(e.Code)
		//log.Println(e.Msg)
		log.Println("Feishu messaging error:", e.Code)
		log.Println("Feishu error message:", e.Msg)
		log.Println("Message JSON causing the error:", content)
		log.Println("Receiver Id for the errored message:", chatId)
		return "", err
	}
	fmt.Println(tools.Prettify(message))
	return message.MessageId, nil
}

func generateFeishuCardJsonString(params FeishuCardParams) (string, error) {
	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 {
		return "", err
	}
	return string(b), nil
}

func generateCard(params FeishuCardParams) (FeishuCard, error) {
	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}}
	return FeishuCard{Config: config, Header: header, Elements: elements}, nil
}

func SendCardToShiftMessageChat(settingParams FeishuChatParams, params FeishuCardParams) (string, error) {
	return SendCardToChat(settingParams, params, viper.GetString("feishu_bot.default.feishu_chats.shift_message_chat"))
}

func SendCardToInternalReportChat(settingParams FeishuChatParams, params FeishuCardParams) (string, error) {
	return SendCardToChat(settingParams, params, viper.GetString("feishu_bot.default.feishu_chats.internal_report_chat"))
}

/*func processingReturnedMessage(msg *im.Message) error {
	if msg.
	return nil
}*/
