<template>
  <div class="login-content" :style="{ 'background-image': 'url(' + login.config.background + ')' }">
    <el-row>
      <el-col :xs="0" :sm="0" :md="13" :lg="14" :xl="14"></el-col>
      <el-col class="main" :xs="24" :sm="24" :md="11" :lg="10" :xl="10">
        <transition name="el-zoom-in-center">
          <!-- 使用账号密码登录 -->
          <div v-if="login.type == 'input'" class="login-wrap sa-flex sa-flex-center sa-flex-1">
            <div class="admin-name">
              <div>
                <div class="sa-line-1">{{ t('modules.auth.welcomeTo', { appName }) }}</div>
                <div class="admin-welcome">{{ t('modules.auth.niceToSeeYou') }}</div>
              </div>
            </div>
            <el-form :model="form.data" :rules="form.rules" label-position="left" ref="formRef" label-width="0">
              <el-form-item prop="account">
                <el-input :class="form.data.account ? 'is-focus' : ''" v-model="form.data.account">
                  <template #prefix>
                    <div class="label">{{ t('modules.auth.account') }}</div>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="pwd">
                <el-input :class="form.data.pwd ? 'is-focus' : ''" v-model="form.data.pwd"
                  :type="showPwd ? 'password' : 'text'" autocomplete="new-password">
                  <template #prefix>
                    <div class="label">{{ t('modules.auth.password') }}</div>
                  </template>
                  <template #suffix>
                    <span v-if="showPwd" @click="showPwd = false">
                      <sa-svg name="sa-password-hide" size="24"></sa-svg>
                    </span>
                    <span v-if="!showPwd" @click="showPwd = true">
                      <sa-svg name="sa-password-show" size="24"></sa-svg>
                    </span>
                  </template>
                </el-input>
              </el-form-item>

              <div>
                <el-checkbox v-model="login.last.rememberMe" @change="changeRememberMe"
                  :label="t('modules.auth.rememberMe')"></el-checkbox>
              </div>
              <el-button type="primary" :loading="loginLoading" @click="accountLogin">
                {{ t('modules.auth.login') }}
              </el-button>
            </el-form>
          </div>
          <!-- 有记住的用户 -->
          <div v-else-if="login.type == 'rememberMe'" class="login-wrap sa-flex sa-flex-center sa-flex-1">
            <div class="admin-name sa-flex sa-row-center">
              <sa-image :url="login.last.info.avatar" size="80" radius="40"></sa-image>
            </div>
            <el-form :model="form.data" :rules="form.rules" label-position="left" ref="formRef" label-width="0">
              <el-form-item prop="account">
                <div class="sa-flex-1 sa-flex sa-row-center">
                  {{ login.last.info.nickname }}
                </div>
              </el-form-item>
              <el-form-item prop="pwd">
                <el-input :class="form.data.pwd ? 'is-focus' : ''" v-model="form.data.pwd"
                  :type="showPwd ? 'password' : 'text'" autocomplete="new-password">
                  <template #prefix>
                    <div class="label">{{ t('modules.auth.password') }}</div>
                  </template>
                  <template #suffix>
                    <span v-if="showPwd" @click="showPwd = false">
                      <sa-svg name="sa-password-hide" size="24"></sa-svg>
                    </span>
                    <span v-if="!showPwd" @click="showPwd = true">
                      <sa-svg name="sa-password-show" size="24"></sa-svg>
                    </span>
                  </template>
                </el-input>
              </el-form-item>

              <el-button type="primary" :loading="loginLoading" @click="accountLogin">登录
              </el-button>
              <el-button @click="changeLoginType('input')"> 使用其他账号登录 </el-button>
            </el-form>
          </div>
        </transition>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { reactive, ref, unref, computed, onBeforeMount, onMounted, onUnmounted } from 'vue';

import router from '@/sheep/router';
import { useRoute } from 'vue-router';
import adminApi from '@/sheep/local-data/admin';
import storage from '@/sheep/utils/storage';
import sheep from '@/sheep';
import { checkUrl } from '@/sheep/utils/checkUrlSuffix';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const accountStore = sheep.$store('account');
const appStore = sheep.$store('app');
const routeQuery = useRoute().query;
if (routeQuery.token) {
  accountStore.setToken(`${routeQuery.token}`);
}
const appName = computed(() => appStore.info.name);

const showPwd = ref(true);

const loginLoading = ref(false);
const formRef = ref(null);

const form = reactive({
  data: {
    account: '',
    pwd: '',
  },
  get rules() {
    return {
      account: [{ required: true, message: t('modules.auth.accountRequired'), trigger: 'blur' }],
      pwd: [{ required: true, message: t('modules.auth.passwordRequired'), trigger: 'blur' }],
    };
  },
});

