<script setup>

import {inject, ref, watch} from "vue"
import SourceCodeBox from "@/components/common/SourceCodeBox.vue";
import TCheckboxBinary from "@/components/ui/TCheckboxBinary.vue";
import DefinitionTable from "@/components/common/DefinitionTable.vue";

const props = defineProps(["id", "v-script-config", "comment", "v-auditing-status"])

const emits = defineEmits(["change"])
const utils = inject("$utils")

const {config, auditingStatus} = (function () {
	let config = props.vScriptConfig
	if (config == null) {
		config = {
			isPrior: false,
			isOn: false,
			code: "",
			auditingCode: ""
		}
	}

	let auditingStatus = null
	if (config.auditingCodeMD5 != null && config.auditingCodeMD5.length > 0 && config.auditingCode != null && config.auditingCode.length > 0) {
		config.code = config.auditingCode

		if (props.vAuditingStatus != null) {
			for (let i = 0; i < props.vAuditingStatus.length; i++) {
				let status = props.vAuditingStatus[i]
				if (status.md5 == config.auditingCodeMD5) {
					auditingStatus = status
					break
				}
			}
		}
	}

	if (config.code.length == 0) {
		config.code = "\n\n\n\n"
	}

	return {
		config: ref(config),
		auditingStatus: ref(auditingStatus)
	}
})()

const change = function () {
	emits("change", config.value)
}

const changeCode = function (code) {
	config.value.code = code
	change()
}

const isPlus = function () {
	return utils.CURRENT_CTX.teaCommon.teaIsPlus
}

watch(() => config.value.isOn, function () {
	change()
})

</script>

<template>
	<div>
		<DefinitionTable>
			<tbody>
			<tr>
				<td class="title">启用脚本设置</td>
				<td>
					<TCheckboxBinary v-model="config.isOn"></TCheckboxBinary>
				</td>
			</tr>
			</tbody>
			<tbody>
			<tr :style="{opacity: !config.isOn ? 0.5 : 1}">
				<td>脚本代码</td>
				<td>
					<p class="comment" v-if="auditingStatus != null">
						<span class="green" v-if="auditingStatus.isPassed">管理员审核结果：审核通过。</span>
						<span class="red" v-else-if="auditingStatus.isRejected">管理员审核结果：驳回 &nbsp; &nbsp; 驳回理由：{{ auditingStatus.rejectedReason }}</span>
						<span class="red" v-else>当前脚本将在审核后生效，请耐心等待审核结果。 <a href="/servers/user-scripts" target="_blank" v-if="isPlus()">去审核 &raquo;</a></span>
					</p>
					<p class="comment" v-if="auditingStatus == null"><span class="green">管理员审核结果：审核通过。</span>
					</p>
					<SourceCodeBox :id="id" type="text/javascript" :read-only="false" @change="changeCode">{{ config.code }}</SourceCodeBox>
					<p class="comment">{{ comment }}</p>
				</td>
			</tr>
			</tbody>
		</DefinitionTable>
	</div>
</template>

<style scoped>
</style>
