<template>
    <div class="login-container">
        <banner hideLg="hideLg"></banner>
        <div class="login-img fl"><img src="../../images/loginImg.png"/></div>
        <div class="login-box">
            <!-- <div class="box-le"><img src="../../images/left.jpg"/></div> -->
            <div class="box-ri">
                <div class="title-box clearfix"> <h3 class="login-title fl">登录</h3> <h4 class="num fr" @click="toRegister">立即注册</h4></div>
               
                <div class="ri-center">
                    <el-form :model="ruleForm2" :rules="rules2" ref="ruleFormReg">
                        <el-form-item prop="tel">
                            <el-input v-model="ruleForm2.tel" name="username" autocomplete="off" maxlength="11"
                                      placeholder="请输入用户名或手机号"
                                      clearable class="ri-tel" @keyup.enter.native="submitForm('ruleForm2')"
                                      ref="username"></el-input>
                        </el-form-item>
                        <div style="height: 20px;"></div>
                        <el-form-item prop="pwd">
                            <el-input v-model="ruleForm2.pwd" name="password" autocomplete="off" maxlength="16"
                                      placeholder="请输入密码"
                                      clearable type="password" class="ri-pwd"
                                      @keyup.enter.native="submitForm('ruleForm2')" ref="password"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <!-- <span class="num" @click="toRegister">注册账号</span> -->
                            <span class="pwd" @click="toForgetPsw">忘记密码?</span>
                        </el-form-item>
                        <el-form-item>
                            <el-button plain v-if="otherCor" >登录</el-button>
                            <el-button ref="btn" v-else class="otherCor" plain @click="submitForm('ruleForm2')">登录
                            </el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </div>{{hideLg}}
        <copy-right-info v-if="!hideLg"></copy-right-info>
    </div>
</template>

<script>
  import Vue from 'vue';
  import banner from '../common/Banner.vue';
  import copyRightInfo from '../common/CopyRightInfo.vue';
  import api from '../../api/index.js';
  import './login.less';
  import md5 from 'js-md5'
  const qs = require('qs');
  export default {
    name: 'Login',
    data() {
      //手机号码验证
      var myreg = /^1[0-9]{10}$/;
      //密码验证 纯字母纯英文
      var numreg = /^(?![0-9]+$)(?![a-zA-Z]+$)/;
      //密码验证 密码长度
      var lengreg = /^[0-9A-Za-z]{6,16}$/;
      var validatePass = (rule, value, callback) => {
        // if(isNaN(value) == false){   //手机号
        // 正常情况

        if (value.trim() == '') {
          callback(new Error('用户名不能为空'));
          this.$refs.username.value = "";
        }
        // 手机号
        if (isNaN(value) == false) {
          if (value.length !== 11 || !myreg.test(value)) {
            callback(new Error('手机号格式有误'));
          } else {
            callback();
          }
        } else if (isNaN(value) == true) {
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value.trim() == '') {
          callback(new Error('密码不能为空'));
          this.$refs.password.value = "";
        } else if (value.length < 6) {
          callback(new Error('密码长度应为6位至16位之间'));
        } else if (!numreg.test(value)) {
          callback(new Error('密码不能为纯数字或纯英文'));
        } else {
          callback();
        }
      };
      return {
        otherCor: true,
        hideLg:false,
        ruleForm2: {
          tel: '',
          pwd: ''
        },
        rules2: {
          tel: [{
            required: true,
            validator: validatePass,
            trigger: 'blur'
          }],
          pwd: [{
            required: true,
            validator: validatePass2,
            trigger: 'blur'
          }],
        }
      };
    },
    mounted() {
      this.hideLg = window.location.hash.indexOf("hideLg=")>-1;
      if (window.history && window.history.pushState) {
        history.pushState(null, null, document.URL);
        window.addEventListener('popstate', function () {
            history.pushState(null, null, document.URL);
        });
      }
    },
    computed: {
      nextButton() {
        const {
          tel,
          pwd
        } = this.ruleForm2;
        return {
          tel,
          pwd
        }
      }
    },
    watch: {
      nextButton: {
        handler: function (val) {
          if (val.tel.trim() && val.pwd.trim()) {
            this.otherCor = false;
          } else {
            this.otherCor = true;
          }
        },
        deep: true
      }
    },
    methods: {
      CalcuMD5(password){
        // password = password.toUpperCase();
        password = md5(password);
        return password;
      },
      submitForm: function () {
        const username = this.ruleForm2.tel;
        const password = this.CalcuMD5(this.ruleForm2.pwd);
        let params = {
          "username": username,
          "password": password
        }
        //重新登录清空原有token;
        localStorage.removeItem('token');
        this.$refs.ruleFormReg.validate((valid) => {
          if (valid) {
            api.loginMess(params).then((res) => {
              if (res.status == 200) {
								// console.log(res)
                if (res.data.code == '10020000') { //未注册
                  // this.$message.error(res.data.msg);
									this.$message.error("该账号或手机号未注册！")
                } else if (res.data.code == '10020001') { //密码错误
                  this.$message.error(res.data.msg);
                } else if (res.data.code == '0') {
                  const token = JSON.stringify(res.data.data);
                  localStorage.setItem("token", token);
                  this.$message({
                    message: '登录成功！',
                    type: 'success',
                    duration: 1000,
                    onClose: function () {
                      const type = res.data.data.type;
                      if (type == 0) {
                        this.$router.push({
                          path: '/user'
                        });
                      } else if (type == 1) {
                        this.$router.push({
                          path: '/admin'
                        });
                      }
                    }.bind(this)
                  });
                }
              }
            }).catch((err) => {
              console.log(err);
            })
          } else {
            console.log('faild')
            return false;
          }
        });
      },
      toRegister() { //点击注册
        this.$router.push({
          path: '/register'
        });
      },
      toForgetPsw() {//忘记密码
        this.$router.push({
          path: '/forgetPassword'
        });
      }
    },
    components: {
      'banner': banner,
      'copyRightInfo': copyRightInfo
    },
  }
</script>
