<template>
  <el-row v-show="getShow" class="login-form" style="margin-right: -10px; margin-left: -10px">
    <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
      <LoginFormTitle style="width: 100%" />
    </el-col>
    <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
      <el-card class="mb-10px text-center" shadow="hover">
        <!--        <Qrcode :logo="logoImg" />-->
        <div id="login_container"></div>
      </el-card>
    </el-col>
    <!--    <el-divider class="enter-x">{{ t('login.qrcode') }}</el-divider>-->
    <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
      <div class="mt-15px w-[100%]">
        <XButton :title="t('login.backLogin')" class="w-[100%]" @click="handleBackLogin()" />
      </div>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import LoginFormTitle from './LoginFormTitle.vue'
import { LoginStateEnum, useLoginState } from './useLogin'

defineOptions({ name: 'QrCodeForm' })

const { t } = useI18n()
const { handleBackLogin, getLoginState } = useLoginState()
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.QR_CODE)
const hasInitDingLogin = ref(false)
const messageHandler = ref<((event: MessageEvent) => void) | null>(null)

const appId = 'dingmr9ez0ecgbmscfeb'
const dingRedirectUrl = import.meta.env.VITE_BASE_URL + '/login?loginType=dingding&type=20'

watch(getShow, (show) => {
  if (show && !hasInitDingLogin.value) {
    initDingLogin()
    hasInitDingLogin.value = true
  } else if (!show && hasInitDingLogin.value) {
    destroyDingLogin()
  }
})

onBeforeUnmount(() => {
  destroyDingLogin()
})
const _getRandomString = (len) => {
  len = len || 10
  let $chars = 'ABCDEFGHIJKMNOPQRSTUVWXYZ' // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
  let maxPos = $chars.length
  let pwd = ''
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}
const initDingLogin = () => {
  // if (window.DDLogin) {
  var url = dingRedirectUrl
  var state = _getRandomString(10)
  var gotoUrl = encodeURIComponent(
    'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?' +
      'appid=' +
      appId +
      '&response_type=code' +
      '&scope=snsapi_login' +
      '&state=' +
      state +
      '&redirect_uri=' +
      url
  )

  nextTick(() => {
    if (!getShow.value) return

    var obj = window.DDLogin({
      id: 'login_container',
      goto: gotoUrl,
      style: 'border:none;background-color:#FFFFFF;',
      width: '100%', // 二维码的宽度
      height: '290' // 二维码的高度
    })
    // 重置扫码登录框的样式，让登录框居中
    let box = document.getElementById('login_container')
    box.querySelector('iframe').style.top = '0'
    box.querySelector('iframe').style.bottom = '0'
    box.querySelector('iframe').style.left = '0'
    box.querySelector('iframe').style.right = '0'
    box.querySelector('iframe').style.margin = 'auto'
  })
  /* new window.DDLogin({
    id: "login_container",
    goto: gotoUrl,
    style: "border:none;background-color:#FFFFFF;",
    width: "350",
    height: "350",
  }); */
  var handleMessage = function (event) {
    var origin = event.origin
    if (origin === 'https://login.dingtalk.com') {
      var loginTmpCode = event.data
      console.log(loginTmpCode)
      window.location.href =
        'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingmr9ez0ecgbmscfeb&response_type=code&scope=snsapi_login&state=' +
        state +
        '&redirect_uri=' +
        url +
        '&loginTmpCode=' +
        loginTmpCode
    }
  }
  if (typeof window.addEventListener != 'undefined') {
    window.addEventListener('message', handleMessage, false)
  } else if (typeof window.attachEvent != 'undefined') {
    window.attachEvent('onmessage', handleMessage)
  }
  messageHandler.value = handleMessage
  // }
}

const destroyDingLogin = () => {
  if (messageHandler.value) {
    window.removeEventListener('message', messageHandler.value, false)
    messageHandler.value = null
  }

  const box = document.getElementById('login_container')
  if (box) {
    box.innerHTML = ''
  }
  hasInitDingLogin.value = false
}
</script>
