<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>
    <template v-if="step === 1">
      <div class="f-form">
        <div class="page-part">
          <mt-field placeholder="手机号码"
                    v-model="step1.mobile"
                    :state="state.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 auto-complete="off"
                    placeholder="短信验证码"
                    v-model="step1.token"
                    :state="state.token">
            <span class="token" @click="getCheckCode" v-text="tokenText">获取验证码</span>
          </mt-field>
        </div>
      </div>
      <div class="form-btn">
        <div class="page-part">
          <el-checkbox v-model="checked">我已阅读并同意 <a href="/common/agreement" class="rgba">《优软云服务条款》</a></el-checkbox>
        </div>
        <mt-button type="primary" size="large" @click.native="checkPhone">验证手机</mt-button>
      </div>
    </template>
    <template v-if="step === 2">
      <div class="f-form">
        <div class="page-part">
          <mt-field placeholder="企业名称"
                    :attr="{ maxlength: 20 }"
                    v-model="step2.spaceName"
                    :state="state.spaceName"></mt-field>
        </div>
        <div class="page-part">
          <mt-field placeholder="营业执照号"
                    v-model="step2.businessCode"
                    :state="state.businessCode"></mt-field>
        </div>
        <div class="page-part" v-if="!hasRegister">
          <mt-field placeholder="管理员姓名"
                    v-model="step2.vipName"
                    :state="state.vipName"></mt-field>
        </div>
        <div class="page-part" v-if="!hasRegister">
          <mt-field placeholder="登录密码"
                    :attr="{ maxlength: 20 }"
                    v-model="step2.password"
                    :state="state.password"
                    type="password"
                    auto-complete="new-password"
                    @input.native="validatePassword"></mt-field>
          <template v-if="step2.password">
            <p class="pwd">密码强度 <em :class="{sm:progress === '弱', md: progress === '中', ld:progress === '强'}"></em> <em :class="{md: progress === '中', ld:progress === '强'}"></em> <em :class="{ld:progress === '强'}"></em> <span :class="{smstep:progress === '弱', mdstep: progress === '中', ldstep:progress === '强'}" v-text="progress">强</span></p>
            <p class="pwd">密码须为8-20字符的英文、数字混合</p>
          </template>
        </div>
        <div class="page-part" v-if="hasRegister">
          <mt-field placeholder="登录密码"
                    v-model="step2.password"
                    :state="state.password"
                    type="password"
                    auto-complete="new-password"></mt-field>
          <template v-if="!step2.password">
            <p class="pwd" style="text-align:right;"><a href="/reset/forgetPasswordValidationAccount">忘记密码?</a></p>
          </template>
          <template v-if="step2.password">
            <p class="pwd">手机号已注册，请输入原密码</p>
          </template>
        </div>
        <div class="page-part" v-if="!hasRegister">
          <mt-field placeholder="密码确认"
                    v-model="step2.confirm"
                    :state="state.confirm"
                    type="password"
                    auto-complete="new-password"></mt-field>
        </div>
        <div class="page-part" v-if="!hasEmail">
          <mt-field placeholder="联系邮箱"
                    v-model="step2.email"
                    :state="state.email"
                    type="email"></mt-field>
        </div>
      </div>
      <div class="form-btn">
        <mt-button type="primary" size="large" @click.native="sureRegister">完成注册</mt-button>
      </div>
    </template>
  </div>
</template>

