<template>
  <view class="container">
    <view class="login-icon">
      <image class="login-img" src="../../image/icon/login-background.svg"></image>
    </view>
    <view class="login-from">
      <view class="inputView">
        <!--账号-->
        <input class="inputText" placeholder="账号" v-model="username" />
        <!--密码-->
        <input class="inputText" placeholder="密码" v-model="password" password="true" />
      </view>
      <view class="loginBtnView">
        <!--按钮-->
        <button class="loginBtn" type="primary" @tap="login">登录</button>
        <button class="loginBtn" type="secondary" bindtap="visitor">访客申请</button>
      </view>
    </view>
  </view>
</template>

<script>
import Taro from '@tarojs/taro'
import md5 from 'blueimp-md5'

import './login.css'

export default {
  data() {
    return {
      ...Taro.getApp().globalData,
      username: '',
      password: ''
    }
  },
  methods: {
    login() {
      if (this.username == '' || this.password == '') {
        Taro.showToast({
          title: "请完善登录信息",
          icon: 'error',
          duration: 2000
        })
      } else {
        let passwordHash = md5(this.password);
        Taro.showLoading({ title: '加载中' })
        Taro.request({
          url: `${this.baseUrl}/user/login`,
          method: "POST",
          header: {
            "Content-Type": "application/x-www-form-urlencoded" //用于post
          },
          data: {
            username: this.username,
            password: passwordHash,
          },
          success: function (d) {
            Taro.hideLoading()
            let result = d.data;
            if (result.success) {
              // 登录成功
              Taro.setStorageSync("userInfo", result.data.userInfo);
              console.log("userInfo", Taro.getStorageSync("userInfo"))
              Taro.switchTab({
                url: '/pages/index/index'
              })
            } else {
              Taro.showToast({
                title: result.msg,
                icon: 'error',
                duration: 2000
              })
            }
          },
          fail: function () {
            Taro.hideLoading()
            Taro.showToast({
              title: "请求失败",
              icon: 'error',
              duration: 2000
            })
          }
        })
      }
    }
  }
}
</script>
