<template>
  <div class="x-container">
    <!-- background slider -->
    <div class="x-banner-wrap">
      <div class="x-banner">
        <ul class="list-unstyled">
          <li>
            <a>
              <div class="inner">
                <div class="x-title x-text-0"></div>
                <div class="x-subtitle x-text-0"></div>
                <div class="x-btn-group">
                </div>
              </div>
            </a>
          </li>
        </ul>
      </div>
    </div>
    <div class="x-login-wrap">
      <div class="x-login">
        <!-- user & pwd login wrap -->
        <div id="form-wrap" class="x-login-form">
          <div>
            <el-form :model="login" :rules="rules2" ref="login" class="demo-ruleForm login-form">
              <el-form-item prop="username">
                <el-input type="text" v-model="login.username" auto-complete="off" placeholder="手机号/邮箱/账号ID"></el-input>
                <i class="fa fa-user"></i>
              </el-form-item>
              <el-form-item prop="password">
                <el-input type="password" v-model="login.password" auto-complete="off" placeholder="密码"></el-input>
                <i class="fa fa-lock"></i>
              </el-form-item>
              <el-form-item prop="captcha" class="captcha" v-show="showCheckCode">
                <el-input type="text" v-model="login.captcha" auto-complete="off" class="code-input"></el-input>
                <img id="captchaImage" class="code-img" src="/sso/login/checkCode"/>
                <a class="code-click" @click="getCode">看不清换一张</a>
              </el-form-item>
              <el-form-item class="text-right">
                <a class="forget" id='forget' @click="goForgetPassword">忘记密码?</a>
              </el-form-item>
              <el-form-item>
                <a class="btn login"
                   @click="isLogin(true)"
                   :disabled="isLoginDisabled">登录</a>
              </el-form-item>
            </el-form>
          </div>
          <div class="warn-text-area">
            为确保您账户的安全及正常使用，依《网络安全法》相关要求，6月1日起会员账户需绑定手机、设置密码保护。感谢您的理解和支持！
          </div>
          <div style="text-align: right;">
            <a id="register" @click="goRegister">
              <i class="fa fa-arrow-circle-o-right"></i>免费注册</a>
          </div>
        </div>
        <!-- qrcode login wrap -->
        <div id="qrcode-wrap" class="x-login-qrcode">
          <div class="x-qrcode-help">
            <span>打开手机客户端，扫描下面的二维码</span>
          </div>
          <div class="x-qrcode-img">
            <img src="/images/all/qrcode.jpg">
          </div>
          <div class="x-qrcode-ex">
            <ul class="list-unstyled list-inline">
              <li><i class="iconfont icon-left icon-input"></i><span>免输入</span></li>
              <li><i class="iconfont icon-left icon-fast"></i><span>更快捷</span></li>
              <li><i class="iconfont icon-left icon-safe"></i><span>更安全</span></li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    <!--选择企业弹出框-->
    <div>
      <el-dialog class="dialog"
                 :visible.sync="dialogVisible"
                 size="tiny">
        <div class="x-floating x-list">
          <div class="x-list-header">您要登录的公司是：</div>
          <ul class="list-unstyled" v-for="space in this.enterprise">
            <li v-text="space.name" @click="chooseOneEnterprise(false, space.id)">华商龙科技有限公司</li>
          </ul>
        </div>
      </el-dialog>
    </div>
    <loading v-show="isShowLoading"/>
  </div>
</template>