// 登录
const accountLogin = async () => {
  // 表单验证
  unref(formRef).validate(async (valid) => {
    if (!valid) return;
    loginLoading.value = true;
    try {
      let submit = form.data;
      const { code } = await accountStore.login(submit);
      if (code == '200') {
        ElMessage.success(t('modules.auth.loginSuccess'));
        storage.set('lastLogin', login.last);
        await appStore.appLoad();
        router.push('/');
      }
    } catch (error) {
      console.error('登录失败:', error);
      // 错误信息通常由 store 或 request 拦截器处理，这里只记录日志
    } finally {
      loginLoading.value = false;
    }
  });
};

const login = reactive({
  config: {
    background: '',
  },
  type: 'input',
  last: {},
});

// 初始化登陆表单
function checkLastLogin() {
  login.last = storage.get('lastLogin', { rememberMe: false });
  if (login.last.rememberMe) {
    login.type = 'rememberMe';
    form.data.account = login.last.info.account;
  }
}

function changeLoginType(type) {
  login.type = type;
  if (type == 'input') {
    form.data.account = '';
    form.data.pwd = '';
    initLogin();
  }
}

function changeRememberMe(e) {
  login.last.rememberMe = e;
}

onBeforeMount(async () => {
  // 检测登录态
  if (accountStore.isLogin) {
    await appStore.appLoad();
    router.push('/');
  } else {
    initLogin();
    checkLastLogin();
  }
});

onMounted(() => {
  document.addEventListener('keyup', enterKey);
});

onUnmounted(() => {
  document.removeEventListener('keyup', enterKey);
});

function enterKey(event) {
  const code = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
  if (code == 13) {
    accountLogin();
  }
}

async function initLogin() {
  const { data } = adminApi.loginConfig();
  login.config = data;
  login.config.background = login.config.background;
}
</script>
<style lang="scss">
.login-content {
  .el-form {
    width: 100%;

    .el-button {
      width: 100%;
      height: 48px;
      line-height: 1;
      margin-top: 10px;
    }

    .el-button--default {
      margin-top: 0;

      .sa-svg {
        font-size: 22px;
        margin-right: 6px;
      }
    }

    .el-form-item {
      margin-bottom: 32px;
    }

    .el-form-item__content {
      line-height: unset;
    }
  }
}
</style>
<style lang="scss" scoped>
.login-content {
  height: 100%;
  color: var(--sa-subtitle);
  background-size: cover;
  background-repeat: no-repeat;
  background-color: var(--sa-background-assist);

  @media only screen and (max-width: 768px) {
    background-position: center;
  }

  .el-row {
    height: 100%;

    .el-col {
      display: flex;
      align-items: center;
    }

    @media only screen and (max-width: 992px) {
      .el-col {
        justify-content: center;
      }
    }
  }

  .main {
    position: relative;
  }

  .login-wrap {
    width: 460px;
    flex-direction: column;
    padding: 56px 52px 64px;
    border-radius: 8px;
    background: var(--sa-background-assist);
    filter: drop-shadow(0 0 16px rgba(0, 0, 0, 0.2));
    position: absolute;

    .admin-name {
      width: 100%;
      height: 112px;
      font-size: 28px;
      text-align: center;

      .admin-welcome {
        font-size: 20px;
        margin-top: 16px;
        text-align: center;
      }

      .sa-image {
        margin-bottom: 32px;
      }
    }
  }

  .login-wrap {
    height: 500px;
  }

  @media only screen and (max-width: 768px) {
    .login-wrap {
      width: 100%;
      max-width: unset;
      height: 100%;
      border-radius: 0;
      padding: 56px 20px 64px;
      background: transparent;
      filter: unset;

      .admin-name {
        font-size: 26px;
      }
    }
  }

  :deep() {
    .el-input {
      --el-input-height: 48px;
      max-width: unset;

      .el-input__wrapper {
        position: relative;

        .label {
          display: flex;
          align-items: center;
          width: fit-content;
          height: 20px;
          position: absolute;
          top: 14px;
          left: 11px;
          pointer-events: none;
          font-size: 18px;
          color: var(--sa-subfont);
        }

        &.is-focus {
          .label {
            top: 4px;
            font-size: 12px;
            transition: ease-in-out 0.2s;
          }

          .el-input__inner {
            padding: 25px 0 9px;
          }
        }
      }

      &.is-focus {
        .label {
          top: 4px;
          font-size: 12px;
          transition: ease-in-out 0.2s;
        }

        .el-input__inner {
          padding: 25px 0 9px;
        }
      }
    }
  }
}
</style>
