package feishu

import (
	"context"
	"fmt"
	"log"
	"poc-daily-report/pkg/model"
	"strconv"
	"sync"
	"time"

	lark "github.com/larksuite/oapi-sdk-go/v3"
	larkbitable "github.com/larksuite/oapi-sdk-go/v3/service/bitable/v1"
	"github.com/spf13/viper"
)

type botSetting struct {
	appId     string
	appSecret string
}

var clients map[botSetting]*lark.Client

var getClientMu sync.Mutex

func init() {
	clients = make(map[botSetting]*lark.Client)
}

func getClient(setting botSetting) *lark.Client {
	getClientMu.Lock()
	defer getClientMu.Unlock()
	client, ok := clients[setting]
	if ok {
		return client
	} else {
		log.Println("appid:", setting.appId, "appsecret:", setting.appSecret)
		newClient := lark.NewClient(setting.appId, setting.appSecret)
		clients[setting] = newClient
		return newClient
	}
	return nil
}

func getDefaultClient() *lark.Client {
	setting := botSetting{appId: viper.GetString("feishu_bot.app_id"), appSecret: viper.GetString("feishu_bot.app_secret")}
	return getClient(setting)
}

func AppendRecordToTable(clusters []model.FocusedCluster, tableParams model.FeishuTableParams, date time.Time) {
	client := getDefaultClient()
	records := []*larkbitable.AppTableRecord{}
	for _, cluster := range clusters {
		fields := map[string]interface{}{}
		fields["Tenant_ID"] = strconv.FormatUint(cluster.TenantId, 10)
		fields["Alias"] = cluster.TenantName
		fields["Region"] = cluster.Region
		fields["POC Status"] = cluster.POCStatus
		if cluster.ClusterId != 0 {
			fields["Cluster_ID"] = strconv.FormatUint(cluster.ClusterId, 10)
		}
		if cluster.ClusterStatus.Valid {
			fields["Cluster Status"] = cluster.ClusterStatus.String
		}
		if cluster.PausedHour != 0 {
			fields["Paused_hours"] = fmt.Sprintf("%f", cluster.PausedHour)
		}
		if cluster.QpsGt500Min != 0 {
			fields["Active_Minutes"] = strconv.Itoa(cluster.QpsGt500Min)
		}
		if cluster.MaxQPS != 0 {
			fields["MAX_QPS"] = fmt.Sprintf("%f", cluster.MaxQPS)
		}
		fields["POC Starttime"] = cluster.POCStartTime.UnixMilli()
		fields["Tenant Plan"] = cluster.PlanType
		if cluster.POCPresales.Valid {
			fields["POC_Presales"] = cluster.POCPresales.String
		}
		if cluster.POCEE.Valid {
			fields["POC EE"] = cluster.POCEE.String
		}
		fields["Detect date"] = date.UnixMilli()
		record := larkbitable.NewAppTableRecordBuilder().Fields(fields).Build()
		records = append(records, record)
	}
	resp, err := client.Bitable.AppTableRecord.BatchCreate(context.Background(), larkbitable.NewBatchCreateAppTableRecordReqBuilder().
		AppToken(tableParams.AppToken).
		TableId(tableParams.TableId).
		Body(larkbitable.NewBatchCreateAppTableRecordReqBodyBuilder().
			Records(records).
			Build()).
		Build())
	if err != nil {
		log.Println(err)
	}
	log.Println(resp.Code)
	log.Println(resp.Msg)
}
