<template>
  <div>
    <div class="logout">
      <loading/>
      <p>跳转中，请稍后...</p>
    </div>
    <template v-if="isMobile">
      <mt-popup v-model="popupVisible" position="right" class="mint-popup" :modal="false">
        <ul style="height:100vh;overflow-y:auto">
          <li class="listitem itemgreen">选择您要登录的公司：</li>
          <li v-for="item in enterprise" class="listitem enName" @click="selectEnterprise(false, item.id)">{{ item.name }}</li>
        </ul>
      </mt-popup>
    </template>
  </div>
</template>

<script>
  import Loading from '~components/common/loading/Loading.vue'
  export default {
    name: 'agency',
    layout: 'mobile',
    data () {
      return {
        popupVisible: false,
        spaceUU: ''
      }
    },
    components: {
      Loading
    },
    mounted () {
      this.$nextTick(() => {
        this.agency(true)
      })
    },
    computed: {
      isMobile () {
        return this.$store.state.option.isMobile
      },
      enterprise () {
        return this.$store.state.login.chooseRegisterEnterprise.choose.data
      }
    },
    methods: {
      selectEnterprise (flag, type) {
        // console.log('type', type)
        this.spaceUU = type
        this.popupVisible = flag
        this.agency(flag)
      },
      agency (flag) {
        let param = new FormData()
        param.append('returnUrl', this.$route.query.returnURL || '')
        param.append('appId', this.$route.query.appId || '')
        param.append('token', this.$route.query.token || '')
        param.append('baseUrl', this.$route.query.baseURL || '')
        param.append('spaceUU', this.spaceUU || this.$route.query.spaceUU || '')
        param.append('isLoginAll', this.$route.query.isLoginAll || '')
        let config = {
          headers: {'Content-Type': 'multipart/form-data'}
        }
        let url = this.$store.state.option.isMobile ? '/sso/login/mobile/proxy' : '/sso/login/proxy'
        this.$http.post(url, param, config)
          .then(response => {
            if (response.data.success) {
              // console.log('res', response.data.content)
              if (response.data.content.spaces) {
                this.$store.commit('login/chooseRegisterEnterprise/GET_ENTERPRISE_SUCCESS', response.data.content.spaces)
                this.popupVisible = flag
              } else if (response.data.content.loginUrls) {
                // 遍历登录url循环让各应用登录(需要跨域)
                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)
                if (response.data.content.currentUrl) {
                  this.$jsonp(`${response.data.content.currentUrl}?${params}`, {
                    name: 'successCallback',
                    timeout: 5000
                  }, (err, data) => {
                    const crossAfter = this.crossAfter
                    if (err) {
                      this.$indicator.close()
                      this.$toast({
                        message: '登录超时，即将跳转...',
                        iconClass: 'el-icon-error'
                      })
                      setTimeout(() => {
                        crossAfter(response.data.content.returnUrl || 'http://www.usoftchina.com')
                      }, 1000)
                      throw err
                    } else {
                      this.loginOther(response, params)
                    }
                  })
                } else {
                  this.loginOther(response, params, 3000)
                }
              } else {
                window.location.href = response.data.content.returnUrl || 'http://www.usoftchina.com'
              }
            } else {
              return Promise.reject(response.data)
            }
          }).catch(err => {
            this.$message.error(err.errMsg)
            setTimeout(() => {
              this.crossAfter(this.$route.query.returnURL || 'http://www.usoftchina.com')
            }, 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)
        }
      },
      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}`))
          }
        }
        Promise.all(promises).then(() => {
          crossAfter(response.data.content.returnUrl || 'http://www.usoftchina.com', timeout)
        }).catch(() => {
          crossAfter(response.data.content.returnUrl || 'http://www.usoftchina.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;
    }
  }
  .enName {
    color: #000000 !important;
  }
</style>
