<template>
  <LoginLayout>
    <div class="outer-page 2xl:py-90px 2xl:px-130px lg:py-40px lg:px-60px pos-relative">
      <div class="tabs fs-24 flex c-999 select-none mb">
        <!-- <div :class="{ active: tabType === 'password' }" class="tab mr-60px cursor-pointer" @click="changeTab('password')">密码登录</div> -->
        <div :class="{ active: tabType === 'captcha' }" class="tab cursor-pointer" @click="changeTab('captcha')">验证码登录</div>
      </div>
      <!-- 注册form -->
      <a-form class="w-376px" ref="postFormRef" :model="postForm" :rules="postFormRules" :colon="false">
        <a-form-item class="mb-20 custom-form-item" ref="account" label="手机号/邮箱" name="account" placehplder="手机号码">
          <a-input v-model:value="postForm.account" placeholder="请输入注册手机号/邮箱" size="large" />
        </a-form-item>
        <a-form-item class="custom-form-item !mb-0" ref="password" label="密码" name="password" v-if="tabType === 'password'">
          <a-input-password v-model:value="postForm.password" placeholder="请输入密码" size="large" />
        </a-form-item>

        <a-form-item class="custom-form-item mb-0" label="验证码" name="captcha" v-if="tabType === 'captcha'">
          <a-input-group class="w-full flex justify-between">
            <a-input v-model:value="postForm.captcha" style="width: calc(100% - 134px)" placeholder="请输入验证码" :maxlength="6" size="large" />
            <a-button
              class="!w-120px !h-50px !text-14px !b-rd-6px !b-#8692a6"
              :disabled="seconds !== 0 || !postForm.account.length"
              @click="onSendCaptcha"
              size="large"
            >
              <span v-if="seconds === 0" class="c-666">获取验证码</span>
              <span v-else>{{ seconds }}s后重新发送</span>
            </a-button>
          </a-input-group>
        </a-form-item>
        <a-form-item class="custom-form-item error-form-item h-22px">
          <div class="flex justify-between mt-12px" v-if="tabType === 'password'">
            <!-- <a-checkbox class="custom-radio" v-model:checked="rememberPsw">记住密码</a-checkbox> -->
            <div class="flex items-center"><ToggleCircle class="mr-10px" v-model="rememberPsw" />记住密码</div>
            <router-link class="flex justify-end text-#0068FF underline" to="/forgetPwd">忘记密码?</router-link>
          </div></a-form-item
        >
        <a-form-item label="" class="mt-32px mb-22px">
          <a-button class="w-full !bg-#0068FF !b-rd-6px text-#fff !fw-700 !h-56px !hover:text-#fff" @click="onLogin" size="large">登录</a-button>
        </a-form-item>
        <div class="text-center c-666">还没有账号， <router-link to="/register" class="text-#0068FF underline">前往注册</router-link></div>
      </a-form>
    </div>
  </LoginLayout>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import useUserStore from 'Store/modules/user'
import type { UnwrapRef } from 'vue'
import type { Rule } from 'ant-design-vue/es/form'
import type { CaptchaData, LoginData } from 'Types/api'
import { apiSendCaptcha } from 'API/user'
import { validatePhoneOrEmail, validatePassword, genValidateTrue } from 'Utils/validate'

const postFormRef = ref()
const rememberPsw = ref(false)
// 当前注册阶段
let seconds = ref(0)
let tabType = ref('captcha')

interface IRegisterForm {
  account: string
  password: string
  captcha: string
}

const postForm: UnwrapRef<IRegisterForm> = reactive({
  account: '',
  password: '',
  captcha: '',
})
const postFormRules: Record<string, Rule[]> = {
  account: [{ required: true, validator: validatePhoneOrEmail, trigger: 'change' }],
  password: [{ required: true, validator: validatePassword, trigger: 'change' }],
  captcha: [{ required: true, message: '验证码未输入', trigger: 'change' }],
}

const changeTab = (type: string) => {
  tabType.value = type
  if (type === 'password') {
    const savedUser = localStorage.getItem('rememberedUser')
    let psw = ''
    if (savedUser) {
      const { password: savedPassword } = JSON.parse(savedUser)
      psw = savedPassword
    }
    postForm.password = psw || ''
  }
  postForm.captcha = ''
}
const onSendCaptcha = () => {
  postFormRef.value
    .validateFields(['account'])
    .then(async () => {
      const captcha: CaptchaData = {
        account: postForm.account,
        type: 's_login',
      }
      const data = await apiSendCaptcha(captcha)
      console.log(data)
      countSeconds()
    })
    .catch((error: Error) => {
      console.log('error', error)
    })
}

const countSeconds = () => {
  seconds.value = 60
  const timer = setInterval(() => {
    seconds.value--
    if (seconds.value === 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const onLogin = async () => {
  postFormRef.value.validate().then(async () => {
    const params: Partial<typeof postForm> = toRaw(postForm)
    if (tabType.value === 'password') {
      delete params.captcha
    } else {
      delete params.password
    }
    const userStore = useUserStore()
    await userStore.login(params as LoginData)
    if (rememberPsw.value) {
      localStorage.setItem(
        'rememberedUser',
        JSON.stringify({
          account: postForm.account,
          password: postForm.password,
          rememberPsw: true,
        })
      )
    } else {
      localStorage.removeItem('rememberedUser')
    }
  })
}

// 检查是否有保存的用户信息
const checkSavedUser = () => {
  const savedUser = localStorage.getItem('rememberedUser')
  if (savedUser) {
    const { account: savedUsername, password: savedPassword, rememberPsw: savedRememberMe } = JSON.parse(savedUser)
    postForm.account = savedUsername
    postForm.password = savedPassword
    rememberPsw.value = savedRememberMe
  }
}

// 在组件挂载时检查保存的用户信息
checkSavedUser()
</script>

<style scoped lang="less">
@import '@/assets/styles/variables.less';
.page {
  .tabs {
    display: flex;
    justify-content: center;
    margin-bottom: 70px;
    .tab {
      padding-bottom: 10px;
      border-bottom: 4px solid transparent;
      transition: 0.3s;
      &.active {
        border-bottom: 4px solid @color-new-primary;
        color: @color-new-primary;
        font-weight: 700;
      }
    }
  }

  .outer-page {
    background-color: #fff;
    border-radius: 18px;
  }
  ::v-deep(.ant-form) {
    .ant-form-item {
      &.custom-form-item {
        .ant-form-item-row {
          display: block !important;
          width: 376px !important;

          .ant-form-item-label {
            color: #000000;
            margin-bottom: 10px;
          }

          .ant-form-item-control {
            .ant-input-affix-wrapper {
              border-radius: 6px;
              width: 376px;
              border-color: #8692a6;
              input {
                height: 34px;
              }
            }
            input {
              width: 376px;
              border-radius: 6px;
              border-color: #8692a6;
              height: 50px;
              line-height: 50px;
              font-size: 16px !important;
              &.ant-input-status-error {
                border-color: #ff4d4f;
              }
            }
            .ant-form-item-explain-error {
              text-align: right;
            }
          }
        }
        &.error-form-item {
          .ant-form-item-explain-error {
            padding-right: 140px;
          }
        }
      }
      .custom-radio {
        .ant-checkbox {
          margin-right: 10px;
          &.ant-checkbox-checked {
            .ant-checkbox-inner {
              background-color: #0068ff;
              border-color: #0068ff;
            }
            &:after {
              border: 1px solid #0068ff;
            }
          }
          .ant-checkbox-inner {
            &:hover {
              border-color: #0068ff !important;
            }
          }
        }
      }
    }
  }
}
</style>
