<!--
 * @Author: wanglj wanglijie@dashoo.cn
 * @Date: 2025-03-11 18:02:10
 * @LastEditors: wanglj wanglijie@dashoo.cn
 * @LastEditTime: 2025-03-21 10:12:40
 * @FilePath: \vant-demo-master\vant\vue3-ts\src\view\login\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="login-container">
    <header>
      <div class="logo mt20 mb20">
        <img width="100" src="../../assets/img/logo-login.png" />
        <h4>临床医学公共实验中心</h4>
      </div>
      <van-field v-model="state.form.userName" placeholder="请输入用户名" />
      <van-field v-model="state.form.password" type="password" placeholder="请输入密码" class="mt10" />
      <!-- <van-row justify="space-between">
        <van-button size="mini" round class="mt10 w50">找回密码</van-button>
        <van-button size="mini" round class="mt10 w50">找回密码</van-button>
      </van-row> -->
      <van-button type="primary" round class="mt10" @click="onSignIn">登录</van-button>
      <van-button round class="mt10" @click="onRegister">注册</van-button>
      <!-- <van-button round class="mt10" @click="blueTooth">蓝牙</van-button> -->
    </header>
    <footer>
      <img width="124" src="../../assets/img/slogan.png" />
    </footer>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, reactive } from 'vue'
  import to from 'await-to-js'
  import { useLoginApi } from '/@/api/login/index'
  import { Local } from '/@/utils/storage'
  import crypto from 'sm-crypto'
  import { useRouter, useRoute } from 'vue-router'
  import { storeToRefs } from 'pinia'
  import { useUserInfo } from '/@/stores/userInfo'
  import { showDialog } from 'vant'
  const router = useRouter()
  const route = useRoute()
  const sm3 = crypto.sm3
  const loginApi = useLoginApi()
  const storesUseUserInfo = useUserInfo()
  const { userInfos, openId } = storeToRefs(storesUseUserInfo)
  const state = reactive({
    loading: {
      signIn: false
    },
    form: {
      userName: '',
      password: ''
    }
  })
  const onSignIn = async () => {
    state.loading.signIn = true
    const params = JSON.parse(JSON.stringify(state.form))
    params.password = sm3(params.password)
    params.openId = openId.value
    // params.password = (params.password)
    // sm3
    console.log(openId.value, 'openIdddddddddddd');
    
    const post = params.openId ? loginApi.weChatLogin : loginApi.signIn
    const [err, res]: ToResponse = await to(post(params))
    if (err) {
      state.loading.signIn = false
      return
    }
    // 存储 token 到浏览器缓存
    Local.set('token', res?.data.token)
    router.push('/home')
  }
  const openIdLogin = async () => {
    const [err, res]: ToResponse = await to(loginApi.weChatLoginOpenId({ openId: openId.value }))
    if (err) return
    Local.set('token', res?.data.token)
    router.push('/home')
  }
  const onRegister = () => {
    router.push('/register')
  }
  const blueTooth = async () => {
    try {
      // 请求蓝牙设备
      // @ts-ignore
      if (!navigator?.bluetooth?.requestDevice) {
        showDialog({
          message: '当前浏览器不支持蓝牙功能，请升级浏览器版本或更换浏览器。',
          confirmButtonText: '确定'
        })
      }
      // @ts-ignore
      const device = await navigator.bluetooth.requestDevice({
        filters: [{ services: ['generic_access'] }],
        optionalServices: [],
        acceptAllDevices: false
      })
      // 连接到设备
      const server = await device.gatt.connect()

      // 获取服务
      const service = await server.getPrimaryService('generic_access')

      // 获取特征
      const characteristic = await service.getCharacteristic('device_name')

      // 读取特征值
      const value = await characteristic.readValue()

      // 将特征值转换为字符串
      const decoder = new TextDecoder('utf-8')
      const deviceName = decoder.decode(value)

      console.log('Device Name:', deviceName)
    } catch (error) {
      console.error('Error:', error)
    }
  }
  onMounted(async () => {
    const code: string = route.query.code ? route.query.code.toString() : ''
    if(code) {
      await storesUseUserInfo.setOpenId(code)
      openIdLogin()
    }
  })
</script>

<style lang="scss" scoped>
  .login-container {
    height: calc(100% - 80px);
    width: 300px;
    display: flex;
    margin: 0 auto;
    padding: 40px 0;
    flex-direction: column;
    .logo {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    header {
      display: flex;
      flex-direction: column;
      flex: 1;
    }
    footer {
      flex: 0 0 30px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    h4 {
      text-align: center;
      font-size: 24px;
      margin: 40px 0;
    }
    .w50 {
      width: 120px;
      background-color: #e8effc;
    }
    .van-cell {
      background-color: #f3f5f6;
      border-radius: 22px;
      overflow: hidden;
      :v-deep .van-van-field__control {
        text-align: center;
      }
      :deep(.van-van-field__control) {
        text-align: center;
      }
    }
  }
</style>
