// Copyright (c) 2025, Jingrow and contributors
// For license information, please see license.txt

jingrow.ui.form.on("Jsite Server", {
	refresh(frm) {
		if (frm.pg.instance_id) {
			frm.add_custom_button(__('重启'), function() {
				// 弹出确认对话框
				jingrow.confirm(
					__('确定要重启服务器吗？重启过程中服务器将暂时不可用。'),
					function() {
						restart_server(frm);
					}
				);
			});
			
			frm.add_custom_button(__('重置密码'), function() {
				// 弹出密码输入对话框
				jingrow.prompt(
					{ 
						fieldtype: 'Password', 
						label: __('服务器密码'), 
						fieldname: 'new_password', 
						reqd: 1,
						description: __('长度为 8 至 30 个字符，必须同时包含大小写英文字母、数字和特殊符号。')
					},
					function(values) {
						if (values.new_password) {
							reset_password(frm, values.new_password);
						} else {
							jingrow.msgprint({
								title: __('错误'),
								message: __('请输入新密码'),
								indicator: 'red'
							});
						}
					},
					__('重置服务器密码')
				);
			});
			
			frm.add_custom_button(__('重置密钥对'), function() {
				// 弹出确认对话框
				jingrow.confirm(
					__('确定要重置密钥对吗？这将删除旧的密钥对并创建新的密钥对。重置后需要使用新的私钥才能连接服务器。'),
					function() {
						reset_key_pair(frm);
					}
				);
			});
			
			frm.add_custom_button(__('重置系统'), function() {
				// 弹出确认对话框
				jingrow.confirm(
					__('确定要重置系统吗？这将清除所有数据并重新安装系统，操作不可逆！'),
					function() {
						reset_system(frm);
					}
				);
			});
			
			frm.add_custom_button(__('创建防火墙规则'), function() {
				// 弹出防火墙规则创建对话框
				let dialog = new jingrow.ui.Dialog({
					title: __('创建防火墙规则'),
					fields: [
						{
							fieldtype: 'Select',
							label: __('协议'),
							fieldname: 'rule_protocol',
							options: [
								{label: 'TCP', value: 'TCP'},
								{label: 'UDP', value: 'UDP'},
								{label: 'ICMP', value: 'ICMP'}
							],
							reqd: 1,
							default: 'TCP'
						},
						{
							fieldtype: 'Data',
							label: __('端口'),
							fieldname: 'port',
							reqd: 1,
							description: __('单个端口号或端口范围（例如：80 或 8000/9000）')
						},
						{
							fieldtype: 'Data',
							label: __('备注'),
							fieldname: 'remark',
							description: __('防火墙规则的说明（可选）')
						}
					],
					primary_action_label: __('创建'),
					primary_action: function() {
						let values = dialog.get_values();
						if (values.rule_protocol && values.port) {
							create_firewall_rule(frm, values.rule_protocol, values.port, values.remark);
							dialog.hide();
						} else {
							jingrow.msgprint({
								title: __('错误'),
								message: __('请填写协议和端口信息'),
								indicator: 'red'
							});
						}
					}
				});
				dialog.show();
			});
			
			frm.add_custom_button(__('同步防火墙规则'), function() {
				// 弹出确认对话框
				jingrow.confirm(
					__('确定要同步防火墙规则吗？'),
					function() {
						sync_firewall_rules(frm);
					}
				);
			});
			
			frm.add_custom_button(__('同步服务器数据'), function() {
				// 弹出确认对话框
				jingrow.confirm(
					__('确定要同步服务器数据吗？这将从阿里云同步最新的服务器信息，包括状态、IP地址、系统信息、规格和防火墙规则等。'),
					function() {
						sync_server_data(frm);
					}
				);
			});
		}
		
		// 为password字段添加眼睛图标
		if (frm.get_field('password')) {
			let password_field = frm.get_field('password');
			
			// 确保toggle-password按钮可见
			password_field.toggle_password.removeClass('hidden');
			
			// 重写toggle_password的点击事件
			password_field.toggle_password.off('click').on('click', function() {
				if (password_field.$input.attr('type') === 'password') {
					// 使用jingrow.call获取解密后的密码
					jingrow.call({
						method: 'jcloud.api.aliyun_server_light.get_password',
						args: {
							pagetype: 'Jsite Server',
							name: frm.pg.name,
							fieldname: 'password'
						},
						callback: function(r) {
							if (r.message) {
								password_field.$input.attr('type', 'text');
								password_field.$input.val(r.message);
								password_field.toggle_password.html(jingrow.utils.icon('hide', 'sm'));
							} else {
								jingrow.msgprint({
									title: __('提示'),
									message: __('当前没有保存的密码'),
									indicator: 'yellow'
								});
							}
						}
					});
				} else {
					password_field.$input.attr('type', 'password');
					password_field.$input.val('••••••••');
					password_field.toggle_password.html(jingrow.utils.icon('unhide', 'sm'));
				}
			});
		}
	}
});

