<template>
	<Dialog v-model="showDialog" :options="{ title }">
		<template #body-content>
			<div class="space-y-4">
				<p class="text-p-base text-gray-800" v-if="description">{{ description }}</p>
				<div class="space-y-4">
					<FormControl
						v-model="password"
						:fieldtype="'Password'"
						:label="'新密码'"
						:fieldname="'password'"
						:reqd="1"
						:description="'长度为 8 至 30 个字符，必须同时包含大小写英文字母、数字和特殊符号'"
					/>
					<FormControl
						v-model="confirmPassword"
						:fieldtype="'Password'"
						:label="'确认密码'"
						:fieldname="'confirm_password'"
						:reqd="1"
					/>
				</div>
			</div>
			<ErrorMessage class="mt-2" :message="error" />
		</template>
		<template #actions>
			<div class="flex gap-2 w-full">
				<Button 
					variant="outline" 
					class="flex-1"
					@click="hide"
				>
					取消
				</Button>
				<Button 
					variant="solid" 
					class="flex-1"
					:loading="isLoading"
					@click="onConfirm"
				>
					确定
				</Button>
			</div>
		</template>
	</Dialog>
</template>

<script>
import { ErrorMessage, FormControl } from 'jingrow-ui';

export default {
	name: 'PasswordDialog',
	props: ['title', 'description', 'onConfirm'],
	expose: ['show', 'hide'],
	data() {
		return {
			showDialog: true,
			error: null,
			isLoading: false,
			password: '',
			confirmPassword: ''
		};
	},
	components: { FormControl, ErrorMessage },
	methods: {
		validatePassword() {
			if (!this.password) {
				this.error = '请输入新密码';
				return false;
			}
			
			if (this.password.length < 8 || this.password.length > 30) {
				this.error = '密码长度必须在 8 至 30 个字符之间';
				return false;
			}
			
			// 检查密码复杂度：必须同时包含大小写英文字母、数字和特殊符号
			const hasUpperCase = /[A-Z]/.test(this.password);
			const hasLowerCase = /[a-z]/.test(this.password);
			const hasNumbers = /\d/.test(this.password);
			const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(this.password);
			
			if (!hasUpperCase || !hasLowerCase || !hasNumbers || !hasSpecialChar) {
				this.error = '密码必须同时包含大小写英文字母、数字和特殊符号';
				return false;
			}
			
			if (this.password !== this.confirmPassword) {
				this.error = '两次输入的密码不一致';
				return false;
			}
			
			return true;
		},
		async onConfirm() {
			this.error = null;
			
			if (!this.validatePassword()) {
				return;
			}
			
			this.isLoading = true;
			try {
				await this.onConfirm(this.password);
				this.hide();
			} catch (error) {
				this.error = error.message || '操作失败';
			} finally {
				this.isLoading = false;
			}
		},
		show() {
			this.showDialog = true;
			this.password = '';
			this.confirmPassword = '';
			this.error = null;
		},
		hide() {
			this.showDialog = false;
		}
	}
};
</script> 