<script setup lang="ts">
import type { DialogProps, FormInstance } from 'vant';
import { updateUserPassword } from '@/request/api/manage';

export interface UpdatePasswordProps {
  pid: string | number;
  title?: string;
  token?: string;
}

const { title = '重置密码', pid, token } = defineProps<UpdatePasswordProps>();
const emits = defineEmits<{
  complete: [];
  cancel: [];
}>();
const show = defineModel('show', { default: false });
const pending = ref(false);

const form = useTemplateRef<FormInstance>('form');
const model = ref({ password: '', again: '' });
const dialog = reactive<Partial<DialogProps>>({
  showCancelButton: true,
  className: 'reset-password-dialog',
  width: 480,
  beforeClose(action) {
    return action !== 'confirm' || onSubmit();
  },
});

const onCancel = () => {
  if (pending.value) return;
  form.value?.resetValidation();
  model.value.password = '';
  model.value.again = '';
  emits('cancel');
};
const onSubmit = async () => {
  try {
    await form.value?.validate();
    await updateUserPassword({ pid, ...model.value }, token).send(true);
    pending.value = true;
    show.value = false;
    await showConfirmDialog({ title: '请重新登录', showCancelButton: false });
    emits('complete');
    return true;
  } catch {
    return false;
  }
};

const validator: any = {
  required: { required: true, message: '请输入', trigger: 'onChange' },
  password: {
    trigger: ['onBlur', 'onSubmit'],
    pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{6,18}$/,
    message: '密码必须由大小写字母和数字三种组合，6-18 位字符',
    validateEmpty: false,
  },
  again: {
    trigger: ['onChange', 'onBlur', 'onSubmit'],
    validator(value: string) {
      return !model.value.password || model.value.password === value;
    },
    message: '两次输入的密码不同',
  },
};
</script>

<template>
  <van-dialog v-bind="dialog" v-model:show="show" :title @closed="onCancel()">
    <van-form ref="form" @submit="onSubmit" class="py-4">
      <van-cell-group inset>
        <van-field v-model="model.password" type="password" name="password" label="新密码" placeholder="请输入新密码" :rules="[validator.required, validator.password]" />
        <van-field
          v-model="model.again"
          type="password"
          name="again"
          label="确认密码"
          placeholder="再次输入新密码"
          :rules="[validator.required, validator.again, validator.password]"
        />
      </van-cell-group>
    </van-form>
  </van-dialog>
</template>

<style scoped lang="scss"></style>
