<template>
  <div class="go-register register">
    <div class="container">
      <div class="content" v-if="isSuccess">
        <div class="content-top">
          <h3>注册</h3>
        </div>
        <div>
          <el-form :model="item" :rules="rules2" ref="item" label-width="100px" class="demo-ruleForm">
            <div>

            </div>
            <el-form-item prop="mobile" class="mobile">
              <el-input v-model="item.mobile"
                        v-bind:class="{active: mobileRegister}"
                        placeholder="手机号码"></el-input>
              <span class="err-tip-msg tip" v-show="showMsgTip">单个手机号只能注册一个用户</span>
              <span class="err-tip-msg tip tip-mobile" v-show="mobileRegister">该手机号已被注册</span>
            </el-form-item>
            <el-form-item prop="captcha" class="captcha" style="overflow: hidden">
              <el-input type="text"
                        v-model="ImgCode"
                        auto-complete="off"
                        class="code-input"
                        @keyup.enter.native="getCheckCode"></el-input>
              <img id="captchaImage2" class="code-img" src="/sso/login/checkCode"/>
              <a class="code-click" @click="getCode">看不清换一张</a>
            </el-form-item>
            <el-form-item prop="code">
              <el-input type="text" v-model="item.code"
                        v-bind:class="{ active: codeErrorChecked }" auto-complete="off" class="msg" placeholder="短信验证码"></el-input>
              <el-button type="primary" class="code"
                         v-show="sendPersonalCode"
                         @click="getCheckCode"
                         :disabled="this.checkMobile">获取验证码</el-button>
              <el-button type="primary"  v-show="!sendPersonalCode" class="code code-send">已发送({{personal_time}}s)</el-button>
              <span v-show="codeErrorChecked" class="codeError-tip">{{codeErrorMsg}}</span>
            </el-form-item>
            <el-form-item class="agree">
              <el-checkbox name="type" v-model="checked" @click="checkboxChecked"></el-checkbox>
              <span class="agree" v-if="!agreementUrl || (agreementUrl && (JSON.parse(agreementUrl.terms).isUrl))">我已阅读并同意 <a href="/common/agreement"  target="_blank">《优软云服务条款》</a></span>
              <span class="agree" v-else>我已阅读并同意<a :href="`/common/cityAgreement/?appId=${this.$route.query.appId}`" target="_blank">《{{JSON.parse(agreementUrl.terms).name || ''}}》</a></span>
            </el-form-item>
            <el-form-item>
              <a class="btn finish" @click="waySubmit">确认注册</a>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="content" v-else>
        <div class="register-success">
          <i class="iconfont icon-zhucechenggong1"></i>
          <p>注册成功！</p>
          <span>您的账号密码已发送至手机，请注意查收</span>
        </div>
      </div>
      <div class="login">已有账号？<a :href="returnLogin">立即登录</a></div>
      <loading v-show="isShowLoading"/>
    </div>
  </div>
</template>

