<!-- eslint-disable vue/no-duplicate-attributes -->
<template>
  <div class="flex items-center w-400 h-100%">
    <div class="w-full bg-#fff rounded-16px px-40px py-32px flex flex-col items-center">
      <div class="flex items-center mb-24px w-full cursor-pointer" @click="onBack">
        <icon-left size="24" class="mr-4px color-#000" />
        <span class="color-#000 text-20px font-500 lh-28px font-family-medium">{{
          isResetPassword ? '重置密码' : '手机注册'
        }}</span>
      </div>
      <Form ref="formRef" :model="formData" :rules="formRules" auto-label-width class="w-320 form-wrap">
        <FormItem name="mobile">
          <Input
            v-model:value="formData.mobile"
            placeholder="请输入手机号"
            allowClear
            :maxlength="11"
            @change="clearErrorMsg"
          />
        </FormItem>
        <FormItem name="password" class="password-form-item">
          <Input.Password v-model:value="formData.password" placeholder="新密码" @change="clearErrorMsg">
            <template #iconRender="visible">
              <img :src="visible ? icon2 : icon1" width="20" height="20" class="cursor-pointer" />
            </template>
          </Input.Password>
        </FormItem>
        <FormItem name="confirm_password" class="password-form-item">
          <Input.Password v-model:value="formData.confirm_password" placeholder="密码确认" @change="clearErrorMsg">
            <template #iconRender="visible">
              <img :src="visible ? icon2 : icon1" width="20" height="20" class="cursor-pointer" />
            </template>
          </Input.Password>
        </FormItem>
        <FormItem name="captcha" class="captcha-form-item">
          <Input v-model:value="formData.captcha" placeholder="请输入验证码" :maxlength="6" @change="clearErrorMsg">
            <template #suffix>
              <div class="w-79px flex justify-center whitespace-nowrap">
                <span
                  class="color-#939499 font-family-regular text-16px font-400 lh-24px cursor-not-allowed"
                  :class="{
                    '!color-#6D4CFE': (isPassPassword && isLegalMobile) || countdown > 0,
                    '!cursor-pointer': canGetCaptcha,
                  }"
                  @click="getCode"
                  >{{ countdown > 0 ? `${countdown}s` : hasGetCode ? '重新发送' : '发送验证码' }}</span
                >
              </div>
            </template>
          </Input>
          <p class="color-#F64B31 text-12px font-400 lh-20px font-family-regular" v-show="errMsg">
            {{ errMsg }}
          </p>
        </FormItem>

        <FormItem class="mt-52px">
          <div class="text-12px flex justify-center items-center mb-16px">
            <Checkbox v-model:checked="hasCheck" class="mr-8px"></Checkbox>
            <span class="text-12px color-#737478 font-400 lh-20px font-family-regular"
              >登录即代表同意<span class="color-#6D4CFE"> 用户协议 </span>和<span class="color-#6D4CFE">
                隐私政策</span
              ></span
            >
          </div>
          <Button
            type="primary"
            class="w-full h-48 mb-8px !text-16px !font-500 !rounded-8px btn-login"
            :class="disabledSubmitBtn ? 'cursor-no-drop' : 'cursor-pointer'"
            :disabled="disabledSubmitBtn"
            @click="handleSubmit"
          >
            {{ isResetPassword ? '重置' : '注册' }}
          </Button>
        </FormItem>
      </Form>
    </div>
  </div>

  <PuzzleVerification
    :show="isVerificationVisible"
    @submit="handleVerificationSubmit"
    @cancel="isVerificationVisible = false"
  />
  <SelectAccountModal ref="selectAccountModalRef" :mobileNumber="mobileNumber" :accounts="accounts" />
</template>

<script setup lang="js">
import { Button, Checkbox, Form, FormItem, Input, message, Tabs, Typography } from 'ant-design-vue';
import PuzzleVerification from '../PuzzleVerification.vue';
import SelectAccountModal from '../select-account-modal/index.vue';
import { postClearRateLimiter } from '@/api/all/common';
import {
  fetchProfileInfo,
  postForgetPassword,
  postForgetPasswordCaptcha,
  postRegister,
  postRegisterCaptcha,
} from '@/api/all/login';
import { joinEnterpriseByInviteCode } from '@/api/all';
import { computed, onUnmounted, ref } from 'vue';
import { useUserStore } from '@/stores';
import { useEnterpriseStore } from '@/stores/modules/enterprise';
import { handleUserLogin } from '@/utils/user';
import { useRoute } from 'vue-router';

import icon1 from '@/assets/img/login/icon-close.png';
import icon2 from '@/assets/img/login/icon-open.png';

const { Link } = Typography;
const { TabPane } = Tabs;

const setPageType = inject('setPageType');
const pageType = inject('pageType');

const formRef = ref();
const route = useRoute();
const userStore = useUserStore();
const enterpriseStore = useEnterpriseStore();
const countdown = ref(0);
let timer = ref();
const isLogin = ref(true);
const isVerificationVisible = ref(false);
const hasGetCode = ref(false);
const submitting = ref(false);
const hasCheck = ref(false);
const mobileNumber = ref('');
const selectAccountModalRef = ref(null);
const accounts = ref([]);
const isLegalMobile = ref(false);
const errMsg = ref('');

const formData = ref({
  mobile: '',
  captcha: '',
  password: '',
  confirm_password: '',
});

