<template>
  <div>
    <div class="box">
      <div class="contentBox">
        <van-row justify="center">
          <van-col>
            <van-image
                width="100px"
                height="100px"
                :src="logo"
            />
          </van-col>
        </van-row>
        <van-form style="width: 90vw;margin: 30px 0 0 5vw;">
          <van-cell-group inset>
            <van-field
                v-model="loginFormData.username"
                label="用户名"
                placeholder="请输入用户名"
                size="large"
            />
            <van-field v-model="unencrypted" label="密码" placeholder="请输入密码" size="large"/>
            <van-field v-model="loginFormData.captcha" placeholder="请输入验证码" size="large">
              <template #button>
                <van-image :src="captchaPicture" width="25vw" height="4vh" @click="getCaptcha"/>
              </template>
            </van-field>
          </van-cell-group>
        </van-form>
        <van-row style="margin-top: 4vh">
          <van-col :span="20" :offset="2">
            <van-button type="primary" size="large" @click="userLogin">登录</van-button>
          </van-col>
        </van-row>
      </div>
    </div>
  </div>
</template>

<script setup>
import { captcha, routerPublicKey, register } from '@/api/login.js'
import logo from '@/assets/logo.png'
import { JSEncrypt } from 'jsencrypt'
import { useUserStore } from '@/pinia/modules/user.js'
const router = useRouter()

const userStore = useUserStore()

defineOptions({
  name: 'Login',
})
onMounted(() => {
  getCaptcha()
  getPublicKey()
})
// 未加密密码
const unencrypted = ref('')
// 登录数据
const loginFormData = reactive({
  username: '',
  password: '',
  captcha: '',
  captchaId: ''
})
// 验证码图片
const captchaPicture = ref('')
// 获取验证码
const getCaptcha = () => {
  captcha().then(res => {
    if (res.code === 0) {
      captchaPicture.value = res.data.picPath
      loginFormData.captchaId = res.data.captchaId
    }
  })
}

// 公钥
const publicKey = ref('')
// 获取公钥
const getPublicKey = () => {
  routerPublicKey().then(res => {
    if (res.code === 0) {
      publicKey.value = res.data.publicKey
    }
  })
}

// 登录
const userLogin = () => {
  // 密码rsa加密
  let encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey.value)
  loginFormData.password = encryptor.encrypt(unencrypted.value)
  // 执行登录
  register(loginFormData).then(res => {
    if (res.code === 0) {
      const data = res.data
      userStore.updateInfo(res.data)
      router.push({path: '/navigation'})
    }
  })
}

</script>

<style scoped lang="scss">
.box {
  width: 100vw;
  height: 100vh;
  position: fixed;
  background-color: #f7f8fa;
  display: flex;
  align-items: center;
  justify-content: center;
  .contentBox{
    width: 100vw;
    height: 50vh;
  }
}
</style>
