<template>
  <div class="login-wrapper">
    <div class="login-main">
      <ele-card shadow="always" class="login-card">
        <div class="login-cover">
          <h1 class="login-title">啤啤猩球</h1>
          <h4 class="login-subtitle"
            >高效制作专属酒单·就在BeerApe</h4
          >
        </div>
        <div class="login-body">
          <div class="login-header">
            <ele-text type="heading" class="login-heading"> 用户登录 </ele-text>
            <ele-segmented
              v-model="tabActive"
              :items="[{ label: '手机号登录', value: 2 }]"
              class="login-segmented"
              @change="handleTabChange"
            />
          </div>
          <!--   手机号登录       -->
          <el-form
            ref="formRef"
            size="large"
            :model="form"
            :rules="rules"
            @keyup.enter="submit"
            @submit.prevent=""
          >
            <el-form-item prop="phoneNumber">
              <el-input
                clearable
                v-model="form.phoneNumber"
                placeholder="请输入手机号"
                :prefix-icon="Iphone"
              />
            </el-form-item>
            <el-form-item prop="code">
              <div class="login-captcha-group">
                <el-input
                  clearable
                  v-model="form.code"
                  placeholder="请输入短信验证码"
                  :prefix-icon="ProtectOutlined"
                />
                <el-button
                  class="sms-code-btn"
                  :disabled="countdown > 0 || smsLoading"
                  :loading="smsLoading"
                  @click="getSmsCode"
                >
                  {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button
                size="large"
                type="primary"
                :loading="loading"
                class="login-btn"
                @click="submit"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
          <!--   手机号登录完      -->
        </div>
      </ele-card>
    </div>
    <PageFooter style="padding-top: 0" />
  </div>
</template>

<script setup>
  import { ref, reactive, unref, onUnmounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { EleMessage } from 'ele-admin-plus';
  import { ProtectOutlined } from '@/components/icons';
  import { Iphone } from '@element-plus/icons-vue';
  import { getToken } from '@/utils/token-util';
  import { usePageTab } from '@/utils/use-page-tab';
  import { SmsLogin, getSmsCaptcha } from '@/api/login';
  import PageFooter from '@/layout/components/page-footer.vue';

  const { currentRoute } = useRouter();
  const { goHomeRoute, cleanPageTabs } = usePageTab();

  /** 页签选中 */
  const tabActive = ref(1);

  /** 表单 */
  const formRef = ref(null);

  /** 加载状态 */
  const loading = ref(false);

  /** 短信验证码加载状态 */
  const smsLoading = ref(false);

  /** 倒计时 */
  const countdown = ref(0);
  let timer = null;

  /** 表单数据 */
  const form = reactive({
    phoneNumber: '',
    code: '',
    uuid: '',
    remember: true
  });

  /** 表单验证规则 */
  const rules = reactive({
    phoneNumber: [
      {
        required: true,
        message: '请输入手机号',
        type: 'string',
        trigger: 'blur'
      },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入正确的手机号格式',
        trigger: 'blur'
      }
    ],
    code: [
      {
        required: true,
        message: '请输入短信验证码',
        type: 'string',
        trigger: 'blur'
      },
      {
        pattern: /^\d{6}$/,
        message: '请输入6位数字验证码',
        trigger: 'blur'
      }
    ]
  });

  // 获取短信验证码
  const getSmsCode = async () => {
    if (!form.phoneNumber) {
      EleMessage.warning('请先输入手机号');
      return;
    }

    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(form.phoneNumber)) {
      EleMessage.warning('请输入正确的手机号格式');
      return;
    }

    // 防止重复点击
    if (smsLoading.value || countdown.value > 0) {
      return;
    }

    smsLoading.value = true;
    try {
      const res = await getSmsCaptcha({ phoneNumber: form.phoneNumber });
      if (res.data && res.data.code === 200) {
        EleMessage.success('短信验证码已发送');
        form.uuid = res.data.uuid;
        countdown.value = 60;
        timer = setInterval(() => {
          if (countdown.value > 0) {
            countdown.value--;
          } else {
            clearInterval(timer);
          }
        }, 1000);
      } else {
        const errorMsg = res.data?.msg || '获取短信验证码失败';
        EleMessage.error(errorMsg);
      }
    } catch (error) {
      const errorMsg =
        error.response?.data?.msg || error.message || '获取短信验证码失败';
      EleMessage.error(errorMsg);
    } finally {
      smsLoading.value = false;
    }
  };

  onUnmounted(() => {
    if (timer) {
      clearInterval(timer);
    }
  });

  /** 提交 */
  const submit = () => {
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      loading.value = true;
      SmsLogin(form)
        .then((msg) => {
          EleMessage.success({ message: msg, plain: true });
          cleanPageTabs();
          goHome();
        })
        .catch((e) => {
          loading.value = false;
          EleMessage.error({ message: e.message, plain: true });
        });
    });
  };

  /** 跳转到首页 */
  const goHome = () => {
    const { query } = unref(currentRoute);
    goHomeRoute(query.from);
  };

  // 如果已登录直接进入首页
  if (getToken()) {
    goHome();
  }
</script>

