<template>
  <FlexCol :padding="30">
    <Form 
      ref="formRef" 
      :model="formData" 
      :rules="rules"
      :labelFlex="2"
      :inputFlex="4"
    >
      <Field name="oldpassword" type="password" label="当前密码" placeholder="请输入当前密码" :maxlength="20" required />
      <Field name="newpassword" type="password" label="新密码" placeholder="请输入新密码" :maxlength="20" required />
      <Field name="confirmPassword" type="password" label="确认新密码" placeholder="请再次输入新密码" :maxlength="20" required />
      
      <text class="tips">
        密码建议：8-20位，包含字母和数字，不要使用过于简单的密码
      </text>
    </Form>
    <Height :height="40" />
    <Button type="primary" :loading="loading" @click="submitForm" >
      保存修改
    </Button>
  </FlexCol>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import userApi from '@/api/auth/UserApi';
import FlexCol from '@/components/layout/FlexCol.vue';
import Form from '@/components/form/Form.vue';
import Field from '@/components/form/Field.vue';
import Height from '@/components/layout/space/Height.vue';
import Button from '@/components/basic/Button.vue';
import type { Rules } from 'async-validator';

const formRef = ref<any>(null);
const loading = ref(false);

const formData = reactive({
  oldpassword: '',
  newpassword: '',
  confirmPassword: ''
});
const rules : Rules = {
  oldpassword: [
    { required: true, message: '请输入当前密码' },
    { min: 6, message: '密码长度至少6位' }
  ] ,
  newpassword: [
    { required: true, message: '请输入新密码' },
    { min: 6, message: '新密码长度至少6位' },
    {
      validator: (rule: any, value: string) => {
        // 密码强度校验：至少包含字母和数字
        const hasLetter = /[a-zA-Z]/.test(value);
        const hasNumber = /[0-9]/.test(value);
        return hasLetter && hasNumber;
      },
      message: '新密码必须包含字母和数字'
    }
  ] ,
  confirmPassword: [
    { required: true, message: '请确认新密码' },
    {
      validator: (rule: any, value: string) => {
        return value === formData.newpassword;
      },
      message: '两次输入的密码不一致'
    }
  ] 
};

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value?.validate();
  } catch (error) {
    console.error('表单验证失败:', error);  
    return;
  }
  
  loading.value = true;
  
  try {
    await userApi.updatePassword({
      oldpassword: formData.oldpassword,
      newpassword: formData.newpassword
    });
    uni.showToast({
      title: '密码修改成功',
      icon: 'success',
      duration: 2000
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 2000);
    
  } catch (error: any) {
    uni.showToast({
      title: error?.message || '密码修改失败，请稍后重试',
      icon: 'none',
      duration: 2000
    });
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.tips {
  font-size: 12px;
  color: #999999;
  margin: 16px 0;
  line-height: 1.5;
}
</style>