import { reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import router from '@/router';
import { t } from '@/support/helper';
import { resetPassword } from '@/api/auth/index';

export const useFind = () => {
  const params = ref({
    email: '',
    password: '',
    password_confirmation: '',
    code: ''
  });
  const loading = ref(false);

  //自定义校验规则
  // const validatePasswordConfirmation = (
  //   rule: any,
  //   value: any,
  //   callback: any
  // ) => {
  //   if (value === '') {
  //     callback(new Error('请再次输入密码'));
  //   } else if (value !== formName.password) {
  //     callback(new Error('两次密码不匹配'));
  //   } else {
  //     callback();
  //   }
  // };

  const rules = reactive({
    email: [
      {
        required: true,
        message: t('login.verify.email.required'),
        trigger: 'blur'
      },
      {
        type: 'email',
        message: t('login.verify.email.invalid'),
        trigger: 'blur'
      }
    ],
    code: [
      {
        required: true,
        message: '请输入验证码',
        trigger: 'blur'
      }
    ],
    password: [
      {
        required: true,
        message: t('login.verify.password.required'),
        trigger: 'blur'
      },
      {
        pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$/,
        message:
          '必须包含大小写字母和数字的组合，可以使用特殊字符，长度在6-20之间'
      }
    ],
    password_confirmation: [
      {
        required: true,
        message: '请再次输入密码',
        trigger: 'blur'
      }
    ]
  });

  const form = ref<FormInstance>();

  const submit = (loginForm: FormInstance | undefined) => {
    if (!loginForm) return;

    loginForm.validate(valid => {
      if (valid) {
        if (params.value.password !== params.value.password_confirmation)
          return ElMessage.warning('两次密码不匹配');
        loading.value = true;
        resetPassword(params.value)
          .then(res => {
            ElMessage.success(res.data.message);
            loading.value = false;
            router.back();
          })
          .catch(e => {
            loading.value = false;
          });
      } else {
        return false;
      }
    });
  };

  return {
    params,

    rules,

    loading,

    submit,

    form
  };
};
