<script setup lang="ts">
import { ref, computed } from 'vue'
import { changePassword } from '@/api/auth'

// 表单数据
const formData = ref({
  old_password: '',
  new_password: '',
  confirm_password: '',
})

// 密码可见性
const passwordVisible = ref({
  old: false,
  new: false,
  confirm: false,
})

// 提交状态
const submitting = ref(false)

// 密码强度
const passwordStrength = computed(() => {
  const password = formData.value.new_password
  if (!password)
    return { level: 0, text: '', color: '' }

  let strength = 0
  // 长度检查
  if (password.length >= 8)
    strength++
  if (password.length >= 12)
    strength++
  // 复杂度检查
  if (/[a-z]/.test(password))
    strength++
  if (/[A-Z]/.test(password))
    strength++
  if (/\d/.test(password))
    strength++
  if (/[^a-zA-Z\d]/.test(password))
    strength++

  if (strength <= 2)
    return { level: 1, text: '弱', color: '#ff6b6b' }
  if (strength <= 4)
    return { level: 2, text: '中', color: '#e68815' }
  return { level: 3, text: '强', color: '#3ed268' }
})

// 表单验证
const isFormValid = computed(() => {
  const { old_password, new_password, confirm_password } = formData.value
  return (
    old_password.length > 0
    && new_password.length >= 8
    && new_password === confirm_password
  )
})

// 切换密码可见性
function togglePasswordVisible(field: 'old' | 'new' | 'confirm') {
  passwordVisible.value[field] = !passwordVisible.value[field]
}

// 提交修改
async function submitChange() {
  // 验证表单
  if (!formData.value.old_password) {
    uni.showToast({
      title: '请输入当前密码',
      icon: 'none',
    })
    return
  }

  if (formData.value.new_password.length < 8) {
    uni.showToast({
      title: '新密码至少8位',
      icon: 'none',
    })
    return
  }

  if (formData.value.new_password !== formData.value.confirm_password) {
    uni.showToast({
      title: '两次密码输入不一致',
      icon: 'none',
    })
    return
  }

  if (formData.value.old_password === formData.value.new_password) {
    uni.showToast({
      title: '新密码不能与当前密码相同',
      icon: 'none',
    })
    return
  }

  submitting.value = true

  try {
    // 调用修改密码接口
    await changePassword({
      old_password: formData.value.old_password,
      new_password: formData.value.new_password,
    })

    uni.showToast({
      title: '密码修改成功',
      icon: 'success',
      duration: 2000,
    })

    // 清除登录状态
    uni.removeStorageSync('admin-token')
    uni.removeStorageSync('refresh_token')
    uni.removeStorageSync('user_info')

    // 延迟跳转到登录页
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/common/login/index',
      })
    }, 2000)
  }
  catch (error: any) {
    console.error('修改密码失败:', error)
    // 如果是前端逻辑错误（非 API 错误），需要手动显示提示
    if (error instanceof Error && error.message && !error.statusCode) {
      uni.$u.toast(error.message)
    }
    // API 请求错误已由拦截器统一处理
  }
  finally {
    submitting.value = false
  }
}

// 清空表单
function clearForm() {
  formData.value = {
    old_password: '',
    new_password: '',
    confirm_password: '',
  }
}
</script>

<template>
  <view class="bg-[var(--bg-page)] min-h-screen pb-safe">
    <view class="px-4 pt-5">
      <view class="bg-white rounded-12px p-4 mb-3">
        <text class="text-12px text-[#999] block mb-2">当前密码</text>
        <view class="flex items-center">
          <input
            v-model="formData.old_password"
            :password="!passwordVisible.old"
            class="flex-1 text-16px text-[#212121]"
            placeholder="请输入当前密码"
            placeholder-class="text-[#ccc]"
          >
          <image
            :src="passwordVisible.old ? '/static/icons/preview-open.png' : '/static/icons/preview-close-one.png'"
            class="w-20px h-20px"
            mode="aspectFit"
            @click="togglePasswordVisible('old')"
          />
        </view>
      </view>

      <view class="bg-white rounded-12px p-4 mb-3">
        <view class="flex items-center justify-between mb-2">
          <text class="text-12px text-[#999]">新密码</text>
          <text
            v-if="formData.new_password"
            :style="{ color: passwordStrength.color }"
            class="text-12px font-600"
          >
            {{ passwordStrength.text }}
          </text>
        </view>
        <view class="flex items-center">
          <input
            v-model="formData.new_password"
            :password="!passwordVisible.new"
            class="flex-1 text-16px text-[#212121]"
            placeholder="请输入新密码"
            placeholder-class="text-[#ccc]"
          >
          <image
            :src="passwordVisible.new ? '/static/icons/preview-open.png' : '/static/icons/preview-close-one.png'"
            class="w-20px h-20px"
            mode="aspectFit"
            @click="togglePasswordVisible('new')"
          />
        </view>
        <view v-if="formData.new_password" class="flex items-center gap-1 mt-2">
          <view
            v-for="i in 3"
            :key="i"
            class="flex-1 h-2px rounded-full"
            :style="{ backgroundColor: i <= passwordStrength.level ? passwordStrength.color : '#e0e0e0' }"
          />
        </view>
      </view>

      <view class="bg-white rounded-12px p-4 mb-3">
        <text class="text-12px text-[#999] block mb-2">确认密码</text>
        <view class="flex items-center">
          <input
            v-model="formData.confirm_password"
            :password="!passwordVisible.confirm"
            class="flex-1 text-16px text-[#212121]"
            placeholder="请再次输入新密码"
            placeholder-class="text-[#ccc]"
          >
          <image
            :src="passwordVisible.confirm ? '/static/icons/preview-open.png' : '/static/icons/preview-close-one.png'"
            class="w-20px h-20px"
            mode="aspectFit"
            @click="togglePasswordVisible('confirm')"
          />
        </view>
        <view v-if="formData.confirm_password" class="mt-2">
          <text
            :class="[
              'text-12px',
              formData.new_password === formData.confirm_password ? 'text-[#52c41a]' : 'text-[#ff4d4f]',
            ]"
          >
            {{ formData.new_password === formData.confirm_password ? '密码一致' : '密码不一致' }}
          </text>
        </view>
      </view>

      <view
        :class="[
          'py-4 rounded-12px text-center text-16px font-600',
          isFormValid && !submitting
            ? 'bg-brand text-white'
            : 'bg-[#f5f5f5] text-[#ccc]',
        ]"
        @click="submitChange"
      >
        {{ submitting ? '修改中...' : '确认修改' }}
      </view>

      <view class="bg-white rounded-12px p-4 mt-4">
        <text class="text-13px font-600 text-[#212121] block mb-3">密码要求</text>
        <view class="space-y-2">
          <view class="flex items-center gap-2">
            <text :class="formData.new_password.length >= 8 ? 'text-[#52c41a]' : 'text-[#ccc]'">●</text>
            <text class="text-13px text-[#666]">至少8个字符</text>
          </view>
          <view class="flex items-center gap-2">
            <text :class="/[a-zA-Z]/.test(formData.new_password) ? 'text-[#52c41a]' : 'text-[#ccc]'">●</text>
            <text class="text-13px text-[#666]">包含字母</text>
          </view>
          <view class="flex items-center gap-2">
            <text :class="/\d/.test(formData.new_password) ? 'text-[#52c41a]' : 'text-[#ccc]'">●</text>
            <text class="text-13px text-[#666]">包含数字</text>
          </view>
          <view class="flex items-center gap-2">
            <text :class="/[^a-zA-Z\d]/.test(formData.new_password) ? 'text-[#52c41a]' : 'text-[#ccc]'">●</text>
            <text class="text-13px text-[#666]">包含特殊字符</text>
          </view>
        </view>
      </view>

      <view class="h-8" />
    </view>
  </view>
</template>

<style scoped>
.center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.space-y-3 > view:not(:last-child) {
  margin-bottom: 12px;
}

.space-y-2 > view:not(:last-child) {
  margin-bottom: 8px;
}

.leading-relaxed {
  line-height: 1.6;
}

.space-y-2 > view:not(:last-child) {
  margin-bottom: 8px;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}
</style>