<script>
  export default {
    name: 'registerEnterprise',
    data () {
      return {
        code: '',
        imgSrc: '',
        step: 1,
        state: {
          mobile: 'error',
          token: 'error',
          spaceName: 'error',
          businessCode: 'error',
          vipName: 'error',
          password: 'error',
          confirm: 'error',
          email: null
        },
        step1: {
          mobile: '',
          token: ''
        },
        step2: {
          spaceName: '',
          businessCode: '',
          vipName: '',
          password: '',
          confirm: '',
          email: ''
        },
        checked: true,
        tokenCode: '',
        tokenTime: 60,
        tokenText: '获取验证码',
        hasRegister: false,
        hasEmail: false,
        progress: '弱'
      }
    },
    mounted () {
      this.$nextTick(() => {
        this.getCode()
      })
    },
    watch: {
      'step1.token': {
        handler (newVal) {
          if (newVal.length === 6) {
            this.validateCode()
          }
        },
        immediate: true
      }
    },
    methods: {
      getCode () {
        this.imgSrc = '/sso/resetPwd/checkCaptcha?timestamp=' + (new Date()).valueOf()
      },
      // 注册
      goRegister () {
        window.location.href = `/register/personalRegistration${this.$store.state.option.fullPath}`
      },
      // 弹窗处理
      downToast (type) {
        this.$toast({
          message: type,
          iconClass: 'el-icon-warning'
        })
      },
      // 验证手机号
      validateMobile () {
        let reg = /^1[0-9]{10}$/
        if (!this.step1.mobile) {
          this.downToast('请先填写手机号')
          this.state.mobile = 'error'
        } else {
          if (!reg.test(this.step1.mobile)) {
            this.downToast('请填写正确的手机号')
            this.state.mobile = 'warning'
          } else {
            this.state.mobile = 'success'
          }
        }
      },
      // 验证正确的验证码
      validateCode () {
        if (!this.step1.token) {
          this.downToast('请先填写验证码')
          this.state.token = 'error'
        } else {
          if (!this.step1.mobile) {
            this.downToast('请先填写正确的手机号码')
            this.state.token = 'warning'
          } else {
            if (this.tokenCode) {
              let param = new FormData()
              param.append('mobile', this.step1.mobile)
              param.append('token', this.tokenCode)
              param.append('code', this.step1.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'
            }
          }
        }
      },
      // 获取验证码
      getCheckCode () {
        if (this.tokenTime > 0 && this.tokenTime < 60) {
          this.downToast('请稍后再点击，我在倒计时')
        } else if (this.code === '') {
          this.downToast('请输入验证码后获取！')
        } else {
          this.validateMobile()
          if (this.state.mobile === 'success') {
            this.$indicator.open('获取中...')
            let _this = this
            this.$http.get('/sso/personal/register/checkCode', {params: {mobile: this.step1.mobile, timestamp: new Date().getTime() + '', code: this.code}})
              .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(() => {
                this.$indicator.close()
                this.downToast('获取失败，请检查网络')
              })
          }
        }
      },
      // 验证手机
      checkPhone () {
        if (this.state.mobile !== 'success') {
          this.validateMobile()
        } else if (this.state.token !== 'success') {
          this.validateCode()
        } else if (this.checked === false) {
          this.downToast('您对阅读条款未做勾选')
        } else {
          this.$indicator.open('验证手机中...')
          let param = new FormData()
          param.append('mobile', this.step1.mobile)
          param.append('code', this.step1.token)
          param.append('appId', this.$store.state.option.appId)
          param.append('token', this.tokenCode)
          let config = {
            headers: {'Content-Type': 'multipart/form-data'}
          }
          this.$http.post('/sso/userspace/register/checkAdminTel', param, config)
            .then(response => {
              this.$indicator.close()
              if (response.data.success) {
                response.data.content.hasEmail ? this.hasEmail = true : this.hasEmail = false
                response.data.content.hasRegister ? this.hasRegister = true : this.hasRegister = false
                this.step = 2
              }
            }).catch((err) => {
              this.$indicator.close()
              this.downToast(err.errMsg)
            })
        }
      },
      // 验证企业名
      validateSpaceName () {
        if (!this.step2.spaceName) {
          this.downToast('请填写企业名称')
          this.state.spaceName = 'error'
        } else {
          if (this.step2.spaceName.length > 20) {
            this.downToast('输入长度过长，限定20个字符以内')
            this.state.spaceName = 'warning'
          } else {
            this.$http.get(`/api/userspace/checkSpaceName`, {params: {spaceName: this.step2.spaceName}})
              .then(response => {
                if (response.data.success) {
                  this.state.spaceName = 'success'
                } else {
                  this.state.spaceName = 'warning'
                  this.downToast(response.data.errMsg)
                }
              })
          }
        }
      },
      // 验证营业号
      validateBusinessCode () {
        let reg = /^[A-Za-z0-9]+$/
        if (!this.step2.businessCode) {
          this.downToast('请填写营业执照号')
          this.state.businessCode = 'error'
        } else {
          if (!reg.test(this.step2.businessCode)) {
            this.downToast('请填写正确的营业执照号')
            this.state.businessCode = 'warning'
          } else {
            this.$http.get(`/api/userspace/checkBusinessCode`, {params: {businessCode: this.step2.businessCode}})
              .then(response => {
                if (response.data.success) {
                  this.state.businessCode = 'success'
                } else {
                  this.state.businessCode = 'warning'
                  this.downToast(response.data.errMsg)
                }
              })
          }
        }
      },
      // 验证管理员名
      validateVipName () {
        if (!this.step2.vipName) {
          this.downToast('请填写管理员姓名')
          this.state.vipName = 'error'
        } else {
          if (this.step2.vipName.length > 20) {
            this.downToast('输入长度请限制在20个字符以内')
            this.state.vipName = 'warning'
          } else {
            this.state.vipName = 'success'
          }
        }
      },
      // 验证密码强度
      validatePassword () {
        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.step2.password)) {
          this.progress = '强'
        } else if (reg2.test(this.step2.password)) {
          this.progress = '中'
        } else {
          this.progress = '弱'
        }
      },
      // 验证密码
      validatePasswordTip () {
        let reg2 = /^(?=.{8,20})(((?=.*[0-9])(?=.*[a-z]))|((?=.*[0-9])(?=.*[A-Z]))).*$/
        if (!this.step2.password) {
          this.downToast('请输入密码')
          this.state.password = 'error'
        } else {
          if (!reg2.test(this.step2.password)) {
            this.downToast('密码须为8-20字符的英文、数字混合')
            this.state.password = 'warning'
          } else {
            this.state.password = 'success'
            if (this.step2.confirm) {
              this.validateConfirm()
            }
          }
        }
      },
      // 验证密码
      validatePasswordTipHas () {
        if (!this.step2.password) {
          this.downToast('请输入密码')
          this.state.password = 'error'
        } else {
          this.state.password = 'success'
        }
      },
      // 验证二次密码
      validateConfirm () {
        if (!this.step2.confirm) {
          this.downToast('请再次输入密码')
          this.state.confirm = 'error'
        } else {
          if (this.step2.confirm === this.step2.password) {
            this.state.confirm = 'success'
          } else {
            this.state.confirm = 'warning'
            this.downToast('两次输入密码不一致，请重新输入')
          }
        }
      },
      // 验证邮箱
      validateEmail () {
        let reg = /^([\w-])+(\.\w+)*@([\w-])+((\.\w{2,3}){1,3})$/
        if (this.step2.email) {
          if (!reg.test(this.step2.email)) {
            this.downToast('请输入正确的邮箱地址格式')
            this.state.email = 'warning'
          } else {
            this.$http.get('/api/user/checkEmail', {params: {email: this.step2.email}})
              .then(response => {
                if (response.data.hasRegister) {
                  this.state.email = 'warning'
                  this.downToast('该邮箱已被注册')
                } else {
                  this.state.email = 'success'
                }
              }).catch((err) => {
                this.downToast(err.errMsg)
              })
          }
        } else {
          // this.downToast('请填写联系邮箱信息')
          this.state.email = 'success'
        }
      },
      // 注册请求方法
      sbmitRegister () {
        this.$indicator.open('注册中...')
        let param = new FormData()
        param.append('spaceName', this.step2.spaceName)
        param.append('businessCode', this.step2.businessCode)
        param.append('vipName', this.step2.vipName || '')
        param.append('password', this.step2.password)
        param.append('email', this.step2.email || '')
        param.append('appId', this.$store.state.option.appId)
        param.append('inviteSpaceUU', this.$store.state.option.inviteSpaceUU)
        param.append('inviteUserUU', this.$store.state.option.inviteUserUU)
        param.append('invitationTime', this.$store.state.option.invitationTime)
        param.append('t', this.$route.query.tk ? this.$route.query.tk : '')
        param.append('returnUrl', this.$route.query.returnURL ? this.$route.query.returnURL : '')
        let config = {
          headers: {'Content-Type': 'multipart/form-data'}
        }
        this.$http.post('/sso/userspace/register', param, config)
          .then(response => {
            this.$indicator.close()
            if (response.data.success) {
              if (response.data.content) {
                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.$message.error('注册成功，请点击下方“立即登录”完成登录')
                      this.isShowLoading = false
                      throw err
                    } else {
                      this.loginOther(response, params)
                    }
                  })
                } else {
                  this.loginOther(response, params, 3000)
                }
              } else {
                window.location.href = '/overRegister/overEnterprise'
              }
            } else {
              this.downToast(response.data.errMsg)
            }
          }).catch((err) => {
            this.$indicator.close()
            this.downToast(err.errMsg)
          })
      },
      // 企业注册
      sureRegister () {
        if (!this.hasRegister) {
          if (this.state.spaceName !== 'success') {
            this.validateSpaceName()
          } else if (this.state.businessCode !== 'success') {
            this.validateBusinessCode()
          } else if (this.state.vipName !== 'success') {
            this.validateVipName()
          } else if (this.state.password !== 'success') {
            this.validatePasswordTip()
          } else if (this.state.confirm !== 'success') {
            this.validateConfirm()
          } else if (this.state.email !== 'success') {
            this.validateEmail()
          } else {
            this.sbmitRegister()
          }
        } else {
          if (!this.hasEmail) {
            if (this.state.spaceName !== 'success') {
              this.validateSpaceName()
            } else if (this.state.businessCode !== 'success') {
              this.validateBusinessCode()
            } else if (this.state.password !== 'success') {
              this.validatePasswordTip()
            } else if (this.state.email !== 'success') {
              this.validateEmail()
            } else {
              this.sbmitRegister()
            }
          } else {
            if (this.state.spaceName !== 'success') {
              this.validateSpaceName()
            } else if (this.state.businessCode !== 'success') {
              this.validateBusinessCode()
            } else if (this.state.password !== 'success') {
              this.validatePasswordTipHas()
            } else {
              this.sbmitRegister()
            }
          }
        }
      },
      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) {
        try {
          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 = decodeURIComponent(this.$route.query.returnURL)
        Promise.all(promises).then(() => {
          crossAfter(returnUrl || 'http://www.ubtob.com', timeout)
        }).catch(() => {
          crossAfter(returnUrl || 'http://www.ubtob.com', timeout)
        })
      }
    }
  }
</script>
