<script setup lang="ts">
import { reactive } from "vue"
import CryptoJS from "crypto-js";
import { getUserInfo, login } from "~/service/modules/login"
import { CellGroup, Cell, Field, Button, Form, showLoadingToast, closeToast, showToast, allowMultipleToast } from "vant"
import { removeAuthToken, setAuthToken } from "~/utils/auth";
import { useRouter } from "vue-router"

import { useTitle } from "@vueuse/core"

const router = useRouter()

allowMultipleToast()

const formData = reactive({
  username: '',
  password: ''
})


function getParameterByName(name) {
  var url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
  var results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

async function onLogin() {
  try {
    showLoadingToast({ message: '登录中...', forbidClick: true })
    const { code, data } = await login(formData)
    closeToast()

    if (code == 0) {
      if (!['265', '264', '132', '107', '55', '81', '95'].includes(String(data.id))) {
        showToast({ message: '账号存在,但该账号不能使用本系统', duration: 2000 })
      } else {
        setAuthToken(data.token)
        router.push('/home')
      }
    }
  } catch (err) {
    console.log(err)
    closeToast()
  }
}

onMounted(async () => {
  const obj = getParameterByName('t')

  if(obj){
    removeAuthToken()
    showLoadingToast({ message: '获取用户信息...', forbidClick: true })
    const decData = CryptoJS.enc.Base64.parse(obj).toString(
      CryptoJS.enc.Utf8
    );

    const decJson = CryptoJS.AES.decrypt(decData, 'key123').toString(
      CryptoJS.enc.Utf8
    );

    const { token } = JSON.parse(decJson);
    // alert(token)
    // return
    const result = await getUserInfo({ token })

    closeToast()

    if (!['265', '264', '132', '107', '55', '81', '95', '109', '36'].includes(String(result.data.id))) {
      showToast({ message: '账号存在,但该账号不能使用本系统', duration: 2000 })
    } else {
      setAuthToken(token)
      router.push('/home')
    }
  }
})


useTitle('登录')
</script>

<template>
  <div class="w-full h-full relative overflow-hidden">
    <!-- <NavBar title="登录" /> -->
    <Form class="max-w-[95%] w-[400px] fixed top-[300px] left-[50%]" style="transform: translate(-50%, -50%)"
      @submit="onLogin">
      <CellGroup>
        <Cell>
          <Field v-model="formData.username" label="手机号" placeholder="请输入手机号" maxlength="11"
            :rules="[{ required: true, message: '请填写手机号', trigger: 'change' }]" />
        </Cell>

        <Cell>
          <Field v-model="formData.password" label="密码" placeholder="请输入密码" type="password"
            :rules="[{ required: true, message: '请填写用户名', trigger: 'change' }]" />
        </Cell>

        <Cell class="mt-[16px]">
          <Button block type="primary" native-type="submit">登录</Button>
        </Cell>
      </CellGroup>
    </Form>
  </div>
</template>
