<template>
  <div class="login-form-container">
    <img class="image-corner" src="" v-show="qrCodeLoginMode" @click="qrCodeLoginMode = false"/>
    <img class="image-corner" src="" v-show="!qrCodeLoginMode" @click="qrCodeLoginMode = true"/>
    <img src="" style="margin-bottom:45px;"/>
    <el-form ref="loginForm" :model="loginForm" v-show="!qrCodeLoginMode" :rules="rules">
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          placeholder="此处输入用户名（手机号）">
          <template slot="prepend">用户名</template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          maxlength="18"
          placeholder="此处输入密码"
          @keyup.enter.native="submitLoginForm">
          <template slot="prepend">密&nbsp;&nbsp;&nbsp;码</template>
        </el-input>
      </el-form-item>
      <el-button type="primary" class="login-btn" @click="submitLoginForm">登&nbsp;&nbsp;录</el-button>
    </el-form>
    <div v-show="qrCodeLoginMode">
      <img :src="qrCodeUrl" width="210" height="210"/>
      <div class="tips-container">
        <div>手机扫码&nbsp;&nbsp;安全登录</div>
        <div>使用<span class="tips-emphasis">微信</span>扫描二维码</div>
      </div>
    </div>
  </div>
</template>

<script>
  /* eslint-disable indent,quotes,eqeqeq */
  import axios from 'axios'
  export default {
    name: "login",
    data() {
      const validateUsername = (rule, value, callback) => {
        const validValue = value ? value.replace(/\s/g, "").replace(/&nbsp;/ig, "") : value
        if (!validValue) {
          return callback(new Error('请填写用户名'))
        }
        const illegalChar = /[\uFF00-\uFFFF]/
        if (illegalChar.test(value)) {
          return callback(new Error('用户名中不能使用全角字符，请重新填写'))
        } else {
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (value.length < 6) {
          return callback(new Error('密码长度应至少在6位或以上'))
        } else {
          callback()
        }
      }
      return {
        qrCodeUrl: '',
        qrCodeLoginMode: false,
        loginForm: {
          username: '',
          password: ''
        },
        rules: {
          username: [
            { validator: validateUsername, trigger: 'change' }
          ],
          password: [
            { validator: validatePassword, trigger: 'change' }
          ]
        }
      }
    },
    methods: {
      getCurrentProfile: function() {
        try {
          const profileStr = localStorage.getItem('profile')
          return JSON.parse(profileStr)
        } catch (err) {
          return null
        }
      },
      toIndexPage() {
        window.location.href = "http://127.0.0.1:8080/index"
      },
      submitLoginForm: function() {
        const form = this.$refs['loginForm']
        var self = this
        form.validate((valid) => {
          if (valid) {
            if (form) {
              self.sendLoginRequest()
            }
          } else {
            // console.log('验证未通过');
            return false
          }
        })
      },
      sendLoginRequest: function() {
        const loading = this.$loading({
          lock: true,
          text: '正在登录',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.2)'
        })
        var self = this
        axios({
          url: '/integral.php/verify/verify_login',
          method: 'post',
          data: this.loginForm,
          transformRequest: [(data) => {
            const paramArray = new Array()
            for (const it in data) {
              paramArray.push(encodeURIComponent(it) + '=' + encodeURIComponent(data[it]))
            }
            return paramArray.join("&")
          }],
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }).then((response) => {
          let message = ""
          let status = 0
          if (response.status == 200) {
            const data = response.data
            status = isNaN(data.status) ? 0 : parseInt(data.status)
            switch (status) {
              case 1:
                message = "登录成功"
                localStorage.setItem('profile', JSON.stringify(data.employee_info))
                localStorage.setItem('begin', new Date().getTime())
                localStorage.removeItem('activeMenuIndex')
                break
              case 2:
                message = data.info ? data.info : "该用户在多个站点中使用，请选择要登录的站点"
                break
              default:
                message = data.info ? data.info : "登录失败"
            }
          } else {
            message = "服务器出现问题"
          }
          loading.close()
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          const form = self.$refs['loginForm']
          form.clearValidate()
          if (status == 1) {
            setTimeout(() => self.toIndexPage(), 1000)
          } else if (status == 2) {

          }
        }).catch(function(error) {
          loading.close()
          console.log(error)
        })
      }
    },
    created() {
      const profile = this.getCurrentProfile()
      if (profile && profile.username) {
        this.loginForm.username = profile.username
      }
      localStorage.removeItem('profile')
    }
  }
</script>

<style>
  .login-form-container {
    position: relative;
    background-color: #FFFFFF;
    border-radius: 5px;
    text-align: center;
    padding: 20px 25px;
  }

  .image-corner {
    position: absolute;
    top: 5px;
    right: 5px;
    cursor: pointer;
  }

  .login-btn {
    width: 100%;
    margin-top: 15px;
    margin-bottom: 10px;
    font-size: 15px;
  }

  .tips-container {
    margin-top: 20px;
    margin-bottom: 10px;
    font-size: 14px;
    color: #C7C7C7;
  }

  .tips-emphasis {
    color: #65CEA7;
  }
</style>