<style lang="scss" scoped>
  .login-wrapper {
    min-height: 100vh;
    min-height: 100dvh;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    background-image: url('@/assets/login-bg.png');
    background-repeat: no-repeat;
    background-size: 100% 100%;

    .login-main {
      flex: auto;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
      padding: 20px;
    }

    .login-card {
      width: 920px;
      max-width: 100%;
      overflow: hidden;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
      border-radius: 12px;

      :deep(.ele-card-body) {
        display: flex;
        padding: 0;
        height: 480px;
      }
    }
  }

  .login-cover {
    flex: 1;
    padding: 32px 8px;
    box-sizing: border-box;
    background-color: #1681fd;
    background-image: url('@/assets/login-img.png');
    background-repeat: no-repeat;
    background-position: bottom;
    background-size: contain;
    text-align: center;
    border-radius: 12px 0 0 12px;
  }

  .login-body {
    width: 400px;
    flex-shrink: 0;
    padding: 40px 48px 32px 48px;
    box-sizing: border-box;
    background: #ffffff;
    border-radius: 0 12px 12px 0;

    :deep(.el-checkbox) {
      height: auto;

      .el-checkbox__label {
        color: inherit;
      }
    }

    :deep(.el-input__prefix-inner > .el-icon) {
      margin-right: 12px;
      transform: scale(1.16);
    }

    :deep(.el-input) {
      .el-input__wrapper {
        border-radius: 8px;
        transition: all 0.3s ease;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

        &:hover {
          border-color: #1681fd;
          box-shadow: 0 2px 8px rgba(22, 129, 253, 0.15);
        }

        &.is-focus {
          border-color: #1681fd;
          box-shadow: 0 2px 8px rgba(22, 129, 253, 0.2);
        }
      }
    }

    :deep(.el-form-item) {
      margin-bottom: 20px;
    }

    .login-header {
      text-align: center;
      margin-bottom: 28px;

      .login-heading {
        font-size: 26px;
        font-weight: 600;
        color: #333;
        margin-bottom: 20px;
        letter-spacing: 0.5px;
      }

      .login-segmented {
        :deep(.ele-segmented) {
          background: #f7f8fa;
          border-radius: 8px;
          padding: 3px;

          .ele-segmented-item {
            border-radius: 6px;
            font-weight: 500;
            transition: all 0.3s ease;

            &.is-active {
              background: #1681fd;
              color: white;
              box-shadow: 0 1px 4px rgba(22, 129, 253, 0.3);
            }
          }
        }
      }
    }

    .login-btn {
      width: 100%;
      height: 44px;
      border-radius: 8px;
      background: #1681fd;
      border: none;
      color: white;
      font-weight: 600;
      font-size: 16px;
      transition: all 0.3s ease;

      &:hover:not(:disabled) {
        background: #0d5ef7;
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(22, 129, 253, 0.3);
      }

      &:active:not(:disabled) {
        transform: translateY(0);
      }

      &:disabled {
        background: #d1d5db;
        cursor: not-allowed;
        transform: none;
      }
    }
  }

  /* 短信验证码 */
  .login-captcha-group {
    width: 100%;
    display: flex;
    align-items: center;
    gap: 10px;

    :deep(.el-input) {
      flex: 1;
    }

    .sms-code-btn {
      flex-shrink: 0;
      height: 40px;
      min-width: 110px;
      border-radius: 8px;
      background: #1681fd;
      border: none;
      color: white;
      font-weight: 500;
      font-size: 14px;
      transition: all 0.3s ease;

      &:hover:not(:disabled) {
        background: #0d5ef7;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(22, 129, 253, 0.3);
      }

      &:active:not(:disabled) {
        transform: translateY(0);
      }

      &:disabled {
        background: #d1d5db;
        cursor: not-allowed;
        transform: none;
      }
    }
  }

  /* 标题 */
  .login-title {
    color: rgba(255, 255, 255, 0.98);
    font-size: 28px;
    margin: 0 0 6px 0;
    font-weight: 500;
    letter-spacing: 1.2px;
  }

  .login-subtitle {
    color: rgba(255, 255, 255, 0.8);
    font-size: 16px;
    margin: 0;
    font-weight: 400;
    letter-spacing: 3px;
  }

  /* 小屏幕适应 */
  @media screen and (max-width: 680px) {
    .login-wrapper {
      background: #fff;

      .login-main {
        padding: 0;
        display: block;
      }

      .login-card {
        width: 100%;
        background: none;
        box-shadow: none;
        border-radius: 0;

        :deep(.ele-card-body) {
          display: block;
          height: auto;
        }
      }
    }

    .login-cover {
      padding: 20px 12px 100px 12px;
      background-size: auto 100px;
      border-radius: 0;
    }

    .login-body {
      width: 100%;
      padding: 32px 24px;
      border-radius: 0;

      .login-header {
        margin-bottom: 24px;

        .login-heading {
          font-size: 24px;
        }
      }

      .login-captcha-group {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;

        .sms-code-btn {
          width: 100%;
          min-width: auto;
          height: 44px;
        }
      }
    }
  }
</style>

<style lang="scss">
  html.dark .login-wrapper {
    background: #000;

    .login-card {
      background: rgba(20, 20, 20, 0.95);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
    }

    .login-body {
      background: rgba(20, 20, 20, 0.95);

      .login-heading {
        color: #ffffff;
      }

      .login-segmented {
        :deep(.ele-segmented) {
          background: rgba(255, 255, 255, 0.1);

          .ele-segmented-item {
            color: rgba(255, 255, 255, 0.8);

            &.is-active {
              background: #1681fd;
              color: white;
            }
          }
        }
      }

      :deep(.el-input) {
        .el-input__wrapper {
          background: rgba(30, 30, 30, 0.8);
          border-color: rgba(255, 255, 255, 0.2);

          &:hover {
            border-color: #1681fd;
          }

          &.is-focus {
            border-color: #1681fd;
          }
        }

        .el-input__inner {
          color: #ffffff;
        }
      }
    }
  }
</style>