<script>
  import Loading from '~components/common/loading/Loading.vue'
  export default {
    name: 'login',
    components: {
      Loading
    },
    data () {
      var validateUsername = (rule, value, callback) => {
        if (value === '') {
          this.checkUsername = false
          this.showCheckCode = false
        } else {
          if (this.login.username !== '') {
            //    获取密码输错次数
            this.$http.get(`/sso/login/getPwdErrorCount`, {params: {username: this.login.username}})
              .then(response => {
                if (response.data) {
                  this.showCheckCode = false
                  let getPasswordErrorCount = response.data.content || ''
                  if (getPasswordErrorCount >= 5) {
                    this.$message.error('密码错误次数已达上限，今日无法登陆')
                    this.isLoginDisabled = true
                    this.showCheckCode = false
                  } else if (getPasswordErrorCount < 3) {
                    this.isLoginDisabled = false
                    this.checkUsername = true
                    this.showCheckCode = false
                  } else if (getPasswordErrorCount >= 3 && getPasswordErrorCount < 5) {
                    if (getPasswordErrorCount === 3) {
                      this.$message.error('当前已输错密码3次，若达到5次今日将无法登陆')
                    }
                    this.isLoginDisabled = false
                    this.checkUsername = true
                    this.showCheckCode = true
                  } else {
                    this.checkUsername = false
                    this.showCheckCode = false
                  }
                }
              }, err => {
                this.$message.error(err)
              })
          }
          callback()
        }
      }
      var validatePassword = (rule, value, callback) => {
        if (value === '') {
          this.checkPassword = false
        } else {
          if (this.login.password !== '') {
            this.checkPassword = true
          }
          callback()
        }
      }
      return {
        login: {
          username: '',
          password: '',
          captcha: '',
          spaceUU: ''
        },
        isShowLoading: false,
        checkUsername: false,
        checkPassword: false,
        showCheckCode: false,
        isLoginDisabled: false,
        dialogVisible: false,
        rules2: {
          username: [
            {validator: validateUsername, trigger: 'blur'}
          ],
          password: [
            {validator: validatePassword, trigger: 'blur'}
          ]
        }
      }
    },
    mounted () {
      this.$nextTick(() => {
        this.getUrl()
      })
    },
    computed: {
      enterprise () {
        let chooseEnterprise = this.$store.state.login.chooseRegisterEnterprise.choose.data
//        console.log(chooseEnterprise)
        return chooseEnterprise
      }
    },
    methods: {
//      获取url参数
      getUrl () {
        var url = window.location.search
        var request = {}
        if (url.indexOf('?' !== -1)) {
          var str = url.substr(1)
          var strs = str.split('&')
          for (var i = 0; i < strs.length; i++) {
            request[strs[i].split('=')[0]] = decodeURI(strs[i].split('=')[1])
          }
        }
        this.appId = request['appId'] || ''
        this.returnUrl = request['returnUrl'] || ''
        this.baseUrl = request['baseUrl'] || ''
      },
//      忘记密码
      goForgetPassword () {
        let url = `/reset/forgetPasswordValidationAccount?appId=${this.appId}&returnUrl=${this.returnUrl}`
        document.getElementById('forget').href = url
      },
//      去注册
      goRegister () {
        if (this.appId === 'mall') {
          var registerurl = `/register/personalRegistration?appId=${this.appId}&returnUrl=${this.returnUrl}`
        } else {
          registerurl = `/register/enterpriseRegistration?appId=${this.appId}&returnUrl=${this.returnUrl}`
        }
        document.getElementById('register').href = registerurl
      },
  //    获取验证码
      getCode () {
        var imgSrc = document.getElementById('captchaImage')
        imgSrc.setAttribute('src', '/sso/login/checkCode?timestamp=' + (new Date()).valueOf())
      },
//      登录
      isLogin (flag) {
        this.isShowLoading = true
        if (!this.checkUsername) {
          this.$message.error('请填写账号')
        } else if (!this.checkPassword) {
          this.$message.error('请填写密码')
        } else {
          let param = new FormData()
          param.append('username', this.login.username)
          param.append('password', this.login.password)
          param.append('captcha', this.login.captcha)
          param.append('appId', this.appId)
          param.append('returnUrl', this.returnUrl)
          param.append('baseUrl', this.baseUrl)
          param.append('spaceUU', this.login.spaceUU)
          let config = {
            headers: {'Content-Type': 'multipart/form-data'}
          }
          this.$http.post('/sso/login', param, config)
            .then(response => {
              if (response.data.success) {
                this.isShowLoading = false
//                console.log(response.data.content)
                if (response.data.content.spaces) {
//                   弹框让用户选择企业
                  this.$store.commit('login/chooseRegisterEnterprise/GET_ENTERPRISE_SUCCESS', response.data.content.spaces)
                  this.dialogVisible = flag
                } else if (response.data.content.loginUrls) {
//                  遍历登录url循环让各应用登录(需要跨域)
                  for (var i in response.data.content.loginUrls) {
//                    this.$http.post(response.data.content.loginUrls[i], response.data.content.data)
                    this.$jsonp(`response.data.content.loginUrls${[i]}`, function (err, data) {
                      if (err) throw err
                      console.log(data)
                    })
                  }
                  window.location.href = response.data.content.returnUrl || 'http://www.ubtob.com'
                }
              } else {
                this.$message.error(response.data)
                var count = response.data.errorCount
                if (count < 3) {
                  this.showCheckCode = false
                  this.isLoginDisabled = false
                } else if (count >= 5) {
                  this.$message.error('密码错误次数已达上限，今日无法登陆')
                  this.isLoginDisabled = true
                  this.showCheckCode = false
                } else if (count >= 3 && count < 5) {
                  this.getCode()
                  if (count === 3) {
                    this.$message.error('当前已输错密码3次，若达到5次今日将无法登陆')
                  }
                  this.showCheckCode = true
                  this.isLoginDisabled = false
                }
                return Promise.reject(response.data)
              }
            }).catch(err => {
              this.isShowLoading = false
              let _this = this
              setTimeout(function () {
                _this.getCode()
              }, 100)
              this.$message.error(err.errMsg)
            })
        }
      },
      chooseOneEnterprise (flag, spaceUU) {
        this.login.spaceUU = spaceUU
        this.isLogin(flag)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .x-container{
    position: relative;
    height: 475px;
    /*登录弹出框*/
    .x-floating {
      position: fixed;
      top: 80px;
      left: 50%;
      z-index: 100000;
      opacity: 1;
      -webkit-transition: all .5s;
      -moz-transition: all .5s;
      transition: all .5s;
    }
    .x-list {
      width: 306px;
      margin-left: -153px;
      background: #fff;
      border-top: 1px solid #e7e7e7;
      cursor: pointer;
      .x-list-header {
        padding: 10px 20px;
        background: #e0e0e0;
        width: 306px;
        height: 42px;
        line-height: 21px;
        font-size: 14px;
        font-weight: 700;
        color: #505050;
      }
      ul{
        margin-bottom: 0;
        li{
          padding: 10px 20px;
          width: 306px;
          height: 42px;
          line-height: 21px;
          font-size: 12px;
          color: #505050;
          border-bottom: 1px solid #e7e7e7;
          &:hover{
            background: #e7e7e7;
           }
        }
      }
      .x-list .x-list-header, .x-list li {
        padding: 10px 20px;
        border-bottom: 1px solid #e7e7e7;
      }
    }
    .x-floating.in {
      top: 80px;
      opacity: 1;
    }
    .x-banner-wrap {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 475px;
      .x-banner {
        position: relative;
        overflow: auto;
        height: 475px;
        text-align: center;
        li{
          width: 100%;
          height: 475px;
          background: url(/images/all/banner.jpg) center center / auto 100% no-repeat rgb(202, 202, 214);
        }
      }
    }
    .x-login-wrap{
      position: absolute;
      top: 10px;
      right: 50%;
      margin-right: -495px;
      height: 475px;
      z-index: 5;
      .x-login {
        position: relative;
        top: 40px;
        width: 346px;
        background: #fff;
        overflow: visible;
        z-index: 4;
        .x-login-form, .x-login-qrcode {
          padding: 20px;
          .btn{
            background: #5078cb;
            color: #fff;
            font-weight: 700;
            letter-spacing: 4px;
            border-radius: 0;
          }
          .x-has-feedback-right {
            float: right;
            display: inline-block;
            a{
              color: #5078cb;
            }
          }
          .x-has-feedback-left {
            position: relative;
            .x-input {
              padding-left: 30px;
              line-height: 18px;
              color: #555;
              border-color: #ccc;
              border-radius: 0;
              box-shadow: none;
            }
            i.fa{
              position: absolute;
              top: 2px;
              left: 0;
              z-index: 2;
              display: block;
              width: 30px;
              height: 34px;
              line-height: 34px;
              text-align: center;
              pointer-events: none;
              color: #999;
              font-size: 18px;
            }
          }
          i.fa-keyboard-o{
            position: absolute;
            right: 10px;
            top: 10px;
          }
          i.fa-arrow-circle-o-right{
            margin-right: 5px;
            font-size: 14px;
            color: #5078cb;
          }
          .warn-text-area{
            margin-top: 5px;
            font-size: 13px;
            color: #000;
          }
        }
        .x-login-qrcode{
          display: none;
        }
      }
    }
  }
</style>