function restart_server(frm) {
	jingrow.call({
		method: 'jcloud.api.aliyun_server_light.reboot_aliyun_instance',
		args: {
			instance_id: frm.pg.instance_id,
			region_id: frm.pg.region
		}
	});
}

function reset_password(frm, new_password) {
	jingrow.call({
		method: 'jcloud.api.aliyun_server_light.reset_aliyun_instance_password',
		args: {
			instance_id: frm.pg.instance_id,
			password: new_password,
			region_id: frm.pg.region
		}
	});
}

function reset_key_pair(frm) {
	jingrow.call({
		method: 'jcloud.api.aliyun_server_light.reset_server_key_pair',
		args: {
			instance_id: frm.pg.instance_id
		}
	});
}

function reset_system(frm) {
	jingrow.call({
		method: 'jcloud.api.aliyun_server_light.reset_aliyun_instance_system',
		args: {
			instance_id: frm.pg.instance_id,
			region_id: frm.pg.region
		}
	});
}

function create_firewall_rule(frm, rule_protocol, port, remark) {
	jingrow.call({
		method: 'jcloud.api.aliyun_server_light.create_aliyun_firewall_rule',
		args: {
			instance_id: frm.pg.instance_id,
			rule_protocol: rule_protocol,
			port: port,
			remark: remark,
			region_id: frm.pg.region
		},
		callback: function(r) {
			if (r.message && r.message.success) {
				jingrow.msgprint({
					title: __('成功'),
					message: __('防火墙规则创建成功'),
					indicator: 'green'
				});
				// 创建成功后自动同步防火墙规则
				setTimeout(function() {
					sync_firewall_rules(frm);
				}, 2000);
			} else {
				jingrow.msgprint({
					title: __('错误'),
					message: r.message ? r.message.message : __('创建防火墙规则失败'),
					indicator: 'red'
				});
			}
		}
	});
}

function sync_firewall_rules(frm) {
	jingrow.call({
		method: 'jcloud.api.aliyun_server_light.sync_firewall_rules',
		args: {
			instance_id: frm.pg.instance_id
		},
		callback: function(r) {
			if (r.message && r.message.success) {
				jingrow.msgprint({
					title: __('成功'),
					message: r.message.message || __('防火墙规则同步成功'),
					indicator: 'green'
				});
				// 刷新表单以显示最新的防火墙规则
				frm.reload_pg();
			} else {
				jingrow.msgprint({
					title: __('错误'),
					message: r.message ? r.message.message : __('同步防火墙规则失败'),
					indicator: 'red'
				});
			}
		}
	});
}

function sync_server_data(frm) {
	jingrow.call({
		method: 'jcloud.api.aliyun_server_light.update_server_record',
		args: {
			instance_ids: JSON.stringify([frm.pg.instance_id])
		},
		callback: function(r) {
			if (r.message && r.message.success) {
				jingrow.msgprint({
					title: __('成功'),
					message: r.message.message || __('服务器数据同步成功'),
					indicator: 'green'
				});
				// 刷新表单以显示最新的服务器数据
				frm.reload_pg();
			} else {
				jingrow.msgprint({
					title: __('错误'),
					message: r.message ? r.message.message : __('同步服务器数据失败'),
					indicator: 'red'
				});
			}
		}
	});
}