// 表单校验规则
const formRules = {
  mobile: [
    {
      required: true,
      validator: (_rule, value) => {
        if (!value) {
          isLegalMobile.value = false;
        }
        if (value && !/^1[3-9]\d{9}$/.test(value)) {
          isLegalMobile.value = false;
          return Promise.reject('手机号格式不正确');
        } else {
          isLegalMobile.value = true;
          return Promise.resolve();
        }
      },
      trigger: ['blur'],
    },
  ],
  password: [
    {
      required: true,
      validator: (_rule, value) => {
        // if (!value) {
        //   return Promise.reject('请输入新密码');
        // }
        // if (value.length < 6) {
        //   return Promise.reject('密码长度不能小于6位');
        // }
        if (formData.value.confirm_password) {
          formRef.value.validateFields('confirm_password');
        }
        return Promise.resolve();
      },
      trigger: ['blur'],
    },
  ],
  confirm_password: [
    {
      required: true,
      validator: (_rule, value) => {
        // if (!value) {
        //   return Promise.reject('请输入密码确认');
        // }
        // if (value.length < 6) {
        //   return Promise.reject('密码长度不能小于6位');
        // }
        if (value !== formData.value.password) {
          return Promise.reject('确认密码与设置的密码不同');
        }
        return Promise.resolve();
      },
      trigger: ['blur'],
    },
  ],
  captcha: [
    // {
    //   required: true,
    //   validator: (_rule, value) => {
    //     // if (!value) {
    //     //   return Promise.reject('请输入验证码');
    //     // }
    //     if (value && !/^\d{6}$/.test(value)) {
    //       return Promise.reject('验证码必须是6位数字');
    //     } else {
    //       return Promise.resolve();
    //     }
    //   },
    //   trigger: ['blur'],
    // },
  ],
};

// 重置密码
const isResetPassword = computed(() => {
  return pageType.value === 'resetPasswordForm';
});

const isPassPassword = computed(() => {
  return (
    formData.value.confirm_password &&
    formData.value.password &&
    formData.value.confirm_password === formData.value.password
  );
});
const canGetCaptcha = computed(() => {
  return isLegalMobile.value && countdown.value === 0 && isPassPassword.value;
});

const disabledSubmitBtn = computed(() => {
  return !isPassPassword.value || !hasCheck.value || !isLegalMobile.value || !formData.value.password.trim();
});

const clearErrorMsg = () => {
  errMsg.value = '';
};

const validateField = (field) => {
  formRef.value.validateFields(field);
};

const clearError = (field) => {
  formRef.value.clearValidate(field);
};

const getCode = async () => {
  if (!canGetCaptcha.value) {
    if (!formData.value.mobile.trim()) {
      formRef.value.validateFields('mobile');
      return;
    }
    return;
  }

  formRef.value.validateFields('mobile').then(() => {
    getCaptcha();
  });
};

const getCaptcha = async () => {
  try {
    const fn = isResetPassword.value ? postForgetPasswordCaptcha : postRegisterCaptcha;
    const { code, message: msg } = await fn({ mobile: formData.value.mobile });
    if (code === 200) {
      startCountdown();
      message.success(msg);
    }
  } catch (error) {
    // 重置倒计时
    countdown.value = 0;
    clearInterval(timer.value);

    if (error.status === 429) {
      isVerificationVisible.value = true;
    }
  }
};

// 验证码验证通过后
const handleVerificationSubmit = async () => {
  isVerificationVisible.value = false;
  await postClearRateLimiter();
  getCaptcha();
};

// 获取用户信息
const getProfileInfo = async () => {
  const { code, data } = await fetchProfileInfo();
  if (code === 200) {
    const enterprises = data['enterprises'];
    mobileNumber.value = data['mobile'];
    accounts.value = enterprises;

    if (enterprises.length > 0) {
      enterpriseStore.setEnterpriseInfo(data.enterprises[0]);
      if (enterprises.length === 1) {
        setTimeout(() => {
          handleUserLogin();
        }, 1500);
      } else {
        selectAccountModalRef.value.open();
      }
    }
  }
};

// 提交表单
const handleSubmit = async () => {
  if (disabledSubmitBtn.value) return;

  try {
    // 校验所有字段
    await formRef.value.validate();

    if (!hasCheck.value) {
      message.error('请先勾选同意用户协议');
      return;
    }

    submitting.value = true;

    const _fn = isResetPassword.value ? postForgetPassword : postRegister;
    const { code, data, message: errorInfo } = await _fn(formData.value);

    if (code === 10001) {
      errMsg.value = errorInfo;
      return;
    }

    if (code === 200) {
      message.success(isResetPassword.value ? '重置成功' : '注册成功');
      // 注册成功后跳转登录页
      if (!isResetPassword.value) {
        setTimeout(() => {
          setPageType('loginForm');
        }, 1500);
        return;
      }
      ;

      userStore.setToken(data.access_token);

      const { invite_code } = route.query;
      if (invite_code) {
        const { code } = await joinEnterpriseByInviteCode(invite_code);
        if (code === 200) {
          message.success('加入企业成功');
        }
      }

      getProfileInfo();
    }
  } finally {
    submitting.value = false;
  }
};

const onBack = () => {
  setPageType('loginForm');
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60;
  hasGetCode.value = true;
  timer.value = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer.value);
      timer.value = null;
    }
  }, 1000);
};

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
</script>

<style scoped lang="scss">
@import './style.scss';
</style>
