<template>
  <div class="loginPage w-full h-full bg-white">
    <van-form show-error :show-error-message="false" @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="username" name="username" label="用户名" placeholder="用户名" :rules="rules" />
        <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码" :rules="rules" />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useLifecycle } from "@hooks/useCommon.js";
import { LOGIN_INTERFACE, USER_ID_LOGIN, WE_CHAT_LOGIN, GET_MESSAGE_LIST } from "@hooks/useApi.js";
import { addressRedirection, obtainEnterpriseWeChatParameters } from "@utility/corpWXparam"
import useShowToast from "../hooks/useToast";
import useRouterStore from "@store/useRouterStore.js";
import useInfoStore from "@store/useInfoStore.js";
import requests from "@common/requests";
const { toastLoading, toastSuccess, toastFail } = useShowToast();

const router = useRouterStore()
const userInfo = useInfoStore()
const username = ref("18122222222");
const password = ref("000000");
const rules = ref([{ required: true }]);

const isCorpWX = ref(false)
const isWX = ref(false)

useLifecycle({
  load: () => {
    verifyLoginEnvironment()
  },
  init: () => {
    verifyLoginEnvironment()
  }
});

function verifyLoginEnvironment() {
  const currentEnvironment = navigator.userAgent.toLowerCase();
  isCorpWX.value = currentEnvironment.indexOf("wxwork") > 0 ? true : false
  isWX.value = currentEnvironment.indexOf("micromessenger") > 0 ? true : false
  const href = window.location.href;
  if (href.indexOf("userId") > 0) {
    let loginUserId = href.substring(href.indexOf("userId=") + "userId=".length);
    if (loginUserId.includes('#/')) {
      loginUserId = loginUserId.substring(0, loginUserId.indexOf('#/'));
    }
    loginByUserId(loginUserId);
  } else {
    // 判断是否为企业微信授权
    if (isCorpWX.value) {
      // 判断企业微信，是否存在授权
      if (href.includes("com/?code")) {
        bindIfNessary()
      } else {
        if (href.indexOf('hasTriedAutoLogin') == -1) {
          tryAutoLogin()
        } else {
          //后台经过验证后，重定向过来带上了userId
          let loginUserId = href.substring(href.indexOf("userId=") + "userId=".length);
          if (loginUserId.includes('#/')) {
            loginUserId = loginUserId.substring(0, loginUserId.indexOf('#/'));
          }
          loginByUserId(loginUserId);
        }
      }
    }
  }
}

// 账号密码登录
function onSubmit(fromVal) {
  toastLoading('登陆中...', 0)
  requests.post(LOGIN_INTERFACE, { ...fromVal }).then(({ data }) => {
    loginProcessing(data)
  })
}

// userId登录
function loginByUserId(userId) {
  toastLoading('登陆中...', 0)
  // requests.post(USER_ID_LOGIN, { params: { userId } }).then(({ data }) => {
  requests.post(USER_ID_LOGIN, {  userId }).then(({ data }) => {
    loginProcessing(data)
  })
}

// 授权回调重定向
function tryAutoLogin() {
  window.location.href = addressRedirection()
}

function bindIfNessary() {
  const href = window.location.href;
  const requestUrl = isCorpWX.value ? '/wxcorp/bindCorpWeiXin' : isWX ? '/wechat/bindWeiXin' : '';
  if (requestUrl.length > 0) {
    //url包括 com/?code 证明为从微信跳转回来的
    if (href.includes("com/?code")) {
      const url = href; //vue自动在末尾加了 #/ 符号，截取去掉
      const jingPosit = url.indexOf("com/") + 4; //获取域名结束的位置
      const urlRight = url.substring(jingPosit, url.indexOf('#/') !== -1 ? url.indexOf('#/') : url.length); //url右侧部分
      const code = urlRight.substring('?code='.length, urlRight.indexOf('&state='));
      const passUserId = urlRight.substring(urlRight.indexOf('&state=') + '&state='.length);
      if (passUserId == '0') {
        requests.get(WE_CHAT_LOGIN, { code }).then((res) => {
          if (res.data != null && ((isWX.value && res.data.wxOpenid != undefined)
            || (isCorpWX.value && res.data.corpwxUserid != undefined))) {
            loginProcessing(res.data)
            window.location.href = '/#/index';
          }
        })
      } else {
        //绑定微信账号的回调, 调用后台接口，注册用户
        requests.get(requestUrl, { code, userId: passUserId }).then((res) => {
          if (res == null) {
            toastFail('绑定失败')
            return
          }
          if (res.data != null && ((isWX.value && res.data.wxOpenid != undefined)
            || (isCorpWX.value && res.data.corpwxUserid != undefined))) {
            loginProcessing(res.data)
            window.location.href = '/#/my/center';
          }
        })
      }
    }
  }
}

// 登陆前的处理
function loginProcessing(data = {}) {
  sessionStorage.setItem('token', data.id)
  userInfo.updateState({
    userInfo: data,
    token: data.id,
    modularList: separateRouting(data.moduleList || []),
    permissionList: data.functionList || []
  })
  router.switchTabBar({
    pathName: 'home',
    success: function () {
      if (isCorpWX.value) {
        obtainEnterpriseWeChatParameters(data)
      }
      toastSuccess('登陆成功')
      setTimeout(() => {
        getMessageList()
      }, 500)
    }
  })
}

function getMessageList() {
  requests.post(GET_MESSAGE_LIST, {}).then(({ data = [] }) => {
    userInfo.updateState({
      numberOfMessages: data.filter((item) => !item.checked)?.length || ''
    })
  })
}

function separateRouting(list = []) {
  return (list || []).filter(item => item.isMenu && !(['/team', '/system', '/analysis', '/corpreport'].includes(item.path)))
}

</script>

<style lang="scss" scoped></style>
