<template>
  <view class="u-p-l-50 u-p-r-50 u-p-t-30">
    <u-form :model="form" ref="loginForm" :error-type="['message']">
      <u-form-item label="用户名" prop="account" label-width="150">
        <u-input placeholder="请输入用户名" v-model="form.account" type="text"></u-input>
      </u-form-item>
      <u-form-item label="密码" prop="password" label-width="150">
        <u-input :password-icon="true" type="password" v-model="form.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;" @click="mixinInit.handleWxLogin">
      <image src="/common/img/weixinIcon.png" mode="" style="width: 85rpx;height: 85rpx;"></image>
    </view>
  </view>
</template>

<script setup>
  import { ref, computed, reactive } from 'vue';
  import { useStore } from 'vuex';
  import { onReady} from '@dcloudio/uni-app';
  import userMixin from '@/hooks/user/userMixin'

  const store = useStore();
  const mixinInit = userMixin();
  const loginForm = ref(null);

  const form = reactive({
    account: '',
    password: ''
  })

  onReady(() => {
    loginForm.value.setRules(mixinInit.rules);
  });

  const submit = () => {
    loginForm.value.validate(valid => {
      if (valid) {
        login()
      }
    });
  }

  async function login() {
    uni.$ui.showLoading();
    try {
      // #ifdef H5
      const client = 0;
      // #endif
      // #ifdef APP-PLUS
      const client = 1;
      // #endif
      const params = reactive({
        client: client,
        data: {
          identifier: form.account,
          credential: form.password,
        },
        type: 3,
      });

      let res = await uni.$u.api.signin(params);
      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.$ui.hideLoading();

      uni.navigateTo({
        url: '/pages/index/index'
      });
    } catch (error) {
      uni.$ui.hideLoading();
      uni.$ui.showToast(error);
    }
  }

  function openPage(url) {
    uni.navigateTo({
      url: url
    })
  }
</script>

<style>
</style>
