<template>
  <div class="topV">
    <div
      class="topV1"
      v-if="identityType === 0"
      :style="{ overflow: 'auto', backgroundSize: smallerThanLg ? 'cover' : 'cover' }"
    >
    </div>
    <div
      class="topV2"
      v-if="identityType === 1"
      :style="{ overflow: 'auto', backgroundSize: smallerThanLg ? 'cover' : 'cover' }"
    >
    </div>
    <div class="flex items-center text-white mt-40px ml-50px" style="position: absolute">
      <img alt="" class="mr-10px h-40px" src="@/assets/imgs/logo5.png" />
    </div>

    <div style="position: absolute; width: 100%; height: 100%; overflow: auto">
      <el-row>
        <el-col :xs="24" :sm="24" :md="24" :lg="14" :xl="14">
          <div
            v-if="identityType === 0"
            class="column topText1"
            style="padding: 0; margin-top: 12vh; justify-content: center; align-items: center"
          >
            <span
              class="text-40px font-bold"
              style="margin-left: 2vw; letter-spacing: 10px; color: #fff"
              >欢迎来到颐年智慧医养数字平台</span
            >
          </div>
          <div
            v-if="identityType === 1"
            class="column topText2"
            style="padding: 0 4vw; margin-top: 20vh; justify-content: center; align-items: center"
          >
            <span class="text-50px font-bold" style="letter-spacing: 10px; color: #333"
              >欢迎来到颐年医养</span
            >
            <div class="column">
              <span class="text-25px font-bold">智慧康养SaaS管理平台，以科技赋能养老</span>
              <span
                class="text-25px font-bold"
                style="margin-top: 18px; letter-spacing: 8px; color: #333; text-indent: 40px"
                >让爱与关怀无处不在，引领未来养老新生态</span
              >
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="10" :xl="10">
          <div
            class="column"
            style="align-items: center; justify-content: center"
            :style="{ height: heightScreen + 'px' }"
          >
            <el-form
              ref="formLogin"
              :model="loginData.loginForm"
              :rules="LoginRules"
              class="login-form"
              label-position="top"
              label-width="120px"
              size="large"
            >
              <div
                class="column cardR"
                :style="{
                  width: '460px',
                  height: 500 + 'px',
                  marginTop: heightScreen * 0.05 + 'px'
                }"
              >
                <div
                  class="row"
                  :style="{
                    width: '382px',
                    marginTop: -10 + 'px'
                  }"
                >
                </div>

                <div
                  class="row"
                  :style="{
                    width: '382px',
                    marginTop: 28 + 'px'
                  }"
                >
                  <el-tabs v-model="loginType" class="demo-tabs" @tab-click="typeCK">
                    <el-tab-pane label="" name="1">
                      <template #label>
                        <span
                          class="text-20px font-bold"
                          :style="{ color: loginType === '1' ? systemTheme : '#333333' }"
                          >账号登录</span
                        >
                      </template>
                    </el-tab-pane>
                  </el-tabs>
                  <div
                    @click="typeCK(1)"
                    class="column"
                    style="align-items: center; cursor: pointer"
                  >
                  </div>
                </div>

                <el-form-item v-if="loginData.tenantEnable === 'true'" prop="tenantName">
                  <div class="row inputM" :style="{ width: '382px', marginTop: '16px' }">
                    <span style="width: 60px; font-size: 14px; color: #000">{{
                      identityType === 0 ? '企业名' : '集团名'
                    }}</span>
                    <input
                      style="height: 50px; font-size: 14px; color: #000"
                      :style="{ width: '300px' }"
                      v-model="loginData.loginForm.tenantName"
                      @focus="focusHd"
                      class="inputS"
                      @keyup.enter="handleLogin"
                      :placeholder="identityType === 0 ? '请输入企业名' : '请输入集团名'"
                    />
                    <div style="flex-grow: 1"></div>
                  </div>
                </el-form-item>

                <el-form-item prop="username" size="small">
                  <div class="row inputM" :style="{ width: '382px', marginTop: '-2px' }">
                    <span style="width: 60px; font-size: 14px; letter-spacing: 12px; color: #000"
                      >账号</span
                    >
                    <input
                      style="height: 50px; font-size: 14px; color: #000"
                      :style="{ width: '300px' }"
                      v-model="loginData.loginForm.username"
                      @focus="focusHd"
                      class="inputS"
                      @keyup.enter="handleLogin"
                      placeholder="请输入账号或手机号"
                    />
                    <div style="flex-grow: 1"></div>
                  </div>
                </el-form-item>

                <el-form-item prop="password" size="small">
                  <div class="row inputM" :style="{ width: '382px', marginTop: '-2px' }">
                    <span style="width: 60px; font-size: 14px; letter-spacing: 12px; color: #000"
                      >密码</span
                    >
                    <input
                      style="height: 50px; font-size: 14px; color: #000"
                      :style="{ width: '260px' }"
                      v-model="loginData.loginForm.password"
                      @focus="focusHd"
                      class="inputS2"
                      @keyup.enter="handleLogin"
                      placeholder="请输入密码"
                      :type="hides ? 'password' : 'text'"
                    />
                    <div style="flex-grow: 1"></div>
                    <div
                      @click="hide"
                      style="width: 20px; height: 20px; cursor: pointer"
                      class="row"
                    >
                      <el-icon v-show="hides" color="#888888" size="18px"><Hide /></el-icon>
                      <el-icon v-show="!hides" color="#888888" size="18px"><View /></el-icon>
                    </div>
                  </div>
                </el-form-item>
                <el-button
                  type="primary"
                  size="large"
                  @click="handleLogin"
                  :loading="loginLoading"
                  :style="{ width: '382px', marginTop: '40px' }"
                  style="height: 50px; font-size: 16px"
                  >登录</el-button
                >
                <a
                  class="aa"
                  @mousemove="isMouseout = true"
                  @mouseout="isMouseout = false"
                  href="https://www.google.cn/intl/zh-CN/chrome/"
                  target="_blank"
                  :style="{ color: isMouseout ? systemTheme : '#888888' }"
                  >使用谷歌浏览器，体验更佳 >></a
                >
              </div>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 账号登录 -->
    <!-- <LoginForm class="m-auto h-auto p-20px lt-xl:(rounded-3xl light:bg-white)" /> -->
    <!-- 手机登录 -->
    <!-- <MobileForm class="m-auto h-auto p-20px lt-xl:(rounded-3xl light:bg-white)" /> -->
    <!-- 二维码登录 -->
    <!-- <QrCodeForm class="m-auto h-auto p-20px lt-xl:(rounded-3xl light:bg-white)" /> -->
    <!-- 注册 -->
    <!-- <RegisterForm class="m-auto h-auto p-20px lt-xl:(rounded-3xl light:bg-white)" /> -->
    <!-- 三方登录 -->
    <!-- <SSOLoginVue class="m-auto h-auto p-20px lt-xl:(rounded-3xl light:bg-white)" /> -->
  </div>
