<template>
  <div class="f-main">
    <div class="content-top">
      <p>个人注册</p>
      <a class="go" @click="goRegister"><i class="fa fa-long-arrow-right"></i>企业注册</a>
    </div>
    <div class="content-tab">
      <span :class="{speed: speediness === false}" @click="clickWay(false)">用户名注册</span>
      <span :class="{speed: speediness === true}" @click="clickWay(true)">手机号注册</span>
    </div>
    <div class="f-form">
      <div class="page-part" v-if="!speediness">
        <mt-field :state="state.vipName"
                  placeholder="会员名"
                  :attr="{ maxlength: 20 }"
                  v-model="vipName"></mt-field>
      </div>
      <div class="page-part" v-if="!speediness">
        <mt-field :state="state.password"
                  placeholder="密码"
                  :attr="{ maxlength: 20 }"
                  v-model="password"
                  @input.native="codePwd"
                  type="password"></mt-field>
        <template v-if="password">
          <p class="pwd">密码强度 <em :class="{sm:step === '弱', md: step === '中', ld:step === '强'}"></em> <em :class="{md: step === '中', ld:step === '强'}"></em> <em :class="{ld:step === '强'}"></em> <span :class="{smstep:step === '弱', mdstep: step === '中', ldstep:step === '强'}" v-text="step">强</span></p>
          <p class="pwd">密码须为8-20字符的英文、数字混合</p>
        </template>
      </div>
      <div class="page-part" v-if="!speediness">
        <mt-field :state="state.confirm"
                  placeholder="确认密码"
                  v-model="confirm"
                  type="password"></mt-field>
      </div>
      <div class="page-part">
        <mt-field :state="state.mobile"
                  placeholder="手机号码"
                  v-model="mobile"
                  type="tel"></mt-field>
      </div>
      <div class="page-part">
        <mt-field placeholder="验证码" v-model="code">
          <img :src="imgSrc" height="45px" width="100px" @click="getCode">
        </mt-field>
      </div>
      <div class="page-part">
        <mt-field :state="state.token"
                  placeholder="短信验证码"
                  v-model="token"
                  auto-complete="off">
          <span class="token" v-text="tokenText" @click="getCheckCode">获取验证码</span>
        </mt-field>
      </div>
    </div>
    <div class="form-btn">
      <div class="page-part">
        <el-checkbox v-model="checked">我已阅读并同意 <a class="rgba" href="/common/agreement">《优软云服务条款》</a></el-checkbox>
      </div>
      <mt-button type="primary" size="large" @click.native="allSubmit">完成注册</mt-button>
    </div>
  </div>
</template>

