<template>
  <div class="login">
    <div class="logo"></div>
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <div class="title-box">
        <!--        <h3 class="title">{{ title }}</h3>-->
        <!--        <lang-select />-->
      </div>
      <div class="login-tabs">
        <span class="is-active">账号登录</span>
      </div>
      <el-form-item v-if="tenantEnabled" prop="tenantId">
        <el-select v-model="loginForm.tenantId" filterable :placeholder="proxy.$t('login.selectPlaceholder')" style="width: 100%">
          <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"></el-option>
          <template #prefix><svg-icon icon-class="company" class="el-input__icon input-icon" /></template>
        </el-select>
      </el-form-item>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" :placeholder="proxy.$t('login.username')">
          <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          size="large"
          auto-complete="off"
          :placeholder="proxy.$t('login.password')"
          @keyup.enter="handleLogin"
        >
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="captchaEnabled" prop="code">
        <el-input
          v-model="loginForm.code"
          size="large"
          auto-complete="off"
          :placeholder="proxy.$t('login.code')"
          style="width: 63%"
          @keyup.enter="handleLogin"
        >
          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" class="login-code-img" @click="getCode" />
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0">{{ proxy.$t('login.rememberPassword') }}</el-checkbox>
      <!--      <button class="forgot-button" type="button">忘记密码?</button>-->
      <!--      <div class="login-options">-->
      <!--      </div>-->
      <!--      <el-form-item style="float: right">-->
      <!--        <el-button circle :title="proxy.$t('login.social.wechat')" @click="doSocialLogin('wechat')">-->
      <!--          <svg-icon icon-class="wechat" />-->
      <!--        </el-button>-->
      <!--        <el-button circle :title="proxy.$t('login.social.maxkey')" @click="doSocialLogin('maxkey')">-->
      <!--          <svg-icon icon-class="maxkey" />-->
      <!--        </el-button>-->
      <!--        <el-button circle :title="proxy.$t('login.social.topiam')" @click="doSocialLogin('topiam')">-->
      <!--          <svg-icon icon-class="topiam" />-->
      <!--        </el-button>-->
      <!--        <el-button circle :title="proxy.$t('login.social.gitee')" @click="doSocialLogin('gitee')">-->
      <!--          <svg-icon icon-class="gitee" />-->
      <!--        </el-button>-->
      <!--        <el-button circle :title="proxy.$t('login.social.github')" @click="doSocialLogin('github')">-->
      <!--          <svg-icon icon-class="github" />-->
      <!--        </el-button>-->
      <!--      </el-form-item>-->
      <el-form-item class="login-submit">
        <el-button :loading="loading" size="large" type="primary" class="login-button" @click.prevent="handleLogin">
          <span v-if="!loading">{{ proxy.$t('login.login') }}</span>
          <span v-else>{{ proxy.$t('login.logging') }}</span>
        </el-button>
        <div v-if="register" style="float: right">
          <router-link class="link-type" :to="'/register'">{{ proxy.$t('login.switchRegisterPage') }}</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright ©2025 海威物联 All Rights Reserved.</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCodeImg, getTenantList } from '@/api/login';
import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import { useI18n } from 'vue-i18n';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const title = import.meta.env.VITE_APP_TITLE;
const userStore = useUserStore();
const router = useRouter();
const { t } = useI18n();

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: ''
} as LoginData);

const loginRules: ElFormRules = {
  tenantId: [{ required: true, trigger: 'blur', message: t('login.rule.tenantId.required') }],
  username: [{ required: true, trigger: 'blur', message: t('login.rule.username.required') }],
  password: [{ required: true, trigger: 'blur', message: t('login.rule.password.required') }],
  code: [{ required: true, trigger: 'change', message: t('login.rule.code.required') }]
};

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(true);

// 注册开关
const register = ref(false);
const redirect = ref('/');
const loginRef = ref<ElFormInstance>();
// 租户列表
const tenantList = ref<TenantVO[]>([]);

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect && decodeURIComponent(newRoute.query.redirect);
  },
  { immediate: true }
);

const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', String(loginForm.value.tenantId));
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        // 否则移除
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      // 调用action的登录方法
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        const redirectUrl = redirect.value || '/';
        await router.push(redirectUrl);
        loading.value = false;
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  const tenantId = localStorage.getItem('tenantId');
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe)
  } as LoginData;
};