</template>

<script lang="ts" setup>
import { useDesign } from '@/hooks/web/useDesign'
import { useAppStore } from '@/store/modules/app'
import { onMounted } from 'vue'
// import { Hide, View } from '@element-plus/icons-vue'
import * as LoginApi from '@/api/login'
import { ElLoading } from 'element-plus'
import * as authUtil from '@/utils/auth'
import { useFormValid } from '@/views/Login/components/useLogin'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { breakpointsTailwind, useBreakpoints } from '@vueuse/core'
import { usePermissionStore } from '@/store/modules/permission'
import { useUserStore } from '@/store/modules/user'
// import { setLOGINPLATFORM } from '@/utils/auth'
defineOptions({ name: 'Login' })
const breakpoints = useBreakpoints(breakpointsTailwind)
const smallerThanLg = breakpoints.smaller('xl') // only larger than md
const { currentRoute, push } = useRouter()
const { t } = useI18n()
const appStore = useAppStore()
const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('login')
const widthScreen = ref(0)
const heightScreen = ref(0)
const titleWidth = ref(0)
const src = ref(true)
const hides = ref(true)
const loginType = ref('1') //登录类型，扫码或者账号
const identityType = ref(0) //身份类型
const animationPlayState = ref('revert') //
const systemTheme = ref(appStore.getTheme.elColorPrimary)
const loginLoading = ref(false)
const formLogin = ref()
const { validForm } = useFormValid(formLogin)
const redirect = ref<string>('')
const isMouseout = ref(false)
const isPhone = ref(false) //是不是手机端
const userStore = useUserStore()
const permissionStore = usePermissionStore()
import fetchHttp from '@/config/axios/fetchHttp'

