<template>
  <div class="view-account">
    <div class="view-account-header"></div>
    <div class="view-account-container">
      <div class="view-account-top">
        <div class="text-2xl">
          <!-- <img :src="websiteConfig.loginImage" alt="" /> -->
          Admin Template
        </div>
        <div class="view-account-top-desc">中后台解决方案</div>
      </div>
      <div class="view-account-form">
        <el-form ref="formRef" :model="formInline" :rules="rules" size="large">
          <el-form-item prop="username">
            <el-input v-model="formInline.username" placeholder="Please Input">
              <template #prefix>
                <el-icon size="20"><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="formInline.password" placeholder="Please Input" :type="passwordType">
              <template #prefix>
                <el-icon size="20"><Lock /></el-icon>
              </template>
              <template #suffix>
                <el-icon
                  class="cursor-pointer"
                  v-show="passwordType != 'password'"
                  @click="passwordType = 'password'"
                  ><View
                /></el-icon>
                <el-icon
                  class="cursor-pointer"
                  v-show="passwordType == 'password'"
                  @click="passwordType = 'text'"
                  ><Hide
                /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <div class="w-full flex justify-between">
              <div class="flex-initial">
                <el-checkbox v-model="formInline.autoLogin">自动登录</el-checkbox>
              </div>
              <div class="flex-initial order-last">
                <a href="javascript:">忘记密码</a>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button class="w-full" type="primary" @click="handleLogin" :loading="loginLoading"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>

    <TenantModal ref="tenantRef" @cancel="onCancelTenant" @select="onSelectTenant" />
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { initDynamicRouter } from '@/router/modules/dynamicRouter';
  import { useUserStore } from '@/stores/modules/user';
  import { useTabsStore } from '@/stores/modules/tabs';
  import { useKeepAliveStore } from '@/stores/modules/keepAlive';
  import { HOME_URL } from '@/config';
  import { login, getToken, getUserInfo } from '@/api/auth';
  import TenantModal from '@/components/TenantModal/index.vue';

  const userStore = useUserStore();
  const tabsStore = useTabsStore();
  const keepAliveStore = useKeepAliveStore();
  const tenantRef = ref();
  const loginLoading = ref(false);
  const passwordType = ref('password');

  const router = useRouter();
  const route = useRoute();

  const formInline = reactive({
    username: 'admin',
    password: '123456',
    autoLogin: false,
  });

  const rules = ref({
    username: [{ required: true, message: 'Please input your username', trigger: 'blur' }],
    password: [
      { required: true, message: 'Please input your password', trigger: 'blur' },
      { min: 6, max: 16, message: 'Password should be 6-16 characters', trigger: 'blur' },
    ],
  });

  /**
   * 取消租户选择
   */
  const onCancelTenant = () => {
    // 取消选择租户，执行退出登录
    userStore.logout();
    loginLoading.value = false;
  };

  /**
   * 选择租户
   * @param tenant 租户
   */
  const onSelectTenant = async (tenant) => {
    userStore.setIsTenant(true);
    userStore.setTenant(tenant);

    // 初始化动态路由
    await initDynamicRouter();

    // 3.清空 tabs、keepAlive 数据
    tabsStore.setTabs([]);
    keepAliveStore.setKeepAliveName([]);

    // 4.跳转到首页
    router.push(HOME_URL);
    loginLoading.value = false;
  };

  /**
   * 登录
   */
  const handleLogin = async () => {
    loginLoading.value = true;
    try {
      // 1.调用接口
      await login(formInline);

      // 2.设置 Token
      const { result } = await getToken();
      userStore.setToken(result);

      // 获取用户详情
      const { result: userInfo } = await getUserInfo();
      userStore.setUserInfo(userInfo);

      // 如果有多个租户，需要选择租户进入系统
      if (userInfo.tenants.length > 1) {
        tenantRef.value.openModal();
      } else {
        await onSelectTenant(userInfo.tenants[0] || null);
      }
    } catch (e) {
      console.log('error', e);
      loginLoading.value = false;
    }
  };

  onMounted(() => {
    // 路由中携带参数tenant
    if (route.params?.tenant) {
      tenantRef.value.openModal();
    }
  });
</script>
<style lang="scss" scoped>
  .view-account {
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: auto;

    &-container {
      flex: 1;
      padding: 32px 12px;
      max-width: 384px;
      min-width: 320px;
      margin: 0 auto;
    }

    &-top {
      padding: 32px 0;
      text-align: center;

      &-desc {
        font-size: 14px;
        color: #808695;
      }
    }

    &-other {
      width: 100%;
    }

    .default-color {
      color: #515a6e;

      .ant-checkbox-wrapper {
        color: #515a6e;
      }
    }
  }
  @media (min-width: 768px) {
    .view-account {
      background-image: url('../../assets/images/login.svg');
      background-repeat: no-repeat;
      background-position: 50%;
      background-size: 100%;
    }

    .page-account-container {
      padding: 32px 0 24px 0;
    }
  }
</style>
