<template>
  <div class="logout">
    <loading/>
    <p>退出中，请稍后...</p>
  </div>
</template>

<script>
  import Loading from '~components/common/loading/Loading.vue'
  export default {
    name: 'logout',
    layout: 'mobile',
    components: {
      Loading
    },
    mounted () {
      this.$nextTick(() => {
        this.logquit()
      })
    },
    methods: {
      logquit () {
        this.$http.get('/sso/login/logout', {params: this.$route.query})
          .then(response => {
            if (response.data.success) {
              let param = response.data.content.logoutUrls
              let a = ''
              for (let n in param) {
                a += (n + '=' + encodeURIComponent(param[n]) + '&')
              }
              let params = a.substr(0, a.length - 1)
              if (this.$route.query.baseUrl) {
                this.$jsonp(this.$route.query.baseUrl, {
                  name: 'successCallback',
                  timeout: 3000
                }, (err, data) => {
                  if (err) {
                    this.$message.error('退出失败，请重试')
                    throw err
                  } else {
                    this.logoutOther(response, params)
                  }
                })
              } else {
                this.logoutOther(response, params, 3000)
              }
            }
          })
      },
      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)
        }
      },
      logoutOther (response, a, timeout) {
        const crossAfter = this.crossAfter
        let promises = []
        for (let i in response.data.content.logoutUrls) {
          if (this.$route.query.baseUrl !== response.data.content.logoutUrls[i]) {
            promises.push(this.getJsonp(`${response.data.content.logoutUrls[i]}`))
          }
        }
        Promise.all(promises).then(() => {
          crossAfter(response.data.content.returnURL || 'http://www.ubtob.com', timeout)
        }).catch(() => {
          crossAfter(response.data.content.returnURL || 'http://www.ubtob.com', timeout)
        })
      }
    }
  }
</script>
<style type="text/scss" lang="scss" scoped>
  .logout{
    p{
      position: fixed;
      left: 0;
      right:0;
      top: 54%;
      z-index: 1000;
      text-align: center;
      font-size: 14px;
      color:#333;
    }
  }
</style>