const loginData = reactive({
  isShowPassword: false,
  captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE,
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  loginForm: {
    tenantName: '',
    username: '',
    password: '',
    captchaVerification: '',
    loginDevice: 1,
    rememberMe: true, // 默认记录我。如果不需要，可手动修改
    loginPlatform: 0 // 0 企业 1集团
  }
})

const LoginRules = {
  tenantName: [required],
  username: [required],
  password: [required]
}

widthScreen.value =
  screen.width ||
  window.innerWidth ||
  document.documentElement.clientWidth ||
  document.body.clientWidth
heightScreen.value =
  screen.height ||
  window.innerHeight ||
  document.documentElement.clientHeight ||
  document.body.clientHeight

onMounted(() => {
  if (widthScreen.value < heightScreen.value) {
    isPhone.value = true
    widthScreen.value = widthScreen.value * 3.6
  } else {
    heightScreen.value = heightScreen.value * 0.756
  }

  titleWidth.value = getTextWidthWithLetterSpacingDOM('欢迎来到颐年医养', '61px Arial', 10)
  console.log('字体宽度', titleWidth.value)

  getLoginFormCache()
  getTenantByWebsite()
})

const getTextWidthWithLetterSpacingDOM = (text, font, letterSpacing) => {
  const span = document.createElement('span')
  span.style.visibility = 'hidden' // 隐藏元素
  span.style.position = 'absolute' // 不影响页面布局
  span.style.font = font
  span.style.letterSpacing = letterSpacing + 'px'
  span.textContent = text
  document.body.appendChild(span) // 添加到DOM中

  const width = span.offsetWidth // 读取计算后的宽度
  document.body.removeChild(span) // 移除元素

  return width
}

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

const typeCK = (type) => {
  loginType.value = type
}

const identityCK = (type) => {
  identityType.value = type
  animationPlayState.value = 'revert'
  setTimeout(() => {
    animationPlayState.value = 'running'
  }, 3000)
}

const focusHd = () => {
  console.log('focusHd')
}

const hide = () => {
  hides.value = !hides.value
}

// 获取租户 ID
const getTenantId = async () => {
  if (loginData.tenantEnable === 'true') {
    authUtil.setTenantId(1)
    // const res = await LoginApi.getTenantIdByName(loginData.loginForm.tenantName)
    // authUtil.setTenantId(res)
  }
}

const loading = ref() // ElLoading.service 返回的实例
// 登录
const handleLogin = async (params) => {
  loginLoading.value = true
  try {
    await getTenantId()
    const data = await validForm()
    if (!data) {
      return
    }

    loginData.loginForm.captchaVerification = params.captchaVerification
    loginData.loginForm.loginPlatform = identityType.value
    let paramsData = {
      organizationName: loginData.loginForm.tenantName,
      username: loginData.loginForm.username,
      password: loginData.loginForm.password
    }
    // const res = await LoginApi.login(loginData.loginForm)
    // const res = await LoginApi.login(paramsData)
    const res = await fetchHttp.post('/api/pc/auth/login', paramsData)
    if (!res) {
      return
    }
    loading.value = ElLoading.service({
      lock: true,
      text: '正在加载系统中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    if (loginData.loginForm.rememberMe) {
      authUtil.setLoginForm(loginData.loginForm)
    } else {
      authUtil.removeLoginForm()
    }
    localStorage.setItem('identity', String(identityType.value))
    authUtil.setToken({
      refreshToken: res.accessToken,
      accessToken: res.accessToken
    })
    localStorage.setItem('organizationId', res.organizationId)
    redirect.value = '/'
    // if (!redirect.value) {
    //   if (identityType.value == 0) {
    //     redirect.value = '/'
    //   } else {
    //     redirect.value = '/home/data_index'
    //   }
    // }
    // 判断是否为SSO登录
    if (redirect.value.indexOf('sso') !== -1) {
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      push({ path: redirect.value || permissionStore.addRouters[0].path })
    }
  } finally {
    loginLoading.value = false
    loading.value?.close()
  }
}

// 根据域名，获得租户信息
const getTenantByWebsite = async () => {
  // const website = location.host
  // const res = await LoginApi.getTenantByWebsite(website)
  // if (res) {
  //   loginData.loginForm.tenantName = res.name
  //   authUtil.setTenantId(res.id)
  // }
}

// 记住我
const getLoginFormCache = () => {
  const loginForm = authUtil.getLoginForm()
  if (loginForm) {
    loginData.loginForm = {
      ...loginData.loginForm,
      username: loginForm.username ? loginForm.username : loginData.loginForm.username,
      password: loginForm.password ? loginForm.password : loginData.loginForm.password,
      rememberMe: loginForm.rememberMe,
      tenantName: loginForm.tenantName ? loginForm.tenantName : loginData.loginForm.tenantName
    }
  }
}
</script>

<style lang="scss" scoped>
$prefix-cls: #{$namespace}-login;

/* 定义动画 */
@keyframes fadeIn {
  from {
    opacity: 0.2;
  }

  to {
    opacity: 1;
  }
}

/* 定义动画 */
@keyframes fadeIn2 {
  from {
    opacity: 0.1;
  }

  to {
    opacity: 1;
  }
}

.#{$prefix-cls} {
  overflow: auto;

  &__left {
    &::before {
      position: absolute;
      top: 0;
      left: 0;
      z-index: -1;
      width: 100%;
      height: 100%;
      background-image: url('@/assets/svgs/login-bg.svg');
      background-position: center;
      background-repeat: no-repeat;
      content: '';
    }
  }
}

