<template>
	<div
		class="mx-auto max-w-3xl space-y-4"
		v-if="$appServer?.pg?.actions && $dbServer?.pg?.actions"
	>
		<div
			v-for="group in actions"
			:key="group.group"
			class="divide-y rounded border border-gray-200 p-5"
		>
			<div class="pb-3 text-lg font-semibold">{{ group.group }}</div>
			<div
				class="py-3 first:pt-0 last:pb-0"
				v-for="row in group.actions"
				:key="row.action"
			>
				<ServerActionCell
					:group="group.group"
					:serverName="row.server_name"
					:serverType="row.server_pagetype"
					:actionLabel="row.action"
					:method="row.pg_method"
					:description="row.description"
					:buttonLabel="row.button_label"
				/>
			</div>
		</div>
	</div>
</template>
<script>
import { getCachedDocumentResource } from 'jingrow-ui';
import ServerActionCell from './ServerActionCell.vue';
import { getDocResource } from '../../utils/resource';

export default {
	name: 'ServerActions',
	props: ['server'],
	components: { ServerActionCell },
	computed: {
		actions() {
			const totalActions = [
				...this.$appServer.pg.actions,
				...this.$dbServer.pg.actions,
				...(this.$dbReplicaServer?.pg?.actions || [])
			];

			const groupedActions = totalActions.reduce((acc, action) => {
				const group = action.group || `${action.server_pagetype} 操作`;
				if (!acc[group]) {
					acc[group] = [];
				}
				acc[group].push(action);
				return acc;
			}, {});

			let groups = Object.keys(groupedActions).map(group => {
				return {
					group,
					actions: groupedActions[group]
				};
			});

			// 将危险操作移到底部
			const dangerousActions = groups.find(
				group => group.group === '危险操作'
			);
			if (dangerousActions) {
				groups = groups.filter(group => group.group !== '危险操作');
				groups.push(dangerousActions);
			}

			return groups;
		},
		$appServer() {
			return getCachedDocumentResource('Server', this.server);
		},
		$dbServer() {
			return getDocResource({
				pagetype: 'Database Server',
				name: this.$appServer.pg.database_server,
				whitelistedMethods: {
					changePlan: 'change_plan',
					reboot: 'reboot',
					rename: 'rename'
				}
			});
		},
		$dbReplicaServer() {
			return getDocResource({
				pagetype: 'Database Server',
				name: this.$appServer.pg.replication_server,
				whitelistedMethods: {
					changePlan: 'change_plan',
					reboot: 'reboot',
					rename: 'rename'
				}
			});
		}
	}
};
</script>