<!-- 主数据管理门户首页 -->
<template>
  <div class="dg-sidebar-frame">
    <dg-page-header></dg-page-header>
    <div v-if="!loading" class="main">
      <div id="index">
        <!--灰色风格-->
        <div v-if="!hideLeftMenu" id="frame-left" class="frame-left-ali" :style="{ width: frameWidth + 'px' }">
          <div id="indexDiv-ali" @click="clickIndexDiv">
            <i id="icon" :class="collapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'"></i>
          </div>
          <dg-menu
            id="indexMenu-ali"
            ref="dgMenuAliyun"
            api-code="sysUserMenu"
            text-color="#dddddd"
            background-color="#404040"
            title-style="height:0;padding:0;margin:0;font-size:0;"
            :root="menuRoot"
            :collapse="collapse"
            key-field="MENU_CODE"
            pkey-field="PARENTCODE"
            title-field="NAME"
            :query-terms="queryTerms"
            route-field="URL"
            @select="changeTab"
          ></dg-menu>
        </div>
        <div id="frame-right" class="frame-right" :style="{ left: frameWidth + 'px' }">
          <div v-if="navShow == 'true'" id="Breadcrumb" style="margin-bottom: 1px">
            <Breadcrumb></Breadcrumb>
            <!-- 公告 -->
            <div v-if="noticeShow == 'true'" id="public">
              <dg-notice></dg-notice>
            </div>
          </div>
          <div id="indexTab" :style="{ height: indexTabHeight }">
            <router-view></router-view>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<!-- 主数据管理门户首页 -->
<script>
// import DgMenu from '@comm/components/DgMenu';
// import PageHeader from './Header';
// import Breadcrumb from '@comm/components/Breadcrumb';
// import DgNotice from '@comm/components/DgNotice';
// import { loginUrl, getPortalUserInfo,DgJsonStore } from '../../api/api';

export default {
  name: 'DgSidebarFrame',
  data() {
    return {
      queryTerms: 'isshow=true',
      menuRoot: 'dva-mdmportal',
      collapse: false,
      backgroundColor: '#545c64',
      textColor: '#FFF',
      frameWidth: 180,
      activeName: '',
      tabPanes: [],
      noticeShow: 'false',
      navShow: 'true',
      indexTabHeight: 'calc(100% - 46px)',
      userId: '',
      loading: true,
      //阿里对接
      hideLeftMenu: false,
      inited: false,
    }
  },
  watch: {
    tabIndex(val) {
      this.activeName = val.toString()
    },
  },
  created() {
    this.init()
  },
  mounted() {
    this.getAllUserInfo()
    this.init()
  },
  methods: {
    // 收缩左侧菜单
    clickIndexDiv() {
      if (this.hideLeftMenu) {
        this.frameWidth = 0
        return
      }
      this.collapse = !this.collapse
      this.frameWidth = this.collapse ? 64 : 180
    },
    // 点击标签页
    handleClick(pane) {
      this.$router.push({
        path: pane.name,
      })
    },
    // 切换标签页
    changeTab(treeNode) {
      console.log('tab>>>' + treeNode.URL)
      if (treeNode.URL) {
        this.$router.push({
          name: treeNode.URL,
        })
        this.activeName = treeNode.URL
        for (let pane of this.tabPanes) {
          if (pane.name === treeNode.URL) return
        }
        this.tabPanes.push({ label: treeNode.NAME, name: treeNode.URL })
      }
    },
    // 获取所有用户信息并缓存
    async getAllUserInfo() {
      const res = await this.$moduleApiData.DgJsonStore({
        apiCode: 'sysUser',
        params: `command=init&VALID_STATE=生效`,
      })
      // TODO 增加优化用户功能
      if (res && res.root) {
        let data = {
          apiCode: 'allUser',
          dimKey: 'allUser',
          selectOptions: [],
        }
        const users = res.root.map((item) => {
          return { name: item.CNNAME, id: item.USER_ID }
        })
        data.selectOptions = res.root.map((item) => {
          return { name: item.CNNAME, id: item.USER_ID }
        })
        window.localStorage.setItem(
          'allUser',
          JSON.stringify(
            res.root.map((item) => {
              return { cnname: item.CNNAME, userId: item.USER_ID }
            })
          )
        )
        this.$store?.commit('SAVE_DIM', data)
      } else {
        this.$message({
          message: '获取用户和角色信息失败！',
          type: 'danger',
        })
      }
    },
    async init() {
      if (this.inited) {
        return
      }
      if (window.sessionStorage.getItem('getUserInfoError')) {
        window.localStorage.removeItem('vuex')
        window.localStorage.removeItem('token')
        const orig = window.location.origin
        // window.location = `http://idm.hbisco.com/cas/logout?service=${orig}${loginUrl}`+ window.location.href;
      }
      // TODO 写死了，待优化
      const r = await this.$moduleApiData.getPortalUserInfo()
      console.log('获取用户', r)
      if (!r || r.code == '401' || !r.data.attributes.userName) {
        window.sessionStorage.setItem('getUserInfoError', JSON.toString(r))
        window.location = this.$moduleApiData.loginUrl + window.location.href
        // this.loading = false
      } else {
        this.loading = false
        this.userId = r.data.id
        const token = r.data.token
        window.localStorage.setItem(`token`, token)
        const rolesRes = await this.$moduleApiData.DgJsonStore({
          apiCode: 'sys_get_role_by_user',
          params: `command=init&resType=user&user=${this.userId}`,
        })
        // TODO 增加优化用户功能
        let roles = {}
        if (rolesRes && rolesRes.root) {
          ;(rolesRes.root || []).forEach((el) => {
            roles[el['ROLE_ID']] = el['CNNAME']
          })
        }
        const userInfo = {
          userId: r.data.id,
          username: r.data.attributes.userName,
          roleNames: (Object.values(roles) || []).join(','),
        }
        this.$store?.dispatch('InitUserInfo', userInfo)
        window.localStorage.setItem('user', userInfo)
        let test = window.localStorage.getItem('vuex')
        console.log(test, 'zj_test local user')
        setTimeout(() => {
          this.queryTerms = 'isshow=true&userId=' + r.data.id + '&role=' + (Object.keys(roles) || []).join(',')
          this.$router.push({
            path: '/mdmportal/myWorkbench',
          })
        }, 150)
      }

      if (this.$store.state.notice) {
        this.noticeShow = this.$store?.state?.notice?.show
        console.log(this.noticeShow, '117')
      }
      if (this.$store.state.navigation) {
        this.navShow = this.$store?.state?.navigation?.show
        if (this.navShow != 'true') this.indexTabHeight = '100%'
        console.log(this.navShow, '119')
      }
      this.inited = true
    },
  },
}
</script>