.topV {
  position: relative;
  width: 100%;
  height: 100%;
  background-attachment: fixed;
  background-color: #e0e7f9;
  background-repeat: no-repeat;
}

.topV1 {
  position: absolute;
  width: 100%;
  height: 100%;
  background-attachment: fixed;
  // background-image: url('@/assets/imgs/home_bg.png');
  background-image: url('@/assets/imgs/login_banner.png');
  background-repeat: no-repeat;
  opacity: 0.2;
  animation: fadeIn 0.7s ease-in forwards;
}

.topV2 {
  position: absolute;
  width: 100%;
  height: 100%;
  background-attachment: fixed;
  // background-image: url('@/assets/imgs/home_bg.png');
  background-image: url('@/assets/imgs/login_banner.png');
  background-repeat: no-repeat;
  opacity: 0.2;
  animation: fadeIn 0.7s ease-in forwards;
}

.topText1 {
  opacity: 0.1;
  animation: fadeIn2 0.8s ease-in forwards;
}

.topText2 {
  opacity: 0.1;
  animation: fadeIn2 0.8s ease-in forwards;
}

.column {
  display: flex;
  flex-direction: column;
}

.row {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.cardR {
  display: flex;
  width: 20vw;
  padding: 26px 10px;
  background-color: white;
  border-radius: 12px;
  align-items: center;
  justify-content: start;
  box-shadow:
    10px 10px 15px rgb(0 0 0 / 2%),
    -10px -10px 15px rgb(0 0 0 / 2%),
    10px -10px 15px rgb(0 0 0 / 2%),
    -10px 10px 15px rgb(0 0 0 / 2%);
}

.inputM {
  width: 16.8vw;
  height: 50px;
  padding: 10px 12px;
  margin-top: 2vh;
  border: #ddd solid 1px;
  border-radius: 4px;
}

.inputS {
  width: 90%;
  background-color: transparent;
  border: none;
  outline: none;
  box-shadow: none;
}

.inputS2 {
  background-color: transparent;
  border: none;
  outline: none;
  box-shadow: none;
}

input::placeholder {
  font-family: Arial, sans-serif; /* 修改placeholder文本的字体 */
  font-size: 14px; /* 修改placeholder文本的字体大小 */
  color: #a0a0a0; /* 修改placeholder文本的颜色 */
}

:deep(.el-tabs__nav-wrap::after) {
  background-color: transparent;
}

:deep(.el-tabs__item) {
  padding: 0 12px;
}

.aa {
  margin-top: 20px;
  font-size: 12px;
  color: #888; /* 未访问链接的颜色 */
}

.aa:hover {
  margin-top: 20px;
  font-size: 12px;
  color: #13b4f1;
}

::-webkit-scrollbar {
  width: 3px; //滚动条宽度
}

::-webkit-scrollbar-thumb {
  //上层
  background: var(--el-border-color-dark); //背景颜色
  border-radius: 10px; //滚动条圆弧半径
  //-webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);	//滚动条阴影
}

::-webkit-scrollbar-track {
  //底层
  //-webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #f7f8fa;
  border-radius: 0;
}
</style>
