<template>
  <view class="u-p-l-50 u-p-r-50 u-p-t-30">
    <u-form :model="model" ref="loginForm" :rules="mixinInit.rules" :error-type="mixinInit.errorType">
      <u-form-item :label-position="mixinInit.labelPosition" label="用户名" prop="account" label-width="150">
        <u-input :border="mixinInit.border" placeholder="请输入用户名" v-model="model.account" type="text"></u-input>
      </u-form-item>
      <u-form-item :label-position="mixinInit.labelPosition" label="密码" prop="password" label-width="150">
        <u-input :password-icon="true" :border="mixinInit.border" type="password" v-model="model.password" placeholder="请输入密码">
        </u-input>
      </u-form-item>
      <view class="flex flex-nowrap">
        <view class="flex-sub"></view>
        <view class="u-m-t-30 u-font-12 text-gray-400" @click="openPage('/pages/user/forgetPassword')">忘记密码</view>
      </view>
    </u-form>

    <view class="u-m-t-50">
      <u-button @click="submit" type="primary">立即登录</u-button>
    </view>

    <view class="flex justify-between">
      <view class="u-m-t-30" style="color: #2885ED;" @click="openPage('/pages/user/rigister')"> 新用户注册</view>
      <view class="u-m-t-30" style="color: #2885ED;" @click="openPage('/pages/user/login')">手机号登录 </view>
    </view>

    <view style="margin-top: 200rpx;text-align: center; color: #999999;font-size: 35rpx;">
      快速登录
    </view>
    <view style="text-align: center; margin-top: 20rpx;">
      <image src="/common/img/weixinIcon.png" mode="" style="width: 85rpx;height: 85rpx;"></image>
    </view>
  </view>
</template>

<script setup>
  import { ref, computed } from 'vue';
  import { useStore } from 'vuex';
  import userMixin from '@/hooks/user/userMixin'

  const store = useStore();
  const mixinInit = userMixin();
  const userInfo = uni.$storage.getStorageSync('user');
  const user = ref({});
  const loginForm = ref(null);
  const model = ref({
    account: '',
    password: ''
  })


  if (userInfo) {
    user.value = JSON.parse(userInfo);
  }

  const submit = () => {
    loginForm.value.validate(data => {
      console.log(data);
    });
  }

  async function login() {
    try {
      uni.$ui.showLoading();
      if (account.value === user.value.account) {
        uni.$ui.showToast('当前账户已登录');
      } else {
        const params = ref({
          client: 1,
          data: {
            identifier: account.value,
            credential: password.value,
          },
          type: 3,
        });

        let res = await uni.$u.api.signin(params.value);
        store.commit('user/setToken', res.token);
        store.commit('user/setUser', res);
        uni.$storage.setStorageSync('anyringToken', res.token || '');
        uni.$storage.setStorageSync('user', JSON.stringify(res));
      }

      uni.navigateTo({
        url: '/pages/index/index'
      });

      uni.$ui.hideLoading();
    } catch (error) {
      uni.$ui.hideLoading();
      uni.$ui.showToast(error);
    }
  }
</script>

<style>
</style>
