<template>
  <Layout style="height: 100%" class="main">
    <Sider hide-trigger collapsible  :width="256" :collapsed-width="64" v-model="collapsed" class="left-sider" :style="{overflow: 'hidden'}">
      <side-menu accordion ref="sideMenu" :active-name="$route.name" theme="light" :collapsed="collapsed" @on-select="turnToPage" :menu-list="menuList">
        <!-- 需要放在菜单上面的内容，如Logo，写在side-menu标签内部，如下 -->
        <div class="logo-con">
          <!-- <img v-show="!collapsed" :src="maxLogo" key="max-logo" /> -->
          <div v-show="!collapsed" class="logotitle">公务员平时考核系统</div>
          <img v-show="collapsed" :src="minLogo" key="min-logo" />
        </div>
      </side-menu>
    </Sider>
    <Layout>
      <Header class="header-con">
        <header-bar :collapsed="collapsed" @on-coll-change="handleCollapsedChange">
          <user :message-unread-count="unreadCount" :user-name="userName" :user-avatar="userAvatar"/>
          <div v-if="objectList.length>0" style="margin-right: 20px">
            <Dropdown @on-click="clickChange">
              <Badge>
                <Icon :size="18" type="icon iconfont iconquyu"></Icon>&nbsp;
                <span style="font-size: 13px;font-weight: bold;">{{objectName}}</span>
              </Badge>
              <Icon :size="18" type="md-arrow-dropdown"></Icon>
              <DropdownMenu slot="list">
                <DropdownItem v-for="item in objectList" :name="item.objectId" :key="item.objectId" :selected="objectName==item.objectName">
                  <span style="font-size: 13px;font-weight: bold;">{{item.objectName}}</span>
                </DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </div>
          <notice style="margin-right: 15px;cursor: pointer; "/>
          <fullscreen v-model="isFullscreen" style="margin-right: 10px;"/>
        </header-bar>
      </Header>
      <Content class="main-content-con">
        <Layout class="main-layout-con">
          <!--<div class="tag-nav-wrapper">
            <tags-nav :value="$route" @input="handleClick" :list="tagNavList" @on-close="handleCloseTag"/>
          </div>-->
          <Content class="content-wrapper">
            <keep-alive :include="cacheList">
              <router-view v-if="isRouterAlive"/>
            </keep-alive>
            <ABackTop :height="100" :bottom="80" :right="50" container=".content-wrapper"></ABackTop>
          </Content>
        </Layout>
      </Content>
    </Layout>
  </Layout>
</template>
<script>
//--------------自定义------------------
import Notice from 'bc-common-ui/src/bc-components/bc-main/components/notice'
//-------------------------------------
import SideMenu from 'bc-common-ui/src/bc-components/bc-main/components/side-menu'
import HeaderBar from 'bc-common-ui/src/bc-components/bc-main/components/header-bar'
import TagsNav from 'bc-common-ui/src/bc-components/bc-main/components/tags-nav'
import User from 'bc-common-ui/src/bc-components/bc-main/components/user'
import ABackTop from 'bc-common-ui/src/bc-components/bc-main/components/a-back-top'
import Fullscreen from 'bc-common-ui/src/bc-components/bc-main/components/fullscreen'
import Language from 'bc-common-ui/src/bc-components/bc-main/components/language'
import ErrorStore from 'bc-common-ui/src/bc-components/bc-main/components/error-store'
import { mapMutations, mapActions, mapGetters } from 'vuex'
import { getNewTagList, routeEqual, initRouter } from 'bc-common-ui/src/bc-components/bc-libs/util'
import routers from 'bc-common-ui/src/bc-components/bc-router/routers'
import router from 'bc-common-ui/src/bc-components/bc-router'
import {getRouterReq} from 'bc-common-ui/src/bc-components/bc-router/routers-api'
/*import minLogo from '@/assets/images/logo-min.jpg11'*/
import minLogo from '@/assets/images/bochu.png'
import userImg from '@/assets/images/user.png'
import './main.less'

import {getBasicParamConfigDomain} from '@/api/basic/paramconfig/basicParamConfig-api'

