<template>
	<Dialog
		v-model="showDialog"
		:options="{ title: `更改 ${app.title} 的分支` }"
	>
		<template #body-content>
			<div class="flex flex-col items-center">
				<Button
					class="w-min"
					v-if="$resources.branches.loading"
					:loading="true"
					loadingText="加载中..."
				/>
				<FormControl
					v-else
					class="w-full"
					label="选择分支"
					type="select"
					:options="$resources.branches.data"
					v-model="selectedBranch"
				/>
				<ErrorMessage
					class="mt-2 w-full"
					:message="$resources.changeBranch.error"
				/>
			</div>
		</template>
		<template #actions>
			<Button
				v-if="!$resources.branches.loading"
				class="w-full"
				variant="solid"
				label="更改分支"
				:loading="$resources.changeBranch.loading"
				@click="changeBranch()"
			/>
		</template>
	</Dialog>
</template>

<script>
import { DashboardError } from '../../utils/error';

export default {
	name: 'ChangeAppBranchDialog',
	emits: ['branchChange'],
	props: ['bench', 'app'],
	data() {
		return {
			selectedBranch: this.app.branch,
			showDialog: true
		};
	},
	resources: {
		branches() {
			return {
				url: 'jcloud.api.bench.branch_list',
				params: {
					name: this.bench,
					app: this.app.name
				},
				auto: true,
				initialData: [],
				transform(data) {
					return data.map(d => d.name);
				}
			};
		},
		changeBranch() {
			return {
				url: 'jcloud.api.bench.change_branch',
				onSuccess() {
					this.$emit('branchChange');
					this.showDialog = false;
				},
				validate() {
					if (this.selectedBranch == this.app.branch) {
						throw new DashboardError('请选择一个不同的分支');
					}
				}
			};
		}
	},
	methods: {
		changeBranch() {
			this.$resources.changeBranch.submit({
				name: this.bench,
				app: this.app.name,
				to_branch: this.selectedBranch
			});
		}
	}
};
</script>