<script setup>
import useUtils from "@/utils/utils.js";
import {ref} from "vue";
import TButton from "@/components/ui/TButton.vue";
import "@/components/ui/services/date.js"
import TLabel from "@/components/ui/TLabel.vue";
import TDivider from "@/components/ui/TDivider.vue";

const props = defineProps([
	"v-certs", // 证书列表
	"v-cert", // 单个证书
	"v-protocol", // 协议：https|tls
	"v-view-size", // 弹窗尺寸：normal, mini
	"v-single-mode", // 单证书模式
	"v-description", // 描述文字
	"v-domains", // 搜索的域名列表或者函数
	"v-user-id" // 用户ID
])
const emits = defineEmits(["update:modelValue"])

const {certs, description} = (() => {
	let certs = props.vCerts
	if (certs == null) {
		certs = []
	}
	if (props.vCert != null) {
		certs.push(props.vCert)
		setTimeout(() => change())
	}

	let description = props.vDescription
	if (description == null || typeof (description) != "string") {
		description = ""
	}
	return {certs: ref(certs), description: ref(description)}
})()
setTimeout(() => change())

const certIds = function () {
	return certs.value.map(function (v) {
		return v.id
	})
}

const utils = useUtils()

// 删除证书
const removeCert = function (index) {
	utils.confirm("确定删除此证书吗？证书数据仍然保留，只是当前网站不再使用此证书。", function () {
		certs.value.$remove(index)
		change()
	})
}

// 选择证书
const selectCert = function () {
	let searchingDomains = []
	if (props.vDomains != null) {
		if (typeof props.vDomains == "function") {
			let resultDomains = props.vDomains()
			if (resultDomains != null && typeof resultDomains == "object" && (resultDomains instanceof Array)) {
				searchingDomains = resultDomains
			}
		} else if (typeof props.vDomains == "object" && (props.vDomains instanceof Array)) {
			searchingDomains = props.vDomains
		}
		if (searchingDomains.length > 10000) {
			searchingDomains = searchingDomains.slice(0, 10000)
		}
	}

	let selectedCertIds = certs.value.map(function (cert) {
		return cert.id
	})
	let userId = props.vUserId
	if (userId == null) {
		userId = 0
	}

	utils.popup("/servers/certs/selectPopup?viewSize=&searchingDomains=" + window.encodeURIComponent(searchingDomains.join(",")) + "&selectedCertIds=" + selectedCertIds.join(",") + "&userId=" + userId, {
		width: "50em",
		height: "40em",
		callback: function (resp) {
			if (resp.data.cert != null) {
				certs.value.push(resp.data.cert)
			}
			if (resp.data.certs != null) {
				certs.value.$pushAll(resp.data.certs)
			}
			change()
		}
	})
}

// 上传证书
const uploadCert = function () {
	let userId = props.vUserId
	if (typeof userId != "number" && typeof userId != "string") {
		userId = 0
	}
	utils.popup("/servers/certs/uploadPopup?userId=" + userId, {
		height: "28em",
		callback: function (resp) {
			utils.success("上传成功", function () {
				if (resp.data.cert != null) {
					certs.value.push(resp.data.cert)
				}
				if (resp.data.certs != null) {
					certs.value.$pushAll(resp.data.certs)
				}
				change()
			})
		}
	})
}

// 批量上传
const uploadBatch = function () {
	let userId = props.vUserId
	if (typeof userId != "number" && typeof userId != "string") {
		userId = 0
	}
	utils.popup("/servers/certs/uploadBatchPopup?userId=" + userId, {
		height: "30em",
		callback: function (resp) {
			if (resp.data.cert != null) {
				certs.value.push(resp.data.cert)
			}
			if (resp.data.certs != null) {
				certs.value.$pushAll(resp.data.certs)
			}
			change()
		}
	})
}

// 格式化时间
const formatTime = function (timestamp) {
	return new Date(timestamp * 1000).format("Y-m-d")
}

// 判断是否显示选择｜上传按钮
const buttonsVisible = function () {
	return props.vSingleMode == null || !props.vSingleMode || certs.value == null || certs.value.length == 0
}

const change = () => {
	emits("update:modelValue", JSON.stringify(certIds()))
}

</script>

<template>
	<div>
		<input type="hidden" name="certIdsJSON" :value="JSON.stringify(certIds())"/>
		<div v-if="certs != null && certs.length > 0" class="label-group">
			<TLabel v-for="(cert, index) in certs" outlined="">
				{{ cert.name }} / {{ cert.dnsNames }} / 有效至{{ formatTime(cert.timeEndAt) }} &nbsp; <a href=""
																										 title="删除"
																										 @click.prevent="removeCert(index)"><i
				class="pi pi-remove"></i></a>
			</TLabel>
			<TDivider v-if="buttonsVisible()"></TDivider>
		</div>
		<div v-else>
			<span class="red" v-if="description.length == 0">选择或上传证书后<span
				v-if="vProtocol == 'https'">HTTPS</span><span v-if="vProtocol == 'tls'">TLS</span>服务才能生效。</span>
			<span class="grey" v-if="description.length > 0">{{ description }}</span>
			<TDivider v-if="buttonsVisible()"></TDivider>
		</div>
		<div v-if="buttonsVisible()" class="my-4">
			<TButton secondary="" size="small" @click.prevent="selectCert()">选择已有证书</TButton> &nbsp;
			<span class="disabled">|</span> &nbsp;
			<TButton secondary="" size="small" @click.prevent="uploadCert()">上传新证书</TButton> &nbsp;
			<TButton secondary="" size="small" @click.prevent="uploadBatch()">批量上传证书</TButton> &nbsp;
		</div>
	</div>
</template>

<style scoped>

</style>