import type { ValidationRule } from 'ant-design-vue/lib/form/Form';
import type { RuleObject } from 'ant-design-vue/lib/form/interface';
import { ref, computed, unref, Ref } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';

export enum LoginStateEnum {
  LOGIN,
  REGISTER,
  RESET_PASSWORD,
  MOBILE,
  QR_CODE,
}

const currentState = ref(LoginStateEnum.LOGIN);

export function useLoginState() {
  function setLoginState(state: LoginStateEnum) {
    currentState.value = state;
  }

  const getLoginState = computed(() => currentState.value);

  function handleBackLogin() {
    setLoginState(LoginStateEnum.LOGIN);
  }

  return { setLoginState, getLoginState, handleBackLogin };
}

export function useFormValid<T extends Object = any>(formRef: Ref<any>) {
  async function validForm() {
    const form = unref(formRef);
    if (!form) return;
    const data = await form.validate();
    return data as T;
  }

  return { validForm };
}
// formData?: Recordable
export function useFormRules() {
  const { t } = useI18n();

  const getAccountFormRule = computed(() => createRule(t('sys.login.accountPlaceholder')));
  const getPasswordFormRule = computed(() => {
    return [
      ...createRule(t('sys.login.passwordPlaceholder')),
      { validator: validatePassword(), trigger: 'change' },
    ];
  });
  const getRegisterPasswordFormRule = computed(() => {
    return [
      ...createRule(t('sys.login.passwordPlaceholder')),
      { validator: registerValidatePassword(), trigger: 'change' },
    ];
  });
  const getSmsFormRule = computed(() => createRule(t('sys.login.smsPlaceholder')));
  // const getMobileFormRule = computed(() => createRule(t('sys.login.mobilePlaceholder')));
  // console.log('formData', formData);
  const getMobileFormRule = computed(() => {
    return [
      ...createRule(t('sys.login.mobilePlaceholder')),
      { validator: validateMobile(), trigger: 'change' },
    ];
  });

  // const validatePolicy = async (_: RuleObject, value: boolean) => {
  //   return !value ? Promise.reject(t('sys.login.policyPlaceholder')) : Promise.resolve();
  // };
  const validateMobile = () => {
    return async (_: RuleObject, value: string) => {
      const reg = new RegExp(/^1\d{10}$/);
      if (!reg.test(value)) {
        if (value) {
          return Promise.reject(t('sys.login.mobileFormat'));
        }
      }
      return Promise.resolve();
    };
  };
  const validatePassword = () => {
    return async (_: RuleObject, value: string) => {
      const reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g');
      if (reg.test(value)) {
        return Promise.reject(t('sys.login.passwordFormat'));
      }
      return Promise.resolve();
    };
  };
  const registerValidatePassword = () => {
    return async (_: RuleObject, value: string) => {
      // const reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g');
      const reg = /^(?=.*[0-9\!@#\$%\^&\*])(?=.*[a-zA-Z]).{8,16}$/;
      if (!reg.test(value) && value?.length) {
        return Promise.reject('请输入8-16位数字和字母组合密码');
      }
      return Promise.resolve();
    };
  };
  // const validateConfirmPassword = (password: string) => {
  //   return async (_: RuleObject, value: string) => {
  //     if (!value) {
  //       return Promise.reject(t('sys.login.passwordPlaceholder'));
  //     }
  //     if (value !== password) {
  //       return Promise.reject(t('sys.login.diffPwd'));
  //     }
  //     return Promise.resolve();
  //   };
  // };

  const getFormRules = computed((): { [k: string]: ValidationRule | ValidationRule[] } => {
    const accountFormRule = unref(getAccountFormRule);
    const passwordFormRule = unref(getPasswordFormRule);
    const registerPasswordFormRule = unref(getRegisterPasswordFormRule);
    const smsFormRule = unref(getSmsFormRule);
    const mobileFormRule = unref(getMobileFormRule);

    const mobileRule = {
      code: smsFormRule,
    };
    switch (unref(currentState)) {
      // register form rules
      case LoginStateEnum.REGISTER:
        return {
          userName: mobileFormRule,
          userPassword: [...registerPasswordFormRule],
          ...mobileRule,
        };

      // // reset password form rules
      // case LoginStateEnum.RESET_PASSWORD:
      //   return {
      //     account: accountFormRule,
      //     ...mobileRule,
      //   };

      // // mobile form rules
      // case LoginStateEnum.MOBILE:
      //   return mobileRule;

      // login form rules
      default:
        return {
          account: accountFormRule,
          password: passwordFormRule,
        };
    }
  });
  return { getFormRules };
}

function createRule(message: string) {
  return [
    {
      required: true,
      message,
      trigger: 'change',
    },
  ];
}
