<template>
  <app-statusbar class="login">
    <div class="login-logo">铁合金掌上行</div>
    <Form class="login-form" @submit="formSubmit">
      <CellGroup>
        <Field v-model="user.LoginID" name="account" label="用户名" size="large" placeholder="请输入用户名"
          :rules="[{ required: true, message: '请输入用户名' }]" />
        <Field v-model="user.LoginPWD" name="password" type="password" label="密码" size="large" placeholder="请输入密码"
          :rules="[{ required: true, message: '请输入密码' }]" autocomplete="off" />
      </CellGroup>
      <div class="button-link">
        <span @click="navigationTo('register')">用户注册</span>
        <span @click="navigationTo('forget')">忘记密码</span>
      </div>
      <div class="button-submit">
        <Button type="primary" native-type="submit" round block>登录</Button>
      </div>
    </Form>
    <div class="login-footer">
      <Checkbox shape="square" icon-size=".32rem" v-model="checked">我已阅读并同意</Checkbox>
      <span @click="navigationTo('rules-zcxy')" style="color:#E92020">《用户注册协议》</span>
      <span>和</span>
      <span @click="navigationTo('rules-yhkhfxgzs')" style="color:#E92020">《用户开户风险告知书》</span>
      <span>和</span>
      <span @click="navigationTo('rules-yszc')" style="color:#E92020">《隐私政策》</span>
    </div>
  </app-statusbar>
</template>

<script lang="ts" setup>
import { shallowRef } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Button, Field, CellGroup, Form, Checkbox, Toast } from 'vant'
import { fullloading } from '@/utils/vant'
import { useAuth } from '@/business/auth'
import { useNavigation } from '@/hooks/navigation'
import service from '@/services'

const { routerTo } = useNavigation()
const { user, login } = useAuth()
const route = useRoute()
const router = useRouter()
const checked = shallowRef(false) // 是否同意协议管理

// 导航跳转
const navigationTo = (name: string) => {
  fullloading((hideLoading) => {
    service.onReady().then(() => {
      hideLoading()
      routerTo(name)
    }).catch(() => {
      Toast.fail('初始化失败')
    })
  })
}

const formSubmit = () => {
  if (checked.value) {
    fullloading((hideLoading) => {
      login().then(() => {
        hideLoading()
        const redirect = route.query.redirect
        if (redirect) {
          router.replace(redirect.toString())
        } else {
          router.replace('/')
        }
      }).catch((err) => {
        Toast.fail(err)
      })
    }, '登录中...')
  } else {
    Toast('请先同意使用条款')
  }
}
</script>

<style lang="less" scoped>
@import './index.less';
</style>