<template>
	<Dialog
		:options="{
			title: '添加新的应用市场应用',
			size: 'xl',
			actions: [
				{
					label: '添加应用',
					variant: 'solid',
					disabled: (!appValidated && !selectedVersion) || !this.app.is_public,
					onClick: addApp
				}
			]
		}"
		v-model="show"
		@update:modelValue="
			() => {
				show = false;
			}
		"
	>
		<template #body-content>
			<GitHubAppSelector
				class="pt-2"
				@validateApp="validateApp"
				@fieldChange="appValidated = false"
			/>
			<LinkControl
				v-if="selectedBranch"
				class="mt-4"
				type="autocomplete"
				label="选择版本"
				:options="{ pagetype: 'Jingrow Version', filters: { public: 1 } }"
				v-model="selectedVersion"
			/>
			<div class="mt-4 space-y-2">
				<div
					v-if="$resources.validateApp.loading && !appValidated"
					class="flex text-base text-gray-700"
				>
					<LoadingIndicator class="mr-2 w-4" />
					正在验证应用...
				</div>
				<div v-if="appValidated" class="flex text-base text-gray-700">
					<div v-if="this.app.is_public === true" class="flex gap-1">
						<FeatherIcon
							class="w-4 p-0.5 text-white rounded bg-green-500"
							name="check"
							:stroke-width="3"
						/>
						找到 {{ this.app.title }} ({{ this.app.name }})
					</div>
					<div v-else-if="this.app.is_public === false">
						<div class="flex text-base text-gray-700 gap-1">
							<FeatherIcon
								class="w-4 p-0.5 text-white rounded bg-red-500"
								name="x"
							/>
							Github 仓库是私有的。
							<Link
								href="https://jingrow.com/marketplace/terms"
								class="font-medium"
							>
								条款和政策
							</Link>
						</div>
					</div>
					<div v-else class="h-4"></div>
				</div>
			</div>
			<ErrorMessage :message="$resources.validateApp.error" />
		</template>
	</Dialog>
</template>

<script>
import { toast } from 'vue-sonner';
import GitHubAppSelector from '../GitHubAppSelector.vue';
import LinkControl from '../LinkControl.vue';
import { getToastErrorMessage } from '../../utils/toast';

export default {
	components: {
		GitHubAppSelector,
		LinkControl
	},
	data() {
		return {
			show: true,
			app: {},
			selectedBranch: '',
			selectedVersion: '',
			appValidated: false,
			selectedGithubUser: null,
			selectedGithubRepository: null
		};
	},
	resources: {
		validateApp() {
			return {
				url: 'jcloud.api.github.app',
				onSuccess: async data => {
					this.appValidated = true;
					if (!data) {
						return;
					}

					const repo_owner = this.selectedGithubUser?.login;
					const repo = this.selectedGithubRepository || data.name;
					const repository_url = `https://github.com/${repo_owner}/${repo}`;
					this.app = {};
					const isPublic = await this.checkRepoVisibility(repo_owner, repo);

					this.app = {
						name: data.name,
						title: data.title,
						repository_url,
						github_installation_id: this.selectedGithubUser?.id,
						branch: this.selectedBranch.value,
						is_public: isPublic
					};
				}
			};
		},
		addApp() {
			return {
				url: 'jcloud.api.client.insert',
				makeParams() {
					return {
						pg: {
							...this.app,
							pagetype: 'Marketplace App',
							version: this.selectedVersion
						}
					};
				}
			};
		}
	},
	methods: {
		addApp() {
			toast.promise(this.$resources.addApp.submit(), {
				loading: '正在添加新应用...',
				success: () => {
					this.show = false;
					this.$router.push({
						name: 'Marketplace App Detail Listing',
						params: { name: this.app.name }
					});
					return '新应用已添加';
				},
				error: e => getToastErrorMessage(e)
			});
		},
		validateApp(data) {
this.selectedBranch = {
				label: data.branch,
				value: data.branch
			};
			this.selectedGithubRepository = data.repository;
			this.selectedGithubUser = data.selectedGithubUser;

			this.$resources.validateApp.submit({
				...data,
				installation: data.selectedGithubUser.id
			});
		},
		async checkRepoVisibility(owner, repo) {
			try {
				const response = await fetch(
					`http://git.jingrow.com:3000/api/v1/repos/${owner}/${repo}`
				);
				if (!response.ok) {
					throw new Error('仓库未找到或为私有');
				}

				const repoData = await response.json();
				return !repoData.private; // 如果为公开返回 true，私有返回 false
			} catch (error) {
				console.error(error);
				return false; // 如果出错则假定为 false
			}
		}
	}
};
</script>