<template>
  <div class="content-header">
    <img :src="oemSiteInfo.sysLogoUrl" style="height: 30px">
  </div>
  <div
    class="content-body"
    :style="[
      { background: 'url(' + oemSiteInfo.mgr.loginPageBGImgUrl + ')' },
      { backgroundSize: 'cover' },
      { backgroundPosition: 'center top' },
      { backgroundRepeat: 'no-repeat' },

    ]"
  >
    <div class="content-main" :style="{ justifyContent: loginPosition }">
      <div class="user-layout-content">
        <!-- 错误提示信息 -->
        <a-alert
          v-if="showLoginErrorInfo"
          type="error"
          showIcon
          style="margin-bottom: 24px"
          :message="showLoginErrorInfo"
        />
        <div class="main">
          <div class="desc">运营平台登录</div>
          <a-form ref="formLogin" class="user-layout-login" :model="formState" :rules="loginrules" @submit="handleSubmit">
            <a-form-item name="username" class="input-item">
              <login-text-up
                v-model:value="formState.username"
                :disabled="!vdata.googleIsShow"
                :isLogin="true"
                :placeholder="vdata.googleIsShow ? '登录名/手机号' : ''"
              />
            </a-form-item>

            <a-form-item name="password" class="input-item" style="margin-bottom: -20px !important">
              <login-text-up
                v-model:value="formState.password"
                :disabled="!vdata.googleIsShow"
                :isLogin="true"
                :placeholder="vdata.googleIsShow ? '密码' : ''"
                isPassword="password"
              />
            </a-form-item>

            <div class="code-body">
              <div class="code-layout" :class="{ googleShow: !vdata.googleIsShow }">
                <div class="code code-layout-item">
                  <a-form-item name="vercode" class="input-item">
                    <login-text-up v-model:value="formState.vercode" :isLogin="true" placeholder="图形验证码" />
                  </a-form-item>

                  <div class="code-img" style="position: relative; background: #ddd">
                    <img v-show="vercodeImgSrc" :src="vercodeImgSrc" @click="refVercode()">
                    <div v-show="isOverdue" class="vercode-mask" @click="refVercode()">
                      已过期 请刷新
                    </div>
                  </div>
                </div>
                <a-form-item v-if="!vdata.googleIsShow" name="mfaCode" class="input-item">
                  <login-text-up
                    v-model:value="formState.mfaCode"
                    style="width: 300px"
                    placeholder="安全码"
                    :isLogin="true"
                    :isGoogle="'false'"
                    class="code-layout-item"
                  />
                </a-form-item>
              </div>
            </div>
            <a-tag v-if="!vdata.googleIsShow" color="orange">
              您已开启虚拟MFA验证，请输入MFA动态安全码。
            </a-tag>
            <a-form-item style="margin-bottom: 30px">
              <!-- 自动登录 -->
              <a-checkbox v-model:checked="isAutoLogin">自动登录</a-checkbox>
              <!-- 忘记密码 -->
              <a class="forge-password" style="float: right" @click="toForgetPwd">忘记密码?</a>
            </a-form-item>
          </a-form>
          <a-button size="large" type="primary" :loading="loginBtnLoadingFlag" style="width: 100%" @click="debounceTime">
            {{ vdata.submitText }}
          </a-button>
        </div>
        <div class="footer" />
      </div>
    </div>
    <div class="content-footer">
      <JeepayFooterInfo />
    </div>
  </div>
</template>
<script setup lang="ts">
import { timeFix } from '@/utils/util'
import { vercode } from '@/api/login'
import { login,$getUploadImgSize } from '@/api/login'
import { useUserStore } from '@/store/modules/user'
import { useOem } from '@/store/modules/oem'
import { debounce } from '@/utils/throttle'
import router from '@/router'
import JeepayFooterInfo from '@/components/JeepayUIComponents/JeepayFooterInfo/JeepayFooterInfo.vue'
import {
  ref,
  onMounted,
  reactive,
  getCurrentInstance,
  h,
  onUnmounted
} from 'vue'

// 获取全局函数
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

const vdata = reactive({
  googleIsShow: true, // 是否让谷歌输入框展示
  submitText: '登录'
})

const userStore = useUserStore()

// 获取网站信息
const oemSiteInfo = useOem().getSiteInfo()

