<template>
  <div class="login-container">
    <!-- <banner></banner> -->
    <div class="login-img fl">
      <img src="../../images/leftimg.png" />
    </div>
    <div class="login-wrap-r">
      <div class="login-box">
        <div class="box-ri">
          <div class="title-box clearfix">
            <img src="../../images/logomax2.png" alt="朗通logo" />
            <h3 class="login-title">医院知识库后台管理系统</h3>
          </div>
          <div class="ri-center">
            <el-form :model="ruleForm2" :rules="rules2" ref="ruleFormReg">
              <p class="personTip">用户名</p>
              <div class="nameIcon">
                <img src="../../images/name.png" />
              </div>

              <el-form-item prop="tel">
                <el-input
                  v-model.trim="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: 16px;"></div>
              <p class="personTip">密码</p>
              <div class="nameIcon">
                <img src="../../images/password.png" />
              </div>

              <el-form-item prop="pwd">
                <el-input
                  v-model.trim="ruleForm2.pwd"
                  name="password"
                  autocomplete="off"
                  maxlength="20"
                  placeholder="请输入密码"
                  clearable
                  type="password"
                  class="ri-pwd"
                  @keyup.enter.native="submitForm('ruleForm2')"
                  ref="password"
                >
                </el-input>
              </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>
    </div>
    <!-- <copy-right-info></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';

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 = '';
      } else {
        callback();
      }
      // // 手机号
      // 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,
      ruleForm2: {
        tel: '',
        pwd: ''
      },
      rules2: {
        tel: [
          {
            required: true,
            validator: validatePass,
            trigger: 'change'
          }
        ],
        pwd: [
          {
            required: true,
            validator: validatePass2,
            trigger: 'change'
          }
        ]
      }
    };
  },
  mounted() {
    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() {
      if (this.otherCor) {
        return;
      }
      this.otherCor = true;
      const username = this.ruleForm2.tel;
      const password = this.CalcuMD5(this.ruleForm2.pwd);
      let params = {
        username: username,
        password: password
      };
      this.$message.closeAll();
      //重新登录清空原有token;
      localStorage.removeItem('token');
      this.$refs.ruleFormReg.validate(valid => {
        if (valid) {
          api
            .loginMess(params)
            .then(res => {
              if (res.status == 200) {
                if (res.data.code == '10020000') {
                  //未注册
                  this.$refs.ruleFormReg.clearValidate();
                  // 手动操作校验、展示登录错误信息
                  this.rules2.tel.push({
                    // js新增一个自定义校验
                    validator: (rule, value, callback) => {
                      callback('用户名未注册');
                    },
                    trigger: 'change'
                  });
                  this.$refs.ruleFormReg.validateField('tel'); // 手动校验
                  this.rules2.tel = this.rules2.tel.slice(0, 1); // 删除校验
                } else if (res.data.code == '10020001') {
                  //密码错误
                  this.$refs.ruleFormReg.clearValidate();
                  // 手动操作校验、展示登录错误信息
                  this.rules2.pwd.push({
                    // js新增一个自定义校验
                    validator: (rule, value, callback) => {
                      callback('密码输入错误!');
                    },
                    trigger: 'change'
                  });
                  this.$refs.ruleFormReg.validateField('pwd'); // 手动校验
                  this.rules2.pwd = this.rules2.pwd.slice(0, 1); // 删除校验
                } else if (res.data.code == '0') {
                  const token = JSON.stringify(res.data.data);
                  localStorage.setItem('token', token);
                  const uesrId = JSON.stringify(res.data.data.type);
                  localStorage.setItem('uesrId', uesrId);
                  this.$message({
                    message: '登录成功！',
                    type: 'success',
                    duration: 1000,
                    onClose: function() {
                      const type = res.data.data.type;
                      if (type == 0) {
                        this.$router.push({
                          path: '/admin'
                        });
                      } else if (type == 1) {
                        this.$router.push({
                          path: '/admin'
                        });
                      }
                    }.bind(this)
                  });
                }
                this.timerOut();
              }
            })
            .catch(err => {
              this.timerOut();
              console.log(err);
            });
        } else {
          console.log('faild');
          this.timerOut();
          return false;
        }
      });
    },
    toRegister() {
      //点击注册
      this.$router.push({
        path: '/register'
      });
    },
    toForgetPsw() {
      //忘记密码
      this.$router.push({
        path: '/forgetPassword'
      });
    },
    timerOut() {
      let timer = setTimeout(() => {
        this.otherCor = false;
        clearTimeout(timer);
      }, 500);
    }
  },
  components: {
    banner: banner,
    copyRightInfo: copyRightInfo
  }
};
</script>