<script>
  import md5 from 'js-md5'
  export default {
    name: 'registerPerson',
    data () {
      return {
        speediness: false,
        imgSrc: '',
        code: '',
        step: 1,
        state: {
          vipName: 'error',
          password: 'error',
          confirm: 'error',
          mobile: 'error',
          token: 'error',
          code: 'error'
        },
        vipName: '',
        password: '',
        confirm: '',
        mobile: '',
        token: '',
        tokenCode: '',
        tokenText: '获取验证码',
        tokenTime: '60',
        checked: true
      }
    },
    mounted () {
      this.$nextTick(() => {
        this.getCode()
      })
    },
    watch: {
      'token': {
        handler (newVal) {
          if (newVal.length === 6) {
            this.codeToken()
          }
        },
        immediate: true
      }
    },
    methods: {
      // 切换注册方式
      clickWay (type) {
        if (this.speediness !== type) {
          this.speediness = type
          this.imgSrc = ''
          this.getCode()
        }
      },
      getCode () {
        this.imgSrc = '/sso/resetPwd/checkCaptcha?timestamp=' + (new Date()).valueOf()
      },
      // 注册
      goRegister () {
        window.location.href = `/register/enterpriseRegistration${this.$store.state.option.fullPath}`
      },
      // 验证弹窗
      downToast (type) {
        this.$toast({
          message: type,
          iconClass: 'el-icon-warning'
        })
      },
      // 验证会员名
      codeVipName () {
        let count = this.vipName.length
        if (count === 0) {
          this.downToast('会员名不能为空')
          this.state.vipName = 'error'
        } else if (count < 2 || count > 20) {
          this.downToast('请填写合适的会员名称，2~20个字符')
          this.state.vipName = 'warning'
        } else {
          this.state.vipName = 'success'
        }
      },
      // 验证密码强度
      codePwd () {
        let reg1 = /^(?=.{8,20})(((?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]))|((?=.*[0-9])((?=.*[a-zA-Z]))(?=.*[^a-zA-Z0-9]))).*$/
        let reg2 = /^(?=.{8,20})(((?=.*[0-9])(?=.*[a-z]))|((?=.*[0-9])(?=.*[A-Z]))).*$/
        if (reg1.test(this.password)) {
          this.step = '强'
        } else if (reg2.test(this.password)) {
          this.step = '中'
        } else {
          this.step = '弱'
        }
      },
      // 验证密码格式
      codePwdBlur () {
        let reg2 = /^(?=.{8,20})(((?=.*[0-9])(?=.*[a-z]))|((?=.*[0-9])(?=.*[A-Z]))).*$/
        if (!this.password) {
          this.downToast('请输入密码')
          this.state.password = 'error'
        } else if (!reg2.test(this.password)) {
          this.downToast('密码须为8-20字符的英文、数字混合')
          this.state.password = 'warning'
        } else {
          this.state.password = 'success'
          if (this.confirm) {
            this.codePassword()
          }
        }
      },
      // 验证密码的确认信息
      codePassword () {
        if (!this.confirm) {
          this.downToast('请再次输入密码')
          this.state.confirm = 'error'
        } else if (this.confirm !== this.password) {
          this.downToast('两次输入密码不一致!')
          this.state.confirm = 'warning'
        } else {
          this.state.confirm = 'success'
        }
      },
      // 验证手机号
      codeMobile () {
        let reg = /^1([0-9]{10})$/
        if (!this.mobile) {
          this.downToast('请输入手机号')
          this.state.mobile = 'error'
        } else if (!reg.test(this.mobile)) {
          this.downToast('请填写正确的手机号码')
          this.state.mobile = 'warning'
        } else {
          this.$http.get(`/api/user/checkMobile`, {params: {mobile: this.mobile, mobileArea: ''}})
            .then(response => {
              if (response.data.hasRegister) {
                this.downToast('该手机号已被注册,可直接登录')
                this.state.mobile = 'warning'
              } else {
                this.state.mobile = 'success'
              }
            }).catch((err) => {
              this.downToast(err.errMsg)
            })
        }
      },
      // 验证-验证码信息
      codeToken () {
        if (!this.token) {
          this.downToast('请先填写验证码')
          this.state.token = 'error'
        } else {
          if (!this.mobile) {
            this.downToast('请先填写正确的手机号码')
            this.state.token = 'warning'
          } else {
            if (this.tokenCode) {
              let param = new FormData()
              param.append('mobile', this.mobile)
              param.append('token', this.tokenCode)
              param.append('code', 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.state.token = 'success'
                  } else {
                    this.$toast({
                      message: response.data.errMsg,
                      iconClass: 'el-icon-error'
                    })
                  }
                }).catch((err) => {
                  this.downToast(err.errMsg)
                })
            } else {
              this.downToast('请点击先获取验证码信息')
              this.state.token = 'warning'
            }
          }
        }
      },
      // 获取验证码
      loadCheckCode () {
        let md5Code = md5(`{mobile=${this.mobile},code=${this.code},salt=sso}`)
        if (this.state.mobile !== 'success') {
          this.codeMobile()
        } else if (this.code === '') {
          this.downToast('请输入验证码后获取！')
        } else {
          this.$indicator.open('获取中...')
          let _this = this
          this.$http.get('/sso/personal/register/checkCode', {params: {sign: md5Code, code: this.code, mobile: this.mobile, timestamp: new Date().getTime() + ''}})
            .then(response => {
              this.$indicator.close()
              if (response.data.errMsg) {
                this.$toast({
                  message: response.data.errMsg,
                  iconClass: 'el-icon-error'
                })
                this.code = ''
                this.getCode()
                return
              }
              if (response.data) {
                this.tokenCode = response.data.token
                this.$toast({
                  message: '验证码已经发送到您的手机，请注意查收',
                  iconClass: 'el-icon-success'
                })
                this.tokenText = '已发送(' + this.tokenTime + 'S)'
                let setTime = setInterval(() => {
                  _this.tokenTime--
                  this.tokenText = '已发送(' + this.tokenTime + 'S)'
                  if (this.tokenTime <= 0) {
                    clearInterval(setTime)
                    _this.tokenText = '获取验证码'
                    _this.tokenTime = 60
                  }
                }, 1000)
              }
            }).catch((err) => {
              this.$indicator.close()
              this.downToast(err.errMsg)
            })
        }
      },
      // 验证码发送请求
      getCheckCode () {
        if (this.tokenTime > 0 && this.tokenTime < 60) {
          this.downToast('请稍后再点击，我在倒计时')
        } else {
          this.loadCheckCode()
        }
      },
      // 表单提交
      submit () {
        if (this.state.vipName !== 'success') {
          this.codeVipName()
        } else if (this.state.password !== 'success') {
          this.codePwdBlur()
        } else if (this.state.confirm !== 'success') {
          this.codePassword()
        } else if (this.state.mobile !== 'success') {
          this.codeMobile()
        } else if (this.state.token !== 'success') {
          this.codeToken()
        } else if (this.checked === false) {
          this.downToast('您对阅读条款未做勾选')
        } else {
          this.$indicator.open('注册中...')
          let param = new FormData()
          param.append('vipName', this.vipName)
          param.append('password', this.password)
          param.append('mobile', this.mobile)
          // param.append('mobileArea', '')
          param.append('appId', this.$store.state.option.appId)
          param.append('code', this.token)
          param.append('token', this.tokenCode)
          param.append('t', this.$route.query.tk ? this.$route.query.tk : '')
          param.append('returnUrl', this.$route.query.returnURL ? this.$route.query.returnURL : '')
          let config = {
            header: {'Content-Type': 'multipart/form-data'}
          }
          this.$http.post('/sso/personal/register', param, config)
            .then(response => {
              this.$indicator.close()
              if (response.data.success) {
                if (response.data.content.data) {
                  let param = response.data.content.data
                  let a = ''
                  for (let n in param) {
                    a += (n + '=' + encodeURIComponent(param[n]) + '&')
                  }
                  let params = a.substr(0, a.length - 1)
                  this.isShowLoading = true
                  if (response.data.content.currentUrl) {
                    this.$jsonp(`${response.data.content.currentUrl}?${params}`, {
                      name: 'successCallback',
                      timeout: 3000
                    }, (err, data) => {
                      if (err) {
                        this.$toast({
                          message: '注册成功，请返回应用登录',
                          iconClass: 'el-icon-success'
                        })
                        this.isShowLoading = false
                        throw err
                      } else {
                        this.loginOther(response, params)
                      }
                    })
                  } else {
                    this.loginOther(response, params, 3000)
                  }
                } else {
                  let userUU = response.data.content.data.userUU
                  if (userUU) {
                    window.location.href = `/overRegister/${userUU}`
                  } else {
                    window.location.href = `/`
                  }
                }
              } else if (response.data.error) {
                this.$toast({
                  message: response.data.errMsg,
                  iconClass: 'el-icon-error'
                })
              }
            }).catch((err) => {
              this.$indicator.close()
              this.downToast(err.errMsg)
            })
        }
      },
      // 快速登录
      waySubmit () {
        if (this.state.mobile !== 'success') {
          this.codeMobile()
        } else if (this.state.token !== 'success') {
          this.codeToken()
        } else if (this.checked === false) {
          this.downToast('您对阅读条款未做勾选')
        } else {
          this.$indicator.open('注册中...')
          let param = new FormData()
          param.append('mobile', this.mobile)
          // param.append('mobileArea', '')
          param.append('appId', this.$store.state.option.appId)
          param.append('code', this.token)
          param.append('token', this.tokenCode)
          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 = {
            header: {'Content-Type': 'multipart/form-data'}
          }
          this.$http.post('/sso/personal/register/sms', param, config)
            .then(response => {
              this.$indicator.close()
              if (response.data.success) {
                this.$toast({
                  message: '注册成功。登陆密码已发送至您的手机，请妥善保管!',
                  iconClass: 'el-icon-success'
                })
                if (response.data.content.data) {
                  let param = response.data.content.data
                  let a = ''
                  for (let n in param) {
                    a += (n + '=' + encodeURIComponent(param[n]) + '&')
                  }
                  let params = a.substr(0, a.length - 1)
                  this.isShowLoading = true
                  if (response.data.content.currentUrl) {
                    this.$jsonp(`${response.data.content.currentUrl}?${params}`, {
                      name: 'successCallback',
                      timeout: 3000
                    }, (err, data) => {
                      if (err) {
                        this.$toast({
                          message: '注册成功，请返回应用登录',
                          iconClass: 'el-icon-success'
                        })
                        this.isShowLoading = false
                        throw err
                      } else {
                        this.loginOther(response, params)
                      }
                    })
                  } else {
                    this.loginOther(response, params, 5000)
                  }
                } else {
                  let userUU = response.data.content.data.userUU
                  if (userUU) {
                    window.location.href = `/overRegister/${userUU}`
                  } else {
                    window.location.href = `/`
                  }
                }
              } else if (response.data.error) {
                this.$toast({
                  message: response.data.errMsg,
                  iconClass: 'el-icon-error'
                })
              }
            }).catch((err) => {
              this.$indicator.close()
              this.downToast(err.errMsg)
            })
        }
      },
      // 提交注册流程
      allSubmit () {
        if (this.speediness) {
          this.waySubmit()
        } else {
          this.submit()
        }
      },
      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)
            }
          })
        })
      },
      crossAfter (url, time) {
        try {
          if (time) {
            setTimeout(function () {
              window.location.href = url
            }, time)
          } else {
            window.location.href = url
          }
        } catch (err) {
          console.log(err)
        }
      },
      loginOther (response, a, timeout) {
        const crossAfter = this.crossAfter
        let promises = []
        for (let i in response.data.content.loginUrls) {
          if (response.data.content.currentUrl !== response.data.content.loginUrls[i]) {
            promises.push(this.getJsonp(`${response.data.content.loginUrls[i]}?${a}`))
          }
        }
        let returnUrl = this.$route.query.returnURL ? decodeURIComponent(this.$route.query.returnURL) : 'https://www.usoftchina.com/'
        Promise.all(promises).then(() => {
          crossAfter(returnUrl, timeout)
        }).catch(() => {
          crossAfter(returnUrl, timeout)
        })
      }
    }
  }
</script>

<style type="text/scss" scoped lang="scss">
  .content-tab{
    width: 70%;
    margin: 0 auto;
    margin-top:.3rem;
    span{
      display:inline-block;
      width:49%;
      vertical-align:top;
      text-align: center;
      line-height:.6rem;
      height:.6rem;
      font-size:16px;
      border:1px solid #E7E7E7;
      background: #E7E7E7;
      color:#999;
      &.speed{
         color:#3F84F6;
         border:1px solid #3F84F6;
        background: #fff;
       }
    }
  }
</style>

