﻿package main

import (
	"log"

	"verification-platform-backend/internal/database"
	"verification-platform-backend/internal/model"

	"gorm.io/gorm"
)

func main() {
	database.Init()

	var app model.Application
	if err := database.DB.First(&app).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			log.Fatal("没有找到任何应用，请先创建应用")
		}
		log.Fatal("查询应用失败:", err)
	}

	log.Printf("使用应用: %s (ID: %d)", app.Name, app.ID)

	var existingVar model.CloudVariable
	err := database.DB.Where("app_id = ? AND key = ?", app.ID, "orders").First(&existingVar).Error
	if err == gorm.ErrRecordNotFound {
		ordersVar := model.CloudVariable{
			UserID:          app.UserID,
			AppID:           &app.ID,
			Key:             "orders",
			DefaultValue:    "",
			VarType:         "stream",
			MaxRecords:      10000,
			Scope:           "app",
			WritePermission: "app_user",
			Description:     "订单记录存储",
			Status:          "active",
		}
		if err := database.DB.Create(&ordersVar).Error; err != nil {
			log.Fatal("创建订单变量失败:", err)
		}
		log.Println("创建订单变量成功: orders")
	} else {
		log.Println("订单变量已存在: orders")
	}

	functions := []struct {
		Name        string
		Key         string
		Description string
		Code        string
	}{
		{
			Name:        "测试推送",
			Key:         "test_push",
			Description: "测试Telegram推送是否正常",
			Code: `var telegramToken = params.telegram_token || "";
var chatId = params.chat_id || "";

if (!telegramToken || !chatId) {
    return { error: "缺少telegram_token或chat_id参数" };
}

var msg = "用户: " + (params.username || "未知") + "\n";
msg += "程序: " + (params.app || "未知") + "\n";
msg += "内容: 信息接收测试, 接收到本消息则表明测试正常.";

var url = "https://api.telegram.org/bot" + telegramToken + "/sendMessage";
var result = http.post(url, {
    "Content-Type": "application/json"
}, {
    chat_id: chatId,
    text: msg
});

if (result.error) {
    return { success: false, error: result.error };
}

return { success: true, data: result.json };`,
		},
		{
			Name:        "读取订单",
			Key:         "read_order",
			Description: "读取并存储订单记录，推送到Telegram",
			Code: `var telegramToken = params.telegram_token || "";
var chatId = params.chat_id || "";
var order = params.order || {};

if (!order.TID) {
    return { error: "缺少订单号TID" };
}

var msg = "用户: " + (params.username || "未知") + "\n";
msg += "程序: " + (params.app || "未知") + "\n";
msg += "类型: 读取注单\n";
msg += "单号: " + (order.TID || "") + "\n";
msg += "时间: " + (order.DATETIME || "") + "\n";
msg += "会员: " + (order.NAME0 || "") + "\n";
msg += "球种: " + (order.GT || "") + "\n";
msg += "赛段: " + (order.SESSION || "") + "\n";
msg += "玩法: " + (order.WAGERS_TYPE || "") + "\n";
if (order.SRV_IP === "手机") {
    msg += "手机\n";
}
msg += "联盟: " + (order.LEAGUE || "") + "\n";
msg += "队伍: " + (order.TEAM_H || "") + " : " + (order.TEAM_C || "") + "\n";
msg += "比分: " + (order.SCORE || "") + "\n";
msg += "盘口: " + (order.ORDER_CON || "") + "\n";
msg += "下注: " + (order.ORDER_TYPE || "") + "\n";
msg += "赔率: " + (order.IORATIO || "") + "\n";
msg += "金额: " + (order.GOLD || "") + "\n";
msg += "开赛时间: " + (order.G_TIME || "");

var telegramResult = null;
if (telegramToken && chatId) {
    var url = "https://api.telegram.org/bot" + telegramToken + "/sendMessage";
    telegramResult = http.post(url, {
        "Content-Type": "application/json"
    }, {
        chat_id: chatId,
        text: msg
    });
}

return {
    action: "add_record",
    variable_key: "orders",
    record_data: order,
    message: msg,
    telegram_result: telegramResult
};`,
		},
		{
			Name:        "接收订单",
			Key:         "accept_order",
			Description: "接收订单通知",
			Code: `var telegramToken = params.telegram_token || "";
var chatId = params.chat_id || "";
var order = params.order || {};

var msg = "用户: " + (params.username || "未知") + "\n";
msg += "程序: " + (params.app || "未知") + "\n";
msg += "类型: 接收注单\n";
msg += "单号: " + (order.TID || "") + "\n";
msg += "时间: " + (order.DATETIME || "") + "\n";
msg += "会员: " + (order.NAME0 || "") + "\n";
msg += "球种: " + (order.GT || "") + "\n";
msg += "赛段: " + (order.SESSION || "") + "\n";
msg += "玩法: " + (order.WAGERS_TYPE || "") + "\n";
if (order.SRV_IP === "手机") {
    msg += "手机\n";
}
msg += "联盟: " + (order.LEAGUE || "") + "\n";
msg += "队伍: " + (order.TEAM_H || "") + " : " + (order.TEAM_C || "") + "\n";
msg += "比分: " + (order.SCORE || "") + "\n";
msg += "盘口: " + (order.ORDER_CON || "") + "\n";
msg += "下注: " + (order.ORDER_TYPE || "") + "\n";
msg += "赔率: " + (order.IORATIO || "") + "\n";
msg += "金额: " + (order.GOLD || "") + "\n";
msg += "开赛时间: " + (order.G_TIME || "");

var telegramResult = null;
if (telegramToken && chatId) {
    var url = "https://api.telegram.org/bot" + telegramToken + "/sendMessage";
    telegramResult = http.post(url, {
        "Content-Type": "application/json"
    }, {
        chat_id: chatId,
        text: msg
    });
}

return {
    action: "add_record",
    variable_key: "orders",
    record_data: order,
    message: msg,
    telegram_result: telegramResult
};`,
		},
		{
			Name:        "筛选订单",
			Key:         "screen_order",
			Description: "筛选订单通知",
			Code: `var telegramToken = params.telegram_token || "";
var chatId = params.chat_id || "";
var order = params.order || {};

var msg = "用户: " + (params.username || "未知") + "\n";
msg += "程序: " + (params.app || "未知") + "\n";
msg += "类型: 筛选注单\n";
msg += "单号: " + (order.TID || "") + "\n";
msg += "时间: " + (order.DATETIME || "") + "\n";
msg += "会员: " + (order.NAME0 || "") + "\n";
msg += "球种: " + (order.GT || "") + "\n";
msg += "赛段: " + (order.SESSION || "") + "\n";
msg += "玩法: " + (order.WAGERS_TYPE || "") + "\n";
if (order.SRV_IP === "手机") {
    msg += "手机\n";
}
msg += "联盟: " + (order.LEAGUE || "") + "\n";
msg += "队伍: " + (order.TEAM_H || "") + " : " + (order.TEAM_C || "") + "\n";
msg += "比分: " + (order.SCORE || "") + "\n";
msg += "最新比分: " + (order.SCORE_NEW || "") + "\n";
msg += "盘口: " + (order.ORDER_CON || "") + "\n";
msg += "最新盘口: " + (order.ORDER_CON_NEW || "") + "\n";
msg += "下注: " + (order.ORDER_TYPE || "") + "\n";
msg += "赔率: " + (order.IORATIO || "") + "\n";
msg += "最新赔率: " + (order.IORATIO_NEW || "") + "\n";
msg += "金额: " + (order.GOLD || "") + "\n";
msg += "开赛时间: " + (order.G_TIME || "") + "\n";
msg += "过滤原因: " + (order.REASON || "");

var telegramResult = null;
if (telegramToken && chatId) {
    var url = "https://api.telegram.org/bot" + telegramToken + "/sendMessage";
    telegramResult = http.post(url, {
        "Content-Type": "application/json"
    }, {
        chat_id: chatId,
        text: msg
    });
}

return {
    action: "add_record",
    variable_key: "orders",
    record_data: order,
    message: msg,
    telegram_result: telegramResult
};`,
		},
		{
			Name:        "跟单成功",
			Key:         "bet_order_success",
			Description: "跟单成功通知",
			Code: `var telegramToken = params.telegram_token || "";
var chatId = params.chat_id || "";
var order = params.order || {};

var msg = "用户: " + (params.username || "未知") + "\n";
msg += "程序: " + (params.app || "未知") + "\n";
msg += "类型: 跟单成功\n";
msg += "单号: " + (order.TID || "") + "\n";
msg += "时间: " + (order.DATETIME || "") + "\n";
msg += "会员: " + (order.NAME0 || "") + "\n";
msg += "球种: " + (order.GT || "") + "\n";
msg += "赛段: " + (order.SESSION || "") + "\n";
msg += "玩法: " + (order.WAGERS_TYPE || "") + "\n";
if (order.SRV_IP === "手机") {
    msg += "手机\n";
}
msg += "联盟: " + (order.LEAGUE || "") + "\n";
msg += "队伍: " + (order.TEAM_H || "") + " : " + (order.TEAM_C || "") + "\n";
msg += "比分: " + (order.SCORE || "") + "\n";
msg += "最新比分: " + (order.SCORE_NEW || "") + "\n";
msg += "盘口: " + (order.ORDER_CON || "") + "\n";
msg += "最新盘口: " + (order.ORDER_CON_NEW || "") + "\n";
msg += "下注: " + (order.ORDER_TYPE || "") + "\n";
msg += "赔率: " + (order.IORATIO || "") + "\n";
msg += "最新赔率: " + (order.IORATIO_NEW || "") + "\n";
msg += "金额: " + (order.GOLD || "") + "\n";
msg += "开赛时间: " + (order.G_TIME || "");

var telegramResult = null;
if (telegramToken && chatId) {
    var url = "https://api.telegram.org/bot" + telegramToken + "/sendMessage";
    telegramResult = http.post(url, {
        "Content-Type": "application/json"
    }, {
        chat_id: chatId,
        text: msg
    });
}

return {
    action: "add_record",
    variable_key: "orders",
    record_data: order,
    message: msg,
    telegram_result: telegramResult
};`,
		},
		{
			Name:        "跟单失败",
			Key:         "bet_order_failed",
			Description: "跟单失败通知",
			Code: `var telegramToken = params.telegram_token || "";
var chatId = params.chat_id || "";
var order = params.order || {};

var msg = "用户: " + (params.username || "未知") + "\n";
msg += "程序: " + (params.app || "未知") + "\n";
msg += "类型: 跟单失败\n";
msg += "单号: " + (order.TID || "") + "\n";
msg += "时间: " + (order.DATETIME || "") + "\n";
msg += "会员: " + (order.NAME0 || "") + "\n";
msg += "球种: " + (order.GT || "") + "\n";
msg += "赛段: " + (order.SESSION || "") + "\n";
msg += "玩法: " + (order.WAGERS_TYPE || "") + "\n";
if (order.SRV_IP === "手机") {
    msg += "手机\n";
}
msg += "联盟: " + (order.LEAGUE || "") + "\n";
msg += "队伍: " + (order.TEAM_H || "") + " : " + (order.TEAM_C || "") + "\n";
msg += "比分: " + (order.SCORE || "") + "\n";
msg += "最新比分: " + (order.SCORE_NEW || "") + "\n";
msg += "盘口: " + (order.ORDER_CON || "") + "\n";
msg += "最新盘口: " + (order.ORDER_CON_NEW || "") + "\n";
msg += "下注: " + (order.ORDER_TYPE || "") + "\n";
msg += "赔率: " + (order.IORATIO || "") + "\n";
msg += "最新赔率: " + (order.IORATIO_NEW || "") + "\n";
msg += "金额: " + (order.GOLD || "") + "\n";
msg += "开赛时间: " + (order.G_TIME || "") + "\n";
msg += "失败原因: " + (order.REASON || "");

var telegramResult = null;
if (telegramToken && chatId) {
    var url = "https://api.telegram.org/bot" + telegramToken + "/sendMessage";
    telegramResult = http.post(url, {
        "Content-Type": "application/json"
    }, {
        chat_id: chatId,
        text: msg
    });
}

return {
    action: "add_record",
    variable_key: "orders",
    record_data: order,
    message: msg,
    telegram_result: telegramResult
};`,
		},
		{
			Name:        "账户掉线",
			Key:         "account_disconnected",
			Description: "账户掉线通知",
			Code: `var telegramToken = params.telegram_token || "";
var chatId = params.chat_id || "";

var msg = "用户: " + (params.username || "未知") + "\n";
msg += "程序: " + (params.app || "未知") + "\n";
msg += "类型: 账户掉线";

var telegramResult = null;
if (telegramToken && chatId) {
    var url = "https://api.telegram.org/bot" + telegramToken + "/sendMessage";
    telegramResult = http.post(url, {
        "Content-Type": "application/json"
    }, {
        chat_id: chatId,
        text: msg
    });
}

return { message: msg, telegram_result: telegramResult };`,
		},
		{
			Name:        "账户重连",
			Key:         "account_reconnected",
			Description: "账户重连通知",
			Code: `var telegramToken = params.telegram_token || "";
var chatId = params.chat_id || "";

var msg = "用户: " + (params.username || "未知") + "\n";
msg += "程序: " + (params.app || "未知") + "\n";
msg += "类型: 账户重连";

var telegramResult = null;
if (telegramToken && chatId) {
    var url = "https://api.telegram.org/bot" + telegramToken + "/sendMessage";
    telegramResult = http.post(url, {
        "Content-Type": "application/json"
    }, {
        chat_id: chatId,
        text: msg
    });
}

return { message: msg, telegram_result: telegramResult };`,
		},
		{
			Name:        "测试邮件",
			Key:         "test_email",
			Description: "测试SMTP邮件发送",
			Code: `var smtpConfig = params.smtp_config || {};
var to = params.to || [];

if (!smtpConfig.host || !smtpConfig.username || !smtpConfig.password) {
    return { error: "缺少SMTP配置参数" };
}

if (to.length === 0) {
    return { error: "缺少收件人地址" };
}

var subject = params.subject || "测试邮件";
var body = params.body || "这是一封测试邮件";
var html = params.html || false;

var result = smtp.send(smtpConfig, to, subject, body, html);

if (result.success) {
    return { success: true, message: "邮件发送成功" };
} else {
    return { success: false, error: result.error };
}`,
		},
		{
			Name:        "订单邮件通知",
			Key:         "order_email_notify",
			Description: "订单邮件通知，同时发送Telegram和邮件",
			Code: `var telegramToken = params.telegram_token || "";
var chatId = params.chat_id || "";
var smtpConfig = params.smtp_config || {};
var to = params.to || [];
var order = params.order || {};

if (!order.TID) {
    return { error: "缺少订单号TID" };
}

var msg = "用户: " + (params.username || "未知") + "\n";
msg += "程序: " + (params.app || "未知") + "\n";
msg += "类型: 订单通知\n";
msg += "单号: " + (order.TID || "") + "\n";
msg += "时间: " + (order.DATETIME || "") + "\n";
msg += "会员: " + (order.NAME0 || "") + "\n";
msg += "金额: " + (order.GOLD || "") + "\n";

var telegramResult = null;
if (telegramToken && chatId) {
    var url = "https://api.telegram.org/bot" + telegramToken + "/sendMessage";
    telegramResult = http.post(url, {
        "Content-Type": "application/json"
    }, {
        chat_id: chatId,
        text: msg
    });
}

var emailResult = null;
if (smtpConfig.host && to.length > 0) {
    var htmlBody = "<h2>订单通知</h2>";
    htmlBody += "<p><strong>用户:</strong> " + (params.username || "未知") + "</p>";
    htmlBody += "<p><strong>程序:</strong> " + (params.app || "未知") + "</p>";
    htmlBody += "<p><strong>单号:</strong> " + (order.TID || "") + "</p>";
    htmlBody += "<p><strong>时间:</strong> " + (order.DATETIME || "") + "</p>";
    htmlBody += "<p><strong>会员:</strong> " + (order.NAME0 || "") + "</p>";
    htmlBody += "<p><strong>金额:</strong> " + (order.GOLD || "") + "</p>";
    
    emailResult = smtp.send(smtpConfig, to, "订单通知 - " + (order.TID || ""), htmlBody, true);
}

return {
    action: "add_record",
    variable_key: "orders",
    record_data: order,
    message: msg,
    telegram_result: telegramResult,
    email_result: emailResult
};`,
		},
	}

	for _, fn := range functions {
		var existingFn model.DynamicCode
		err := database.DB.Unscoped().Where("application_id = ? AND key = ?", app.ID, fn.Key).First(&existingFn).Error
		if err == nil {
			database.DB.Unscoped().Delete(&existingFn)
			log.Printf("删除旧的云端函数: %s (key: %s)", fn.Name, fn.Key)
		}
		
		log.Printf("创建云端函数: %s (key: %s)", fn.Name, fn.Key)
		dynamicCode := model.DynamicCode{
			ApplicationID: app.ID,
			UserID:        &app.UserID,
			Name:          fn.Name,
			Key:           fn.Key,
			Code:          fn.Code,
			Description:   fn.Description,
			Status:        "active",
		}
		if err := database.DB.Create(&dynamicCode).Error; err != nil {
			log.Printf("创建云端函数失败 %s: %v", fn.Name, err)
		}
	}

	log.Println("\n=== 创建完成 ===")
	log.Println("云端变量: orders (记录类型)")
	log.Println("云端函数:")
	log.Println("  - test_push: 测试推送")
	log.Println("  - read_order: 读取订单")
	log.Println("  - accept_order: 接收订单")
	log.Println("  - screen_order: 筛选订单")
	log.Println("  - bet_order_success: 跟单成功")
	log.Println("  - bet_order_failed: 跟单失败")
	log.Println("  - account_disconnected: 账户掉线")
	log.Println("  - account_reconnected: 账户重连")
	log.Println("  - test_email: 测试邮件")
	log.Println("  - order_email_notify: 订单邮件通知")
}
