<script setup>
import {ref} from "vue";
import "@/lib/array.js"
import useUtils from "@/utils/utils.js";
import TLabel from "@/components/ui/TLabel.vue";
import TDivider from "@/components/ui/TDivider.vue";
import PlusButton from "@/components/common/PlusButton.vue";

const props = defineProps({
	"v-countries": Array
})
const emits = defineEmits(["update:modelValue"])

let oldCountries = props.vCountries
if (oldCountries == null) {
	oldCountries = []
}
let oldCountryIds = oldCountries.$map(function (k, v) {
	return v.id
})

const countries = ref(oldCountries)
const countryIds = ref(oldCountryIds)

const utils = useUtils()

const add = function () {
	let countryStringIds = countryIds.value.map(function (v) {
		return v.toString()
	})
	utils.popup("/ui/selectCountriesPopup?countryIds=" + countryStringIds.join(","), {
		width: "48em",
		callback: function (resp) {
			countries.value = resp.data.countries
			change()
		}
	})
}

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

const change = function () {
	countryIds.value = countries.value.$map(function (k, v) {
		return v.id
	})
	emits("update:modelValue", JSON.stringify(countryIds.value))
}
</script>

<template>
	<div>
		<input type="hidden" name="countryIdsJSON" :value="JSON.stringify(countryIds)"/>
		<div v-if="countries.length > 0" style="margin-bottom: 0.5em" class="flex flex-wrap gap-2">
			<TLabel v-for="(country, index) in countries" outlined="">{{ country.name }}
				<a href="" title="删除" @click.prevent="remove(index)"><i class="pi pi-remove"></i></a></TLabel>
			<TDivider></TDivider>
		</div>
		<div>
			<PlusButton size="small" type="button" @click.prevent="add"></PlusButton>
		</div>
	</div>
</template>

<style scoped>

</style>