<template>
  <div class="view-account">
    <div class="view-account-header"></div>
    <div class="view-account-container">
      <div class="view-account-top">
        <div>
          <!-- <img :src="websiteConfig.loginImage" alt="" /> -->
          亿数据数据平台
        </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="请输入账号">
              <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="请输入密码" :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>
            <el-button
              class="login-button"
              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 useSocketStore from '@/stores/modules/websocket';
  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';
  import { getAppEnvConfig } from '@/utils/env';
  const envs = getAppEnvConfig();
  const userStore = useUserStore();
  // const socketStore = useSocketStore();
  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: '',
    password: '',
    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.跳转到首页
    setTimeout(() => {
      router.push(HOME_URL);
      loginLoading.value = false;
    }, 1000);
  };

  /**
   * 登录
   */
  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);

      // let url = `ws://8.152.205.9:8080/websocket/${userInfo.id}`;
      // socketStore.connection(url);
      // 如果有多个调解中心，需要选择调解中心进入系统
      if (userInfo.tenants.length > 1) {
        tenantRef.value.openModal(userInfo.tenants);
      } 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;
    background: #e8e8e8;

    &-container {
      max-width: 450px;
      background: #f8f9fd;
      background: linear-gradient(0deg, rgb(255, 255, 255) 0%, rgb(244, 247, 251) 100%);
      border-radius: 40px;
      padding: 25px 55px;
      border: 5px solid rgb(255, 255, 255);
      box-shadow: rgba(133, 189, 215, 0.8784313725) 0px 30px 30px -20px;
      margin: auto;
    }

    &-top {
      text-align: center;
      font-weight: 900;
      font-size: 30px;
      color: rgb(16, 137, 211);

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

    &-other {
      width: 100%;
    }

    .default-color {
      color: #515a6e;

      .ant-checkbox-wrapper {
        color: #515a6e;
      }
    }
  }
  .view-account-form {
    margin-top: 20px;
    :deep(.el-input__wrapper) {
      width: 410px;
      background: white;
      border: none;
      padding: 15px 20px;
      border-radius: 20px;
      margin-top: 15px;
      box-shadow: #cff0ff 0px 10px 10px -5px;
      border-inline: 2px solid transparent;
      // &::-moz-placeholder {
      //   color: rgb(170, 170, 170);
      // }
      // &::placeholder {
      //   color: rgb(170, 170, 170);
      // }
      // &:focus {
      //   outline: none;
      //   border-inline: 2px solid #12B1D1;
      // }
    }
  }
  .login-button {
    display: block;
    width: 100%;
    font-weight: bold;
    background: linear-gradient(45deg, rgb(16, 137, 211) 0%, rgb(18, 177, 209) 100%);
    color: white;
    padding-block: 15px;
    height: 50px !important;
    margin: 20px auto;
    border-radius: 20px;
    box-shadow: rgba(133, 189, 215, 0.8784313725) 0px 20px 10px -15px;
    border: none;
    transition: all 0.2s ease-in-out;
    &:hover {
      transform: scale(1.03);
      box-shadow: rgba(133, 189, 215, 0.8784313725) 0px 23px 10px -20px;
    }
    &:active {
      transform: scale(0.95);
      box-shadow: rgba(133, 189, 215, 0.8784313725) 0px 15px 10px -10px;
    }
  }
  @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>
