<template>
	<Dialog
		:options="{
			title: '添加标签',
			actions: [
				{
					label: '添加',
					variant: 'solid',
					onClick: () =>
						addNewTag(
							selectedTag?.value === '__new__' ? newTag : selectedTag.value
						)
				}
			]
		}"
		v-model="show"
	>
		<template #body-content>
			<FormControl
				v-if="selectedTag?.value !== '__new__'"
				label="选择标签"
				type="autocomplete"
				v-model="selectedTag"
				:options="tagOptions"
			/>
			<FormControl
				v-if="selectedTag?.value === '__new__'"
				v-model="newTag"
				label="输入新标签并按回车"
				placeholder="生产, 测试, 预发布"
				@keydown.enter="e => addNewTag(e.target.value)"
			/>
		</template>
	</Dialog>
</template>
<script>
import {
	Autocomplete,
	Dialog,
	FormControl,
	getCachedDocumentResource
} from 'jingrow-ui';

export default {
	name: 'AddTagDialog',
	props: ['pagetype', 'docname'],
	emits: ['added', 'removed'],
	components: { Dialog, Autocomplete, FormControl },
	data() {
		return {
			selectedTag: null,
			newTag: '',
			show: true
		};
	},
	resources: {
		existingTags() {
			return {
				type: 'list',
				pagetype: 'Jcloud Tag',
				filters: { pagetype_name: this.pagetype },
				fields: ['tag'],
				pageLength: 1000,
				auto: true
			};
		}
	},
	methods: {
		addNewTag(value) {
			if (!value) return;
			let $pg = getCachedDocumentResource(this.pagetype, this.docname);
			if (!$pg) return;
			return $pg.addTag.submit({ tag: value }).then(() => {
				this.$emit('added', value);
				this.show = false;
			});
		}
	},
	computed: {
		tagOptions() {
			return [
				{ label: '创建新标签', value: '__new__' },
				...(this.$resources.existingTags.data || []).map(d => ({
					label: d.tag,
					value: d.tag
				}))
			];
		}
	}
};
</script>