<template>
  <div>
    <h3>修改密码</h3>
    <v-divider class="mb-4"></v-divider>
    <div class="login-user mb-4">当前登录账号： <span style="color: var(--v-primary-base);">{{ userInfo.phone }}</span></div>
    <div style="width: 300px;">
      <PhonePage ref="phoneRef"></PhonePage>
      <v-form ref="passwordRef">
        <v-text-field
          v-model="query.password"
          placeholder="请输入密码" 
          variant="outlined" 
          density="compact"
          color="#00897B"
          prepend-inner-icon="mdi-lock-outline" 
          :append-inner-icon="passwordType ? 'mdi-eye-outline' : 'mdi-eye-off-outline'"
          :type="passwordType ? 'text' : 'password'"
          :rules="[v=> !!v || '请填写密码']"
          @click:append-inner="passwordType = !passwordType"
        ></v-text-field>
        <v-text-field
          v-model="query.checkPassword"
          placeholder="请再次输入密码" 
          variant="outlined" 
          density="compact"
          color="#00897B"
          prepend-inner-icon="mdi-lock-outline" 
          :append-inner-icon="show ? 'mdi-eye-outline' : 'mdi-eye-off-outline'"
          :type="show ? 'text' : 'password'"
          :rules="[v=> !!v || '请再次输入密码', passwordCheck]"
          @click:append-inner="show = !show"
        ></v-text-field>
      </v-form>
      <div class="text-center">
        <v-btn class="buttons" color="primary" @click="handleSubmit" :loading="loading">确认密码</v-btn>
      </div>
    </div>
  </div>
</template>

<script setup name="editPassword">
import PhonePage from '@/components/VerificationCode'
import { updatePassword } from '@/api/common/index'
import { ref, reactive, computed } from 'vue'

const phoneRef = ref()
const passwordRef = ref()
const passwordType = ref(false)
const show = ref(false)
const loading = ref(false)
const query = reactive({
  password: '',
  checkPassword: ''
})
const passwordCheck = computed(() => {
  return query.checkPassword === query.password || '两次密码输入不一致'
})

// 当前登录的用户信息
const userInfo = JSON.parse(localStorage.getItem('userInfo'))

const handleSubmit = async () => {
  const { valid: phoneValid } = await phoneRef.value.phoneForm.validate()
  const { valid: passValid} = await passwordRef.value.validate()
  if (!phoneValid || !passValid) return
  loading.value = true
  try {
    await updatePassword({ password: query.password, code: phoneRef.value.loginData.code })
    console.log('success')
  } catch (error) {
    console.log(error, 'error')
    alert(error.msg)
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
h3 {
  font-size: 20px;
  text-align: left;
  font-weight: 600;
  padding-bottom: 25px;
}
.login-user {
  color: var(--default-text);
  font-weight: 600;
}
</style>