<script setup>
  import { reactive } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { useUI } from '@/utils/use-ui'
  import { reLaunch, navigateTo } from '@/utils/router'
  import { userLogin, getIpBlack } from '@/api'
  import { useTokenStore } from '@/stores/token'
  import { useUserStore } from '@/stores/user'

  const { showToast, showDialog } = useUI()
  const { setToken } = useTokenStore()
  const { fetchUserInfo } = useUserStore()

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

  const onLogin = async () => {
    if (!formData.agreement) {
      showToast('请同意协议')
      return
    }
    const show = await getIpBlack()
    if (show.data.data) {
      const res = await userLogin({
        account: formData.username,
        password: formData.password
      })
      setToken(res.token)
      await fetchUserInfo()
      reLaunch('/TUIKit/components/TUIConversation/index')
    } else {
      showDialog('提示', '当前账号或者IP已被限制登录！', false)
    }
  }

  const onRegister = () => {
    reLaunch('/pages/login/phone-register/phone-register')
  }

  const onTopRight = () => {
    navigateTo('/pages/login/forgot-password/forgot-password')
  }

  onLoad(e => {
    console.log('接收参数，返回对应页面的时候使用', e)
  })
</script>

<template>
  <view class="login">
    <view class="top-nav">
      <text class="title-left">登录</text>
      <text class="title-right" @click="onTopRight">忘记密码</text>
    </view>
    <div class="input-wrapper">
      <cb-input
        v-model="formData.username"
        placeholder="请输入手机号/邮箱"
      ></cb-input>
      <cb-input
        v-model="formData.password"
        type="password"
        icon="2"
        placeholder="请输入密码"
      ></cb-input>
      <agreement-checkbox v-model="formData.agreement" />
      <cb-button
        class="bottom-btn"
        :disabled="
          !formData.username || !formData.password || !formData.agreement
        "
        @click="onLogin"
      >
        登录
      </cb-button>
      <view class="bottom-text">
        <text class="text">还没账号？</text>
        <text class="text" @click="onRegister">去注册</text>
      </view>
    </div>
  </view>
</template>

<style lang="scss" scoped>
  @import '/styles/login.scss';
  .login {
    .bottom-btn {
      margin: 160rpx 0 64rpx;
    }
  }
</style>
