<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" @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 + '=' + param[n] + '&')
                }
                const crossAfter = this.crossAfter
                let promises = []
                for (let i in response.data.content.loginUrls) {
                  promises.push(this.getJsonp(`${response.data.content.loginUrls[i]}?` + a.substr(0, a.length - 1)))
                }
                Promise.all(promises).then(() => {
                  crossAfter(response.data.content.returnUrl || 'http://www.ubtob.com')
                }).catch(() => {
                  crossAfter(response.data.content.returnUrl || 'http://www.ubtob.com')
                })
                // for (let i in response.data.content.loginUrls) {
                //   this.$jsonp(`${response.data.content.loginUrls[i]}?` + a.substr(0, a.length - 1), function (err, data) {
                //     if (err) throw err
                //     console.log(data)
                //   })
                // }
                // setTimeout(function () {
                //   window.location.href = response.data.content.returnUrl || 'http://www.ubtob.com'
                // }, 3000)
              }
            } else {
              return Promise.reject(response.data)
            }
          }).catch(err => {
            this.$message.error(err.errMsg)
          })
      },
      getJsonp: function (url) {
        return new Promise((resolve, reject) => {
          this.$jsonp(url, {
            name: 'successCallback',
            timeout: 200
          }, function (err, data) {
            if (err) {
              reject(err)
              throw err
            } else {
              resolve(data)
            }
          })
        })
      },
      crossAfter (url) {
        try {
          window.location.href = url
        } catch (err) {
          console.log(err)
        }
      }
    }
  }
</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>
