<script setup lang="ts">
import { computed, ref, watch, onUnmounted } from 'vue'
import { NInput, NPopover } from 'naive-ui'

const props = defineProps<{ df: any; record: Record<string, any>; canEdit: boolean; ctx: any }>()

// Label布局:上下结构(vertical) 或 左右结构(horizontal)
const labelLayout = computed(() => props.df.label_layout || 'vertical')

// 密码校验相关状态
const showValidationPopover = ref(false)
const validationMessage = ref('')
let validationTimer: ReturnType<typeof setTimeout> | null = null

// 仅对new_password字段进行前端校验
const shouldValidate = computed(() => props.df.fieldname === 'new_password')

// 监听密码输入变化
watch(() => props.record[props.df.fieldname], (newValue) => {
  if (!shouldValidate.value || !newValue || !props.canEdit) {
    showValidationPopover.value = false
    return
  }

  // 防抖处理：延迟300ms后执行校验
  if (validationTimer) {
    clearTimeout(validationTimer)
  }
  
  validationTimer = setTimeout(() => {
    validatePassword(newValue)
  }, 300)
})

// 前端密码格式校验
function validatePassword(password: string) {
  if (!password || password.length === 0) {
    showValidationPopover.value = false
    return
  }

  const errors: string[] = []
  
  // 最小长度检查（通常8位）
  if (password.length < 8) {
    errors.push(props.ctx.t('Password must be at least 8 characters'))
  }
  
  // 检查是否包含小写字母
  if (!/[a-z]/.test(password)) {
    errors.push(props.ctx.t('Password must contain lowercase letters'))
  }
  
  // 检查是否包含大写字母
  if (!/[A-Z]/.test(password)) {
    errors.push(props.ctx.t('Password must contain uppercase letters'))
  }
  
  // 检查是否包含数字
  if (!/[0-9]/.test(password)) {
    errors.push(props.ctx.t('Password must contain numbers'))
  }
  
  // 检查是否包含特殊字符
  if (!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) {
    errors.push(props.ctx.t('Password must contain special characters'))
  }
  
  // 如果有错误，显示提示
  if (errors.length > 0) {
    validationMessage.value = props.ctx.t('Password strength insufficient') + '：' + errors.join('、')
    showValidationPopover.value = true
  } else {
    showValidationPopover.value = false
  }
}

// 清理定时器
const cleanupTimer = () => {
  if (validationTimer) {
    clearTimeout(validationTimer)
    validationTimer = null
  }
}

// 组件卸载时清理
onUnmounted(() => {
  cleanupTimer()
})
</script>

<template>
  <div :class="['field-wrapper', `layout-${labelLayout}`]">
    <label class="field-label">
      {{ ctx.t(df.label || df.fieldname) }}
      <span v-if="df.reqd" class="required">*</span>
    </label>
    <n-popover
      v-if="shouldValidate"
      :show="showValidationPopover"
      trigger="manual"
      placement="bottom-start"
      :show-arrow="true"
      style="max-width: 400px"
    >
      <template #trigger>
        <n-input 
          v-model:value="record[df.fieldname]" 
          type="password"
          placeholder=""
          :disabled="!canEdit"
          :status="showValidationPopover ? 'error' : undefined"
        />
      </template>
      <div class="password-validation-message">
        {{ validationMessage }}
      </div>
    </n-popover>
    <n-input 
      v-else
      v-model:value="record[df.fieldname]" 
      type="password"
      placeholder=""
      :disabled="!canEdit"
    />
  </div>
</template>

<style scoped>
.field-wrapper :deep(.n-input) {
  flex: 1;
}

.password-validation-message {
  color: #d03050;
  font-size: 13px;
  line-height: 1.5;
  padding: 4px 0;
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
