<template>
	<div class="flex items-center gap-2">
		<el-input
			v-model="password"
			type="password"
			show-password
			v-bind="$attrs"
			:placeholder="hasPassword ? '已设置密码' : '请输入密码'"
			:disabled="!canEnter"
			@blur="encryptPassword"
		/>
		<el-button v-if="hasPassword" @click="resetPassword">重置密码</el-button>
	</div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'

const password = ref('')
const canEnter = ref(false)

const modelValue = defineModel<{ rsa_aesKey: string; cipher_text: string }>()

// 存在密码
const hasPassword = computed(() => {
	const h = !password.value?.trim() && modelValue.value?.cipher_text
	canEnter.value = !h
	return h
})

// 加密处理
const encryptPassword = () => {
	if (!password.value?.trim()) {
		return
	}

	/// 获取AES秘钥
	// @ts-ignore
	const aesKey = window?.BpmTools?.$generateAESKey()

	// 将AES秘钥加密
	// @ts-ignore
	const rsaAesKey = window?.BpmTools?.$encryptAESKey(aesKey)

	// 进行AES算法加密密码
	// @ts-ignore
	const newPwd = window?.BpmTools?.$encryptDataWithAES(aesKey, password.value)

	// rsaAesKey和newPwd构建db_password字段
	modelValue.value = {
		rsa_aesKey: rsaAesKey,
		cipher_text: newPwd
	}
}

const resetPassword = () => {
	password.value = ''
	canEnter.value = true
	modelValue.value = {
		rsa_aesKey: '',
		cipher_text: ''
	}
}
</script>

<style scoped></style>