/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList(false);
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type: string) => {
  authBinding(type, loginForm.value.tenantId).then((res: any) => {
    if (res.code === HttpStatus.SUCCESS) {
      // 获取授权地址跳转
      window.location.href = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

onMounted(() => {
  getCode();
  initTenantList();
  getLoginData();
});
</script>

<style lang="scss" scoped>
.logo {
  position: absolute;
  top: 1vw;
  left: 1vw;
  width: 100px;
  height: 76px;
  //background-image: url('../assets/images/profile.jpg');
  background-image: url('../assets/images/logo.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
.login {
  //display: flex;
  //justify-content: center;
  //align-items: center;
  height: 100%;
  min-height: 640px;
  background-image: url('../assets/images/login-background.jpg');
  //background-size: cover;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

.title-box {
  display: flex;

  .title {
    margin: 0px auto 30px auto;
    text-align: center;
    color: #707070;
  }

  :deep(.lang-select--style) {
    line-height: 0;
    color: #7483a3;
  }
}

.login-form {
  width: 480px;
  padding: 76px 80px 58px;
  position: absolute;
  top: 50%;
  right: 14.9%;
  transform: translateY(-50%);
  z-index: 1;
  border: 1px solid rgba(231, 239, 250, 0.92);
  border-radius: 0;
  background: rgba(255, 255, 255, 0.94);
  box-shadow: 0 14px 38px rgba(62, 112, 172, 0.1);

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

  :deep(.el-form-item__error) {
    padding-top: 6px;
    color: #f56c6c;
  }

  .el-input {
    height: 52px;

    input {
      height: 52px;
      color: #4f5f73;
      font-size: 15px;
      letter-spacing: 0;
    }
  }

  .input-icon {
    width: 15px;
    height: 51px;
    margin-left: 2px;
    color: #aab4c4;
  }
}

.login-tabs {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 34px;
  height: 34px;
  margin-bottom: 42px;
  color: #8f96a3;
  font-size: 20px;
  font-weight: 400;
  letter-spacing: 2px;
  line-height: 1;
  white-space: nowrap;

  span {
    position: relative;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    height: 34px;
  }

  .is-active {
    color: #253347;
    font-weight: 500;
  }

  .is-active::after {
    content: '';
    position: absolute;
    left: 50%;
    bottom: -11px;
    width: 36px;
    height: 3px;
    border-radius: 99px;
    background: #118df0;
    transform: translateX(-50%);
  }
}

:deep(.el-select__wrapper),
:deep(.el-input__wrapper) {
  min-height: 52px;
  padding: 0 16px;
  border-radius: 3px;
  background: #f4f6fb;
  box-shadow: none;
}

:deep(.el-select__wrapper.is-focused),
:deep(.el-input__wrapper.is-focus) {
  background: #fff;
  box-shadow:
    0 0 0 1px #1590f1 inset,
    0 6px 16px rgba(17, 141, 240, 0.1);
}

:deep(.el-input__inner::placeholder) {
  color: #adb4c0;
}

.login-options {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: -8px 0 54px;
  color: #a3abb7;

  :deep(.el-checkbox) {
    height: 18px;
    color: #a3abb7;
    font-size: 14px;
    font-weight: 400;
  }

  :deep(.el-checkbox__label) {
    padding-left: 8px;
    color: #a3abb7;
  }

  :deep(.el-checkbox__inner) {
    width: 16px;
    height: 16px;
    border-color: #c8ced8;
    border-radius: 0;
    background: transparent;
  }
}

.forgot-button {
  padding: 0;
  border: 0;
  background: transparent;
  color: #a3abb7;
  font: inherit;
  cursor: pointer;
}

.forgot-button:hover {
  color: #118df0;
}

.login-submit {
  width: 100%;
  margin-bottom: 0 !important;
}

.login-button {
  width: 100%;
  height: 54px;
  border: 0;
  border-radius: 4px;
  background: #118df0;
  font-size: 18px;
  font-weight: 600;
  letter-spacing: 14px;
  box-shadow: none;

  span {
    margin-right: -14px;
  }
}

.login-button:hover,
.login-button:focus {
  background: #0b83e4;
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 52px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial, serif;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 52px;
  padding-left: 12px;
}

@media (max-width: 1280px) {
  .login-form {
    right: 8%;
  }
}

@media (max-width: 960px) {
  .login {
    min-height: 100%;
    background-size: cover;
    background-position: center;
  }

  .login-form {
    width: min(88vw, 480px);
    min-height: auto;
    padding: 56px 42px 44px;
    right: 50%;
    transform: translate(50%, -50%);
  }

  .login-tabs {
    gap: 22px;
    justify-content: center;
    font-size: 17px;
    letter-spacing: 1px;
  }
}
</style>
