
<template>
  <ul class="nav navbar-nav navbar-right">
    <li class="dropdown">
      <a
        v-if="loginInfo"
        
        class="dropdown-toggle"
        data-toggle="dropdown"
        role="button"
        aria-haspopup="true"
        aria-expanded="false"
      >
        {{ loginClientName }}
        <span class="caret" />
      </a>
      <ul
        v-if="clientCanAccessList != null && clientCanAccessList.length > 0"
        class="dropdown-menu"
      >
        <li
          v-for="clientCanAccess in clientCanAccessList"
          :key="clientCanAccess.id"
        >
          <a @click="changeTokenClient(clientCanAccess.id)">{{ clientCanAccess.name }}</a>
        </li>
      </ul>
    </li>
  </ul>
</template>

<script>

import Common from '../common/Common.js';
import ClientResourceV2 from '../api/base/ClientResourceV2.js';
import TokenClientResource from '../api/base/TokenClientResource.js';
import { Notify, Uuid } from 'pc-component-v3';

export default {
  props: {
    loginInfo: {
      type: Object,
      default: function(){
        return null;
      },
    },
  },

  data: function () {
    return {
      clientCanAccessList: [],
      loginClientName:'',
    };
  },


  mounted: function () {
    this.listClientCanAccess();
    this.queryTokenClient();
  },

  methods: {
    /**
     * 获取可以访问的公司
     */
    listClientCanAccess: function () {
      var _self = this;
      ClientResourceV2.listClientCanAccess().then(baseListResponse => {
        if (baseListResponse.errorCode == 0) {
          _self.clientCanAccessList = baseListResponse.datas;
        } else {
          Notify.error(_self.$t('lang.Notify.error'), baseListResponse.errorMessage, false);
        }
      }, errorData => {
        Common.processException(errorData);
      });
    },

    /**
     * 切换公司
     */
    changeTokenClient: function (clientId) {
      var _self = this;
      console.log(_self.loginInfo);
      const tokenClientChangeRequest = {
        userId: _self.loginInfo.userId,
        clientId: clientId,
        token: _self.loginInfo.token,
      };

      TokenClientResource.changeTokenClient(tokenClientChangeRequest).then(baseObjectResponse => {
        if (baseObjectResponse.errorCode == 0) {
          // Notify.success('正确','公司切换成功',true);
          _self.queryTokenClient();
          window.location.reload();
        }else{
          Notify.error(_self.$t('lang.Notify.companySwitchFailed'), baseObjectResponse.errorMessage, false);
        }
      }, errorData => {
        Common.processException(errorData);
      });
    },

    /**
     * 查询设置的公司
     */
    queryTokenClient: function () {
      var _self = this;
      TokenClientResource.queryTokenClient().then(baseObjectResponse => {
        if (baseObjectResponse.errorCode == 0) {
          _self.loginClientName = baseObjectResponse.data.clientName;
        }
      }, errorData => {
        Common.processException(errorData);
      });
    },
  },
};
</script>