<script>
  import md5 from 'js-md5'
  import Loading from '~components/common/loading/Loading.vue'
  export default {
    name: 'PersonalRegistration',
    layout: 'sass',
    components: {
      Loading
    },
    data () {
      var validateMobile = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写正确的手机号'))
          this.showMsgTip = false
          this.checkMobile = true
          this.mobileRegister = false
          this.mobileChecked = false
        } else {
          if (this.item.mobile !== '') {
            var reg = /^1([0-9]{10})$/
            if (!reg.test(value)) {
              callback(new Error('请填写正确的手机号'))
              this.showMsgTip = false
              this.checkMobile = true
              this.mobileRegister = false
              this.mobileChecked = false
            } else {
              this.$http.get(`/api/user/checkMobile`, {params: {mobile: this.item.mobile, mobileArea: ''}})
                .then(response => {
                  if (response.data.hasRegister) {
                    this.mobileRegister = true
                    this.showMsgTip = false
                    this.checkMobile = true
                    this.mobileChecked = false
                  } else {
                    this.showMsgTip = false
                    this.checkMobile = false
                    this.mobileRegister = false
                    this.mobileChecked = true
                  }
                })
            }
          }
          callback()
        }
      }
      var validateCode = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写正确的验证码'))
          this.codeErrorChecked = false
          this.codeChecked = false
        } else {
          if (this.item.mobile === '') {
            callback(new Error('请先填写正确的手机号'))
          } else {
            if (this.token) {
              if (this.item.code.length === 6) {
                let param = new FormData()
                param.append('mobile', this.item.mobile)
                param.append('code', this.item.code)
                param.append('token', this.token)
                let config = {
                  headers: {'Content-Type': 'multipart/form-data'}
                }
                this.$http.post(`/sso/personal/register/checkCode`, param, config)
                  .then(response => {
                    if (response.data.success) {
                      this.codeChecked = true
                      this.codeErrorChecked = false
                    } else {
                      this.codeErrorChecked = true
                      this.codeChecked = false
                      return Promise.reject(response.data)
                    }
                  }).catch(err => {
                    // this.codeErrorMsg = err.errMsg
                    this.$message.error(err.errMsg)
                  })
              } else {
                callback(new Error('请输入正确的验证码'))
                this.codeChecked = false
                this.codeErrorChecked = false
              }
            } else {
              callback(new Error('请先获取验证码'))
              this.codeChecked = false
              this.codeErrorChecked = false
            }
          }
          callback()
        }
      }
      var validateCodeIsEmpty = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写正确的验证码'))
          this.codeErrorChecked = false
          this.codeChecked = false
        } else {
          if (this.item.mobile === '') {
            callback(new Error('请先填写正确的手机号'))
          } else {
            if (this.token) {
              if (this.item.code.length === 6) {
                let param = new FormData()
                param.append('mobile', this.item.mobile)
                param.append('code', this.item.code)
                param.append('token', this.token)
                let config = {
                  headers: {'Content-Type': 'multipart/form-data'}
                }
                this.$http.post(`/sso/personal/register/checkCode`, param, config)
                  .then(response => {
                    if (response.data.success) {
                      this.codeChecked = true
                      this.codeErrorChecked = false
                    } else {
                      this.codeErrorChecked = true
                      this.codeChecked = false
                      return Promise.reject(response.data)
                    }
                  }).catch(err => {
                    this.$message.error(err.errMsg)
                    // this.codeErrorMsg = err.errMsg
                  })
              } else {
                callback(new Error('请输入正确的验证码'))
                this.codeChecked = false
                this.codeErrorChecked = false
              }
            } else {
              callback(new Error('请先获取验证码'))
              this.codeChecked = false
              this.codeErrorChecked = false
            }
          }
          callback()
        }
      }
      return {
        isSuccess: true,
        speediness: false,
        ImgCode: '',
        item: {
          mobile: '',
          code: ''
        },
        isShowLoading: false,
        showPasswordError: false,
        mobileChecked: false,
        codeChecked: false,
        codeErrorChecked: false,
        showMsgTip: true,
        checkMobile: true,
        checked: true,
        token: '',
        mobileRegister: false,
        sendPersonalCode: true,
        codeErrorMsg: '',
        personal_time: 0,
        queryLink: '',
        appId: '',
        returnLogin: '',
        rules2: {
          mobile: [
            { validator: validateMobile, trigger: 'blur' }
          ],
          code: [
            { validator: validateCode, trigger: 'blur' },
            { validator: validateCodeIsEmpty, trigger: 'blur' }
          ]
        }
      }
    },
    mounted () {
//      获取链接
      this.$nextTick(() => {
        this.getUrl()
        this.getCode()
      })
    },
    computed: {
      loginStyle () {
        return this.$store.state.login.loginStyle.data.content
      },
      agreementUrl () {
        return this.$store.state.login.agreementUrl.data.content
      }
    },
    methods: {
      // 获取链接
      getUrl () {
        var url = window.location.search
        var request = {}
        var origin = window.location.origin
        this.returnLogin = origin + '/sassLogin' + url
        if (url.indexOf('?' !== -1)) {
          var str = url.substr(1)
          var strs = str.split('&')
          this.queryLink = str
          for (var i = 0; i < strs.length; i++) {
            request[strs[i].split('=')[0]] = decodeURI(strs[i].split('=')[1])
          }
        }
        this.appId = request['appId'] || ''
      },
      // 注册
      goRegister () {
        window.location.href = `/register/enterpriseRegistration${this.queryLink ? '?' + this.queryLink : ''}`
      },
//      我同意是否被选中
      checkboxChecked () {
        this.checked = !this.checked
      },
      // 快速注册
      waySubmit () {
        console.log(this.$route.params.baseUrl)
        if (this.mobileChecked && this.codeChecked && this.checked) {
          this.isShowLoading = true
          let param = new FormData()
          param.append('mobile', this.item.mobile)
          param.append('appId', this.appId)
          param.append('code', this.item.code)
          param.append('token', this.token)
          param.append('t', this.$route.query.tk ? this.$route.query.tk : '')
          if (this.$route.query.baseUrl) {
            param.append('baseUrl', this.$route.query.baseUrl)
          }
          if (this.$route.query.returnURL) {
            param.append('returnUrl', this.$route.query.returnURL)
          }
          let config = {
            headers: {'Content-Type': 'multipart/form-data'}
          }
          this.$http.post('/sso/personal/register/sms', param, config)
            .then(response => {
              this.isShowLoading = false
              if (response.data.success) {
                this.isSuccess = false
                this.isShowLoading = false
                this.getJsonp(decodeURIComponent(this.$route.query.baseUrl))
              } else {
                return Promise.reject(response.data)
              }
            }).catch(err => {
              this.$message.error(err.errMsg)
              this.isShowLoading = false
              this.personal_time = 0
            })
        } else {
          if (!this.item.mobile) {
            this.$message.error('手机号不能为空')
          } else if (!this.mobileChecked) {
            this.$message.error('手机号输入有误，请按提示重新输入')
          } else if (!this.token) {
            this.$message.error('请先获取验证码')
          } else if (!this.item.code) {
            this.$message.error('验证码不能为空')
          } else if (!this.codeChecked) {
            this.$message.error('验证码输入有误，请按提示重新输入')
          } else if (!this.checked) {
            this.$message.error('您对阅读条款未做勾选')
          }
        }
      },
      //    获取验证码
      getCode () {
        let imgSrc = document.getElementById('captchaImage2')
        imgSrc.setAttribute('src', '/sso/resetPwd/checkCaptcha?timestamp=' + (new Date()).valueOf())
      },
      getCheckCode () {
        let md5Code = md5(`{mobile=${this.item.mobile},code=${this.ImgCode},salt=sso}`)
        this.isShowLoading = true
        this.$http.get(`/sso/personal/register/checkCode`, {params: {mobile: this.item.mobile, timestamp: new Date().getTime() + '', code: this.ImgCode, sign: md5Code}})
          .then(response => {
            this.isShowLoading = false
            if (response.data) {
              this.token = response.data.token
              if (response.data.errMsg) {
                this.$message({
                  message: response.data.errMsg,
                  type: 'error'
                })
                this.ImgCode = ''
                this.getCode()
                return
              }
              if (this.token !== '') {
                this.$message({
                  message: '验证码已经发送到您的手机，请注意查收',
                  type: 'success'
                })
                this.sendPersonalCode = false
                this.personal_time = 60
                var personalTime = setInterval(() => {
                  this.personal_time--
                  if (this.personal_time <= 0) {
                    this.sendPersonalCode = true
                    clearInterval(personalTime)
                  }
                }, 1000)
              }
            } else {
              return Promise.reject(response.data)
            }
          }).catch(err => {
            this.isShowLoading = false
            this.$message.error(err.errMsg)
          })
      },
      getJsonp: function (url, timeout = 500) {
        return new Promise((resolve, reject) => {
          this.$jsonp(url, {
            name: 'successCallback',
            timeout: timeout
          }, function (err, data) {
            if (err) {
              reject(err)
              throw err
            } else {
              resolve(data)
            }
          })
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .go-register.register {
    position: relative;
    bottom: -18px;
    margin: 0 auto;
    width: 100%;
    background: #eee;
    .container{
      padding-top: 38px!important;
      margin: 0 auto;
      width: 980px;
      text-align: center;
      background: #fff;
      box-shadow: none!important;
      .content{
        padding: 0 50px;
        margin: 50px auto 0;
        width: 100%;
        text-align: center;
        .register-success {
          padding-top: 40px;
          width: 100%;
          height: 380px;
          i.icon-zhucechenggong1{
            font-size: 148px;
            color: #00BB00;
          }
          p{
            margin-top: 20px;
            font-size: 28px;
            color: #333;
          }
          span{
            font-size: 16px;
            color: #666;
          }
        }
        .content-top{
          position: relative;
          height: 80px;
          line-height: 80px;
          border-bottom: 1px solid #dcdcdc;
          h3{
            font-family: 'SimHei';
            font-size: 24px;
            color: #000;
          }
          a.go{
            position: absolute;
            top: 0;
            right: 0;
            font-size: 14px;
            i{
              margin-right: 3px;
            }
          }
        }
        .content-tab{
          width: 360px;
          margin: 0 auto;
          height: 50px;
          margin-top: 15px;
          color: #999;
          span{
            display:inline-block;
            width:50%;
            vertical-align:top;
            font-size:20px;
            text-align: center;
            line-height:40px;
            height:40px;
            border-bottom:2px solid #fff;
            cursor:pointer;
            &.speed{
              color:#3375a7;
              border-bottom:2px solid #3375a7;
            }
          }
        }
        form {
          padding-bottom: 44px;
          margin-top: 15px;
          input{
            padding: 0 0 0 18px;
            width: 360px;
            height: 44px;
            line-height: 44px;
            font-size: 14px;
            color: #000;
            border-radius: 0;
          }
          span.help{
            position: absolute;
            right: -230px;
            top:0;
            font-size: 12px;
            color: #f00;
          }
          i.fa{
            position: absolute;
            top: 10px;
            right: 18px;
            font-size: 24px;
            color: #a0a0a0;
            cursor: pointer;
          }
          span.tip{
            position: absolute;
            top: 40px;
            left: 0;
            font-size: 12px;
            color: #8c8c8c;
            &.tip-mobile{
              color: #ff4949;
            }
          }
          .el-form-item__error {
            position: static;
            margin: 0 auto;
            text-align: left;
          }
          span.codeError-tip{
            position: absolute;
            top: 3px;
            left: 378px;
            width: 200px;
            text-align: left;
            color: #ff4949;
            font-size: 12px;
          }
          span.tip.passwordError{
            position: absolute;
            top: 3px;
            left: 380px;
            width: 200px;
            text-align: left;
            color: #ff4949;
            font-size: 12px;
          }
          input.msg{
            float: left;
            width: 210px;
          }
          button.msg{
            float: right;
            width: 130px;
            height: 44px;
            font-size: 14px;
            color: #5a5a5a;
            background: #f4f4f4;
            border: 1px solid #dcdcdc;
            cursor: pointer;
            &:disabled{
              cursor: not-allowed ;
              opacity: .7;
            }
          }
          span.msg.send{
            float: right;
            width: 130px;
            height: 44px;
            line-height: 44px;
            font-size: 14px;
            background: #d2d2d2;
            color: #fff;
            border: 1px solid #dcdcdc;
          }
          input[type='checkbox']{
            margin: 0 14px 0 55px;
            float: left;
            width: 16px;
            height: 16px;
          }
          span.agree{
            float: left;
            margin: 1px 0 0 10px;
            font-size: 14px;
            color: #8b8b8b;
            a{
              color: #0076ad;
            }
          }
          .form-group.agree{
            margin: 20px auto 0 !important;
          }
          .submitBtn {
            display: inline-block;
            width: 360px;
            height: 44px;
            line-height: 44px;
            font-size: 16px;
            color: #fff;
            background: #0076AD;
            border-radius: 3px;
            border: none;
            &:disabled{
              cursor: not-allowed ;
              opacity: .7;
            }
          }
        }
      }
      .login{
        margin-top: 20px;
        font-size: 14px;
        color: #8c8c8c;
        a{
          font-size: 14px;
          color: #0076ad;
        }
      }
    }
  }
  .footer{
    padding: 50px 0;
  }
</style>
