<script setup>
import "@/lib/array.js"
import {inject, ref} from "vue"
import TDivider from "@/components/ui/TDivider.vue";
import TButton from "@/components/ui/TButton.vue";
import TLabel from "@/components/ui/TLabel.vue";

const utils = inject("$utils")
const props = defineProps(["v-type", "v-countries"])
const emits = defineEmits(["change"])

const {listType, countries} = (function () {
	let countries = props.vCountries
	if (countries == null) {
		countries = []
	}

	return {
		listType: ref(props.vType),
		countries: ref(countries)
	}
})()

const addCountry = function () {
	let selectedCountryIds = countries.value.map(function (country) {
		return country.id
	})
	utils.popup("/servers/server/settings/waf/ipadmin/selectCountriesPopup?type=" + listType.value + "&selectedCountryIds=" + selectedCountryIds.join(","), {
		width: "52em",
		height: "30em",
		callback: function (resp) {
			countries.value = resp.data.selectedCountries
			notifyChange()
		}
	})
}

const removeCountry = function (index) {
	countries.value.$remove(index)
	notifyChange()
}

const resetCountries = function () {
	countries.value = []
	notifyChange()
}

const notifyChange = function () {
	emits("change", {
		"countries": countries.value
	})
}

</script>

<template>
	<div>
		<span v-if="countries.length == 0" class="disabled">暂时没有选择<span v-if="listType =='allow'">允许</span><span v-else>封禁</span>的区域。</span>
		<div v-show="countries.length > 0" class="label-group">
			<TLabel outlined="" v-for="(country, index) in countries">
				<input type="hidden" :name="listType + 'CountryIds'" :value="country.id"/>
				({{ country.letter }}){{ country.name }}
				<a href="" @click.prevent="removeCountry(index)" title="删除"><i class="icon remove"></i></a>
			</TLabel>
		</div>
		<TDivider></TDivider>
		<TButton type="button" secondary="" size="small" @click.prevent="addCountry">修改</TButton> &nbsp;
		<TButton type="button" secondary="" size="small" v-show="countries.length > 0" @click.prevent="resetCountries">清空</TButton>
	</div>
</template>

<style scoped>
</style>
