<template>
  <page-layout class="">
    <template #header-right>
      <q-btn flat dense @click="save">保存</q-btn>
    </template>
    <q-form ref="formRef" class="q-pa-md bg-white">
      <q-input
        v-if="props.type == 'pwd' || store.user.has_pay_password"
        v-model="oldpwd"
        label="旧密码"
        :rules="[rules[0]]"
        type="password"
      />
      <q-input
        v-model="pwd"
        label="新密码"
        :rules="rules"
        type="password"
      />
      <q-input
        v-model="pwd2"
        label="确认密码"
        :rules="[...rules,sameRule]"
        type="password"
      />
    </q-form>
    <div class="q-pa-md text-right" v-if="props.type == 'pwd'">
      <q-btn color="primary" flat dense to="/my/forget">忘记密码？</q-btn>
    </div>
  </page-layout>
</template>
<script setup>
import { api } from "boot/axios";
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useSelfStore } from "stores/self";
import { useQuasar } from "quasar";
import { Rules } from "src/utils/tools";

const $q = useQuasar()
const route = useRoute();
const router = useRouter();
const store = useSelfStore();

const props = defineProps(["type"])
const oldpwd = ref("");
const pwd = ref("");
const pwd2 = ref("");

const rules = [
  Rules.required,
  Rules.password
];
function sameRule(val) {
  return val==pwd.value || '确认密码与新密码不一致'
}

const formRef = ref(null);

function save() {
  formRef.value.validate().then((success)=>{
    if(!success){
      return false
    }
    $q.loading.show()
    api[props.type == 'pwd'?'changePassword':'changePayPassword']({
      password_old: oldpwd.value,
      password: pwd.value,
      password_confirmation: pwd2.value
    }).then(res => {
      $q.notify({type: 'positive',message: res.message || '修改成功'})
      store.refresh().then(res => {
        router.back()
      })
    }).catch(e=>{
      $q.notify({type: 'negative',message: e.message})
    }).finally(()=>{
      $q.loading.hide()
    })
  })
}
</script>
