<script setup lang="ts">
import { modifyPassword } from '@af-mobile-client-vue3/services/api/user'
import { useUserStore } from '@af-mobile-client-vue3/stores/modules/user'
import { validatePassword } from '@af-mobile-client-vue3/utils/login/loginVerify'
import { showDialog, showToast, Button as vanButton, Field as vanField, Form as vanForm, Icon as vanIcon, Popup as vanPopup } from 'vant'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'

const props = defineProps<{
  visible: boolean
  ename?: string
  password?: string
}>()

const emit = defineEmits<{
  (event: 'update:visible', value: boolean): void
}>()

const router = useRouter()
let userStore: any
const formRef = ref()

// 表单数据
const formData = reactive({
  oldPassword: props.password || '',
  newPassword: '',
  confirmPassword: '',
})

// 密码显示状态
const showOldPassword = ref(false)
const showNewPassword = ref(false)
const showConfirmPassword = ref(false)

// 加载状态
const loading = ref(false)

// 表单验证规则
const rules = computed(() => ({
  oldPassword: [
    { required: !props.password, message: '请输入旧密码' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码' },
    {
      validator: (value: string) => {
        if (!value)
          return true
        const result = validatePassword(value)
        if (!result.isValid) {
          return result.errors[0]
        }
        return true
      },
    },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码' },
    {
      validator: (value: string) => value === formData.newPassword,
      message: '两次密码输入不一致',
    },
  ],
}))

// 提交表单
async function handleSubmit() {
  try {
    // 1. 校验新密码格式
    const passwordResult = validatePassword(formData.newPassword)
    if (!passwordResult.isValid) {
      showToast(passwordResult.errors[0])
      return
    }
    // 2. 校验确认密码
    if (formData.newPassword !== formData.confirmPassword) {
      showToast('两次密码输入不一致')
      return
    }
    loading.value = true
    // 3. 表单校验
    await formRef.value?.validate()
    // 4. 调用修改密码API
    const result = await handleModifyPassword({
      data: {
        ename: props.ename || userStore.getUserInfo().username,
        password: props.password || formData.oldPassword,
        newpassword: formData.newPassword,
        affirmpassword: formData.confirmPassword,
      },
    })
    if (result.success) {
      showDialog({
        title: '成功',
        message: '修改密码成功，请重新登录',
        confirmButtonText: '立即重新登录',
      }).then(() => {
        // 退出登录
        userStore.logout()
        // 跳转到登录页
        router.push('/login')
      })
    }
    else {
      showToast(result.message || '修改密码失败!')
    }
  }
  catch (error) {
    console.error('修改密码失败:', error)
    showToast('修改密码失败，请检查输入信息')
  }
  finally {
    loading.value = false
  }
}

// 关闭弹窗
function closeModal() {
  emit('update:visible', false)
}

// 修改密码API调用
async function handleModifyPassword(data: any) {
  try {
    const res = await modifyPassword(data)
    if (res && (res.userId || res === 'true')) {
      return { success: true, message: '修改成功' }
    }
    else {
      return { success: false, message: '修改密码失败,请检查原始密码是否正确！' }
    }
  }
  catch (error: any) {
    return { success: false, message: error?.message || error?.msg || '修改密码失败' }
  }
}

// 监听visible变化，重置表单
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    formData.oldPassword = ''
    formData.newPassword = ''
    formData.confirmPassword = ''
    showOldPassword.value = false
    showNewPassword.value = false
    showConfirmPassword.value = false
  }
  else if (props.password) {
    formData.oldPassword = props.password
  }
})

onMounted(() => {
  try {
    userStore = useUserStore()
  }
  catch (error) {
    console.error('useUserStore error:', error)
    showToast(`初始化'登录'失败--${error}`)
  }
})
</script>

<template>
  <van-popup
    :show="props.visible"
    position="center"
    :close-on-click-overlay="false"
    round
    :z-index="1999"
    class="modify-password-popup"
    @update:show="emit('update:visible', $event)"
  >
    <div class="popup-content">
      <div class="popup-header">
        <h3 class="popup-title">
          修改密码
        </h3>
        <van-icon name="cross" class="close-icon" @click="closeModal" />
      </div>

      <van-form ref="formRef" class="password-form" @submit="handleSubmit">
        <van-field
          v-if="!props.password"
          v-model="formData.oldPassword"
          name="oldPassword"
          label="旧密码"
          placeholder="请输入旧密码"
          :type="showOldPassword ? 'text' : 'password'"
          :rules="rules.oldPassword"
          @click-right-icon="showOldPassword = !showOldPassword"
        >
          <template #right-icon>
            <van-icon
              :name="showOldPassword ? 'eye-o' : 'closed-eye'"
              color="#666"
            />
          </template>
        </van-field>

        <van-field
          v-model="formData.newPassword"
          name="newPassword"
          label="新密码"
          placeholder="请输入新密码"
          :type="showNewPassword ? 'text' : 'password'"
          :rules="rules.newPassword"
          @click-right-icon="showNewPassword = !showNewPassword"
        >
          <template #right-icon>
            <van-icon
              :name="showNewPassword ? 'eye-o' : 'closed-eye'"
              color="#666"
            />
          </template>
        </van-field>

        <van-field
          v-model="formData.confirmPassword"
          name="confirmPassword"
          label="确认新密码"
          placeholder="请再次输入新密码"
          :type="showConfirmPassword ? 'text' : 'password'"
          :rules="rules.confirmPassword"
          @click-right-icon="showConfirmPassword = !showConfirmPassword"
        >
          <template #right-icon>
            <van-icon
              :name="showConfirmPassword ? 'eye-o' : 'closed-eye'"
              color="#666"
            />
          </template>
        </van-field>

        <div class="form-buttons">
          <van-button
            plain
            type="default"
            size="large"
            class="cancel-btn"
            @click="closeModal"
          >
            取消
          </van-button>
          <van-button
            type="primary"
            size="large"
            native-type="submit"
            :loading="loading"
            class="submit-btn"
          >
            确认修改
          </van-button>
        </div>
      </van-form>
    </div>
  </van-popup>
</template>

<style scoped lang="less">
.modify-password-popup {
  width: 90%;
  max-width: 400px;

  .popup-content {
    padding: 20px;

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .popup-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        margin: 0;
      }

      .close-icon {
        font-size: 20px;
        color: #999;
        cursor: pointer;
        padding: 4px;

        &:hover {
          color: #666;
        }
      }
    }

    .password-form {
      .form-buttons {
        display: flex;
        gap: 12px;
        margin-top: 24px;

        .cancel-btn,
        .submit-btn {
          flex: 1;
          height: 44px;
          border-radius: 8px;
          font-size: 16px;
        }

        .cancel-btn {
          border-color: #ddd;
          color: #666;
        }

        .submit-btn {
          background-color: #3b82f6;
          border-color: #3b82f6;
        }
      }
    }
  }
}

:deep(.van-field) {
  padding: 12px 0;

  .van-field__label {
    color: #333;
    font-weight: 500;
    display: flex;
    align-items: center;
  }

  .van-field__control {
    color: #333;
    padding-right: 40px;
  }

  .van-field__right-icon {
    padding: 8px;
    min-width: 32px;
  }
}

:deep(.van-popup) {
  border-radius: 12px;
}
</style>