let loginPosition = ref('') // 决定登录框水平位置 左中右？
let loginPageCardPosition = oemSiteInfo.mgr.loginPageCardPosition
if (loginPageCardPosition === 'right') {
  loginPosition.value = 'flex-end'
} else if (loginPageCardPosition === 'center') {
  loginPosition.value = 'center'
} else if (loginPageCardPosition === 'left') {
  loginPosition.value = 'flex-start'
}

let isOverdue = ref(false) // 设置过期样式
let isAutoLogin = ref() // 是否是自动登录
let loginBtnLoadingFlag = ref(false) // 登录按钮是否显示 加载状态
let showLoginErrorInfo = ref('') // 是否显示登录错误面板信息
let timer: number = -1
let vercodeImgSrc = ref('') // 验证码图片
let vercodeToken = ref('') // 验证码验证token

let formLogin = ref()

let formState = reactive({
  username: '',
  password: '',
  vercode: '',
  mfaCode: ''
})
const loginrules: any = reactive({
  username: [{ required: true, message: '请输入登录名/手机号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  vercode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { max: 4, message: '验证码长度错误', trigger: 'blur' }
  ]
})

onMounted(() => {
  refVercode()
})
// 防抖函数
const debounceTime = debounce(handleSubmit, 500)
// handler
function handleSubmit() {
  let loginParams = {
    username: formState.username,
    password: formState.password,
    vercode: formState.vercode,
    vercodeToken: vercodeToken.value,
    googleCode: formState.mfaCode
  }

  formLogin.value
    .validate()
    .then(() => {
      loginBtnLoadingFlag.value = true // 登录按钮显示加载loading
      // console.log('values', formState, toRaw(formState))
      // 请求登录
      login(loginParams)
        .then((bizData) => {
          showLoginErrorInfo.value = ''
          loginBtnLoadingFlag.value = false

          if (bizData['isMFA']) {
            vdata.submitText = '确认登录'
            vdata.googleIsShow = false
            delete loginrules?.vercode
            loginrules.mfaCode = [
              { required: true, message: '请输入安全码', trigger: 'blur' }
            ] as any
            return
          }

          userStore.putToken(bizData['iToken'])
          $getUploadImgSize().then(res=>{
            localStorage.setItem('uploadImgSize',res.applymentImgUploadSize)
          })
          router.push({ path: '/' })
          // 延迟 1 秒显示欢迎信息
          setTimeout(() => {
            let lastLoginTimeStr = bizData['lastLoginTime']
              ? '上次登录时间：' + bizData['lastLoginTime']
              : ''
            $infoBox.notification.success({
              message: '欢迎',
              description: [
                h('p', `${timeFix()}，欢迎回来`),
                h('p', lastLoginTimeStr)
              ]
            })
          }, 1000)
          showLoginErrorInfo.value = ''

          // router.push('/merchant/list')
        })
        .catch((err) => {
          loginBtnLoadingFlag.value = false
          showLoginErrorInfo.value = err.msg || JSON.stringify(err)
        })
    })
    .catch((error) => {
      console.log('error', error)
    })
}

function refVercode() {
  // 刷新图片验证码
  // 获取图形验证码
  vercode().then((res) => {
    vercodeImgSrc.value = res.imageBase64Data
    vercodeToken.value = res.vercodeToken

    isOverdue.value = false

    if (timer) clearInterval(timer) // 如果多次点击则清除已有的定时器
    // 超过60秒提示过期刷新
    timer = window.setInterval(() => {
      res.expireTime--
      if (res.expireTime <= 0) {
        isOverdue.value = true
        clearInterval(timer)
      }
    }, 1000)
  })
}

// 忘记密码跳转页面
function toForgetPwd() {
  router.push({ name: 'forget', path: '/user/forget' })
}
// 计算轮播图位置
const calcPositionStyle = () => {
  if (loginPageCardPosition == 'right') return { left: '10vw' }
  return { right: '10vw' }
}
// 监听回车事件
document.onkeydown = function (e) {
  var theEvent = e || window.event
  var code = theEvent.keyCode || theEvent.which || theEvent.charCode
  if (code == 13) {
    //回车键的键值为13
    debounceTime()
  }
}
onUnmounted(() => {
  document.onkeydown = null
})
</script>

<style lang="less" scoped>
.content-header {
  display: flex;
  align-items: center;
  position: fixed;
  z-index: 100;
  padding: 0 50px;
  left: 0;
  right: 0;
  height: 80px;
  background-color: hsla(100, 100, 100, 0.85);
  backdrop-filter: blur(50px) saturate(180%);
}

.content-body {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  object-fit: cover;
  padding: 0 10vw;
  padding-top: 80px;
 min-height: 100vh;

  .content-main {
    flex-grow: 1;
    display: flex;
    // justify-content: flex-end;
    align-items: center;

  }
}

.user-layout-content {

  transition: 0.3s ease;

  input {
    height: 40px !important;
  }

  .main {
    padding: 50px 30px;
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    background: #fff;
    box-shadow: 0 30px 60px -35px rgb(0 0 0 / 10%);
    border: 1px solid #e7eaf3;
    align-items: center;
    border-radius: 15px;
    transition: all 0.3s, border 0s ease;

    .ant-form {
      max-width: 300px;
    }

    .desc {
      font-weight: bold;
      font-size: 20px;
      letter-spacing: 0.04em;
      color: var(--ant-primary-color);
      margin-bottom: 50px;
      text-align: center;
    }

    .input-item {
      height: 65px;
      margin: 0 !important;
    }
  }

  .footer {
    // position: absolute;
    width: 100%;
    bottom: 0;
    padding: 0 16px;
    margin: 48px 0 24px;
    text-align: center;

    .links {
      margin-bottom: 8px;
      font-size: 14px;

      a {
        color: rgba(0, 0, 0, 0.45);
        transition: all 0.3s;

        &:not(:last-child) {
          margin-right: 40px;
        }
      }
    }

    .copyright {
      color: rgba(0, 0, 0, 0.45);
      font-size: 14px;
    }
  }
}

.code-body {
  padding-top: 20px;
  width: 300px;
  overflow-x: hidden;
}

.code-layout {
  display: flex;
  width: 600px;
  transition: 0.3s;

  .code-layout-item {
    width: 50%;
  }
}

.googleShow {
  margin-left: -300px;
}

//登录页响应式的调整
@media screen and (min-width: 769px) and (max-width: 1024px) {
  .container {
    padding: 0 100px;
    min-height: 700px;


    .user-layout-content {
      width: 360px;
      height: auto;

      .main {
        width: 360px;
        box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
        border: 0.0625rem solid #e7eaf3;
        height: auto;
        justify-content: center;
        border-radius: 10px;
      }
    }
  }
}

@media screen and (min-width: 1025px) and (max-width: 1366px) {
  .container {
    padding: 0 150px;
    min-height: 700px;


    .user-layout-content {
      width: 360px;
      height: auto;

      .main {
        width: 360px;
        box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
        border: 0.0625rem solid #e7eaf3;
        height: auto;
        justify-content: center;
        border-radius: 10px;
      }
    }
  }
}

@media screen and (min-width: 1367px) and (max-width: 1600px) {
  .container {
    padding: 0 250px;
    min-height: 700px;

    .user-layout-content {
      width: 360px;
      height: auto;

      .main {
        width: 360px;
        box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
        border: 0.0625rem solid #e7eaf3;
        height: auto;
        justify-content: center;
        border-radius: 10px;
      }
    }
  }
}

@media screen and (min-width: 1601px) {
  .container {
    padding: 0 300px;
    min-height: 700px;


    .user-layout-content {
      width: 360px;
      height: auto;

      .main {
        width: 360px;
        box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
        border: 0.0625rem solid #e7eaf3;
        height: auto;
        justify-content: center;
        border-radius: 10px;
      }
    }
  }
}
</style>
<style lang="less" scoped>
/deep/ input:-webkit-autofill {
  box-shadow: inset 0 0 0 1000px #fff;
}

/deep/ input:hover:-webkit-autofill {
  box-shadow: inset 0 0 0 1000px #fff;
}

.user-layout-login {
  label {
    font-size: 14px;
  }

  .forge-password {
    font-size: 14px;
    color: @jee-theme;
  }

  // button.login-button {
  //   padding: 0 15px;
  //   font-size: 16px;
  //   height: 40px;
  //   width: 100%;
  // }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }

  .code {
    display: flex;
    justify-content: space-between;

    .code-input {
      width: 216px;
    }

    .code-img {
      width: 120px;
      height: 40px;
      background-color: #ddd;
      margin-left: 10px;

      img {
        width: 120px;
        height: 40px;
      }
    }
  }

  .submit {
    margin-bottom: 0;
  }
}

.vercode-mask {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #000;
  opacity: 0.8;
  text-align: center;
  line-height: 40px;
  color: #fff;

  &:hover {
    cursor: pointer;
  }
}
</style>