export default {
  name: 'Main',
  components: {
    SideMenu,
    HeaderBar,
    Language,
    TagsNav,
    Fullscreen,
    ErrorStore,
    User,
    ABackTop,
    Notice
  },
  provide () {
    return {
      reload: this.reload
    }
  },
  data () {
    return {
      collapsed: true,
      minLogo,
      maxLogo,
      userImg,
      isFullscreen: false,
      isRouterAlive: true,
      objectId:'',
      objectName:'',
      userType:'',
      objectList:[],
      quarterlyOpenTag:1,
      monthOpenTag:1
    }
  },
  computed: {
    ...mapGetters([
      'errorCount'
    ]),
    tagNavList () {
      return this.$store.state.app.tagNavList
    },
    tagRouter () {
      return this.$store.state.app.tagRouter
    },
    userAvatar () {
      return this.userImg
      //return this.$store.state.user.avatarImgPath
    },
    userId () {
      return this.$store.state.user.userId
    },
    userName () {
      return this.$store.state.user.userName
    },
    cacheList () {
      const list = ['ParentView', ...this.tagNavList.length ? this.tagNavList.filter(item => !(item.meta && item.meta.notCache)).map(item => item.name) : []]
      return list
    },
    menuList () {
      let list = this.$store.getters.menuList;
      for(let l of list){
        let lrs = l.children;
        if(lrs&&lrs.length>0){
          for(let i=lrs.length-1;i>=0;i--){
            let lr = lrs[i];
            let mName = lr.name;
            if(!this.quarterlyOpenTag){
              if(["workTask-manage-quarterly","workTask-quarterly","workTaskTrack-manage-quarterly"].indexOf(mName)>-1){
                lrs.splice(i, 1);
              }
            }
            if(!this.monthOpenTag){
              if(["workTask-manage-month","workTask-month","workTaskTrack-manage-month"].indexOf(mName)>-1){
                lrs.splice(i, 1);
              }
            }
          }
        }
      }
      return list
    },
    local () {
      return this.$store.state.app.local
    },
    hasReadErrorPage () {
      return this.$store.state.app.hasReadErrorPage
    },
    unreadCount () {
      return this.$store.state.user.unreadCount
    }
  },
  methods: {
    ...mapMutations([
      'setBreadCrumb',
      'setTagNavList',
      'addTag',
      'setLocal',
      'setHomeRoute',
      'closeTag',
      'setUserId',
      'setUserName',
      'updateIsInit'
    ]),
    ...mapActions([
      'handleLogin',
      'getUnreadMessageCount'
    ]),
    clickChange(objectid){
          if(this.objectId==objectid)return
          this.$Modal.confirm({
              title: '系统提示',
              width: '360',
              loading:true,
              content: '<p>确定切换吗？</p>',
              onCancel: () => {
              },
              onOk: () => {
                  this.objectList.forEach((item,i)=>{
                      if(item.objectId == objectid){
                          this.objectId = item.objectId;
                          this.objectName = item.objectName;
                          this.$userUtil.setCurrentObject(item);
                          //刷新单位信息
                          this.$userUtil.refreshCompanyList(item,data=>{
                              this.reload();
                              this.$Modal.remove();
                              this.$Message.success("切换成功!");
                          });

                          /*this.$refreshCompanys(item.objectid,data=>{
                            this.$refreshSequenceTree(item.objectid,data=>{
                              this.reload();
                              this.$Modal.remove();
                              this.$Message.success("切换成功!")
                            })
                          })*/
                      }
                  })
              }
          });
    },
    reload () {
      this.isRouterAlive = false;
        this.$nextTick(function () {
          this.isRouterAlive = true
      })
    },
    turnToPage (route) {
      let { name, params, query } = {}
      if (typeof route === 'string') {
        name = route
        params = {nowMenuName: name}
      } else {
        name = route.name
        params = route.params?route.params:{nowMenuName: name}
        query = route.query
      }
      if (name.indexOf('isTurnByHref_') > -1) {
        window.open(name.split('_')[1])
        return
      }
      this.$router.push({
        name,
        params,
        query
      })
    },
    handleCollapsedChange (state) {
      this.collapsed = state
    },
    handleCloseTag (res, type, route) {
      if (type !== 'others') {
        if (type === 'all') {
          this.turnToPage(this.$config.homeName)
        } else {
          if (routeEqual(this.$route, route)) {
            this.closeTag(route)
          }
        }
      }
      this.setTagNavList(res)
    },
    handleClick (item) {
      this.turnToPage(item)
    },
    getBindingInfo(){
          let userType = '';//0：业务员、1：人社局、2：组织部 3：主管单位 -1：普通单位
          let areas = this.$store.state.user.extendedAttribute.areas;
          let areaList = this.$store.state.user.extendedAttribute.bindingAreas;
          let companyList = this.$store.state.user.extendedAttribute.bindingCompanys;
          if(areaList!=null&&areaList.length > 0){
              userType = '0';
              this.objectId = areaList[0].id;
              this.objectName = areaList[0].areaName;
              this.$userUtil.setCurrentObject({
                  objectId: areaList[0].id,
                  objectName: areaList[0].areaName,
                  userType: userType,
                  areaId: areaList[0].id,
                  areaCode: areaList[0].areaCode,
                  areaName: areaList[0].areaName,
              });
              areaList.forEach(item=>{
                  this.objectList.push({
                      objectId: item.id,
                      objectName: item.areaName,
                      userType: userType,
                      areaId: item.id,
                      areaCode: item.areaCode,
                      areaName: item.areaName,
                  });
              });
          }else if(companyList.length > 0){
              let companyType = '0';
              for(let item of companyList){
                  if('1'==item.companyType||'2'==item.companyType||'3'==item.companyType){
                      companyType = item.companyType;
                      break;
                  }
              }
              if(companyType == '0'){
                  userType = '-1';
              }else if(companyType == '1'){//人社局
                  userType = '1';
              }else if(companyType == '2'){//组织部
                  userType = '2';
              }else if(companyType == '3'){//主管单位
                  userType = '3';
              }
              this.objectId = areas[0].id;
              this.objectName = areas[0].areaName;
              this.$userUtil.setCurrentObject({
                  objectId: this.objectId,
                  objectName: this.objectName,
                  userType: userType,
                  areaId: areas[0].id,
                  areaCode: areas[0].areaCode,
                  areaName: areas[0].areaName,
                  companys: areas[0].companys
              });
              areas.forEach(item=>{
                  this.objectList.push({
                      objectId: item.id ,
                      objectName: item.areaName ,
                      userType: userType,
                      areaId: item.id ,
                      areaCode: item.areaCode ,
                      areaName: item.areaName ,
                      companys: item.companys
                  });
              });
          }else{
              this.$Message.warning({
                  content: '该账号没有绑定区域或单位，请联系管理员!',
                  duration: 60,
                  closable: true
              });
          }
    }
  },
  watch: {
    '$route' (newRoute) {
      const { name, query, params, meta } = newRoute
      this.addTag({
        route: { name, query, params, meta },
        type: 'push'
      })
      this.setBreadCrumb(newRoute)
      this.setTagNavList(getNewTagList(this.tagNavList, newRoute))
      this.$refs.sideMenu.updateOpenName(newRoute.name)
    }
  },
  created() {
    this.$BusinessDictUtil.initDict();
    this.getBindingInfo();

    getBasicParamConfigDomain(res => {
      if (res) {
        this.quarterlyOpenTag = res.quarterlyOpenTag;
        this.monthOpenTag = res.monthOpenTag;
      }
    });
  },
  mounted () {
    // 异步初始化菜单
    /*if (this.$store.getters.isInit){

    }*/
    getRouterReq().then(res => {
      //处理异步获取的菜单
      //this.updateIsInit(false)
      initRouter(this, res.data.result);

    }).catch(err =>{
      console.log(err);
      this.$Message.error('菜单加载失败!请稍后再试或联系管理员');
    })

    /**
     * @description 初始化设置面包屑导航和标签导航
     */
    this.setTagNavList()
    this.setHomeRoute(routers)
    const { name, params, query, meta } = this.$route
    this.addTag({
      route: { name, params, query, meta }
    })
    this.setBreadCrumb(this.$route)

    // 设置初始语言
    this.setLocal(this.$i18n.locale)
    // 如果当前打开页面不在标签栏中，跳到homeName页
    if (!this.tagNavList.find(item => item.name === this.$route.name)) {
      this.$router.push({
        name: this.$config.homeName
      })
    }
    // 获取未读消息条数
    //this.getUnreadMessageCount()

  }
}
</script>
