<script>
import Cookie from 'js-cookie'

export default defineComponent({
  beforeRouteEnter (to, from, next) {
    if (Cookie.get('token')) {
      next('/home')
    } else {
      next()
    }
  }
})
</script>
<script setup name="login">
import { onMounted, ref, getCurrentInstance, defineComponent, reactive } from 'vue'
import router from '@/router'
import dd from 'gdt-jsapi'
import { scanQrcode, getVerificationCode } from '@/http/apis/auth'
import { UserFilled, Lock } from '@element-plus/icons-vue'

const
  { proxy } = getCurrentInstance()
const appName = import.meta.env.MODE === 'production' ? '浙政钉' : '专有钉钉'
const qrSrc =
  import.meta.env.MODE === 'production'
    ? 'https://login-pro.ding.zj.gov.cn/oauth2/auth.htm?response_type=code&client_id=ls_project_managment_dingoa&redirect_uri=http://60.188.225.145/&scope=get_user_info&authType=QRCODE&embedMode=true'
    : 'https://login.dg-work.cn/oauth2/auth.htm?response_type=code&client_id=ls-rebuild_dingoa&redirect_uri=http://ls-rebuild.ningdatech.com/login&scope=get_user_info&authType=QRCODE&embedMode=true'
const tabStatus = ref(true)
const clickTab = (val) => {
  tabStatus.value = val
}
const ruleForm = reactive({})
const ruleFormRef = ref()
const rules = reactive({
  phoneNum: [
    { required: true, message: '请输入手机号', trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
})
// 验证码登录
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      scanQrcode({
        credential: ruleForm.verifyCode,
        identifier: ruleForm.phoneNum,
        loginType: 'PHONE_VERIFICATION_CODE_LOGIN'
      }).then((res) => {
        if (res.code === 200) {
          flag.value = true
          router.replace('/')
        } else {
          proxy.$message.error(res.respMsg)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 自动登录
const flag = ref(false)
const isDD = ref(true)
const autoLogin = () => {
  if (dd) {
    dd.getAuthCode({})
      .then(result => {
        if (result && (result.code || result.auth_code)) {
          scanQrcode({
            credential: result.code || result.auth_code,
            identifier: '',
            loginType: 'DING_MD_LOGIN'
          }).then((res) => {
            if (res.code === 200) {
              flag.value = true
              router.replace('/')
            } else {
              proxy.$message.error(res.respMsg)
            }
          })
        }
      })
      .catch(() => {
        isDD.value = false
        // 注册监听扫码事件
        const registerQrcode = () => {
          window.addEventListener('message', function (event) {
            // console.log('event.data.code', event.data.code)
            if (!flag.value && event.data.code) {
              scanQrcode({
                credential: event.data.code,
                identifier: '',
                loginType: 'DING_QR_LOGIN'
              }).then((res) => {
                if (res.code === 200) {
                  flag.value = true
                  router.replace('/')
                } else {
                  proxy.$message.error(res.respMsg)
                }
              })
            }
          })
        }
        registerQrcode()
      })
  } else {
    console.log('未找到ddApi')
  }
}
// 获取验证码
const count = ref('')
const timer = ref(null)
const countShow = ref(true)
const getVerificationCodeFunc = async () => {
  const res = await getVerificationCode({ mobile: ruleForm.phoneNum, verificationType: 'LOGIN' })
  if (res.code === 200) {
    proxy.$message.success('验证码已发送')
    const TIME_COUNT = 60
    if (!timer.value) {
      count.value = TIME_COUNT
      countShow.value = false
      timer.value = setInterval(() => {
        if (count.value > 0 && count.value <= TIME_COUNT) {
          count.value--
        } else {
          countShow.value = true
          clearInterval(this.timer)
          timer.value = null
        }
      }, 1000)
    }
  }
}
onMounted(() => {
  var device = navigator.userAgent.toLowerCase()
  if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(device)) {
    window.location.href = appName === '浙政钉' ? 'http://60.188.225.145:8090/' : 'http://lsmobile.ningdatech.com/'
  } else {
    autoLogin()
  }
})
</script>

<template>
  <div v-if="!isDD" class="mainBox">
    <div class="loginBox">
      <!-- <div class="text">
        <p>欢迎使用</p>
        <p>丽水市政府投资信息化项目管理系统</p>
      </div> -->
      <div class="text">
      </div>
      <div class="loginTab">
        <div class="mt-50 flex justify-center">
          <span
            class="tabItem mr-20"
            :class="{ 'itemBlue':tabStatus }"
            @click="clickTab(true)"
          >扫码登录</span>
          <span
            class="tabItem"
            :class="{ 'itemBlue':tabStatus === false}"
            @click="clickTab(false)"
          >验证码登录</span>
        </div>
        <div
          v-show="tabStatus"
          class="qrcodeBox"
        >
          <div class="qrcode">
            <iframe
              width="200"
              height="430"
              :src="qrSrc"
              frameborder="0"
            ></iframe>
          </div>
          <p class="bottom">请使用{{ appName }}扫描二维码登陆</p>
        </div>
        <div
          v-show="!tabStatus"
          class="verificationCode"
        >
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="atuo"
            class="demo-ruleForm"
            status-icon
          >
            <el-form-item
              label=""
              prop="phoneNum"
            >
              <el-input
                v-model="ruleForm.phoneNum"
                :prefix-icon="UserFilled"
                placeholder="请输入手机号"
              />
            </el-form-item>
            <el-form-item
              label=""
              prop="verifyCode"
            >
              <el-input
                v-model="ruleForm.verifyCode"
                :prefix-icon="Lock"
                placeholder="请输入验证码"
              >
                <template #suffix>
                  <span v-show="countShow" class="itemBlue" @click="getVerificationCodeFunc"> 获取验证码</span>
                  <span v-show="!countShow" class="itemBlue">{{ count }}</span>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
          <el-button
            class="w-full mt-50"
            type="primary"
            @click="submitForm(ruleFormRef)"
          >
            登录
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.mainBox {
  display: flex;
  width: 100vw;
  height: 100vh;
  background: url('../../assets/images/loginBg.png') no-repeat center / cover;

  .loginBox {
    position: relative;
    width: 900px;
    height: 450px;
    margin: auto;
    border-radius: 5px;

    .text {
      width: 60%;
      height: 100%;
      position: absolute;
      background: url('../../assets/images/loginLeftPic.png') no-repeat center center;
      background-size: 100% 100%;
    }

    .loginTab {
      width: 40%;
      height: 100%;
      background-color: white;
      border-radius: 5px;
      float: right;

      .tabItem {
        cursor: pointer;
        font-weight: 500;
        color: #999999;
      }

      .itemBlue {
        cursor: pointer;
        color: rgb(67, 97, 208);
      }

      .qrcodeBox {
        margin-top: 20px;
        display: flex;
        flex-flow: column;
        align-items: center;
        justify-content: center;

        .qrcode {
          width: 200px;
          height: 200px;
          overflow: hidden;
          margin-bottom: 30px;

          iframe {
            transform: translateY(-78px);
          }
        }
      }

      .verificationCode {
        margin-top: 50px;
        padding: 0 20px 0 20px;
      }
    }
  }
}

.l403 {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  padding-top: 140px;
  box-sizing: border-box;

  .container {
    text-align: center;

    p {
      color: rgba(0, 0, 0, 0.65);
      font-size: 26px;
      margin: 23px 0 8px 0;
      padding: 0 24px;
    }

    img {
      user-select: none;
      -webkit-user-drag: none;
    }

    div {
      background-color: #e5eeff;
      border-radius: 50px;
      color: rgba(0, 0, 0, 0.65);
      padding: 5px 24px;
      font-size: 14px;
    }
  }
}
</style>
