<!-- @desc:主页面  @auth:周兴  @time:2022/4/3 9:56 -->
<template>
  <div style="height: 100%" @mousemove="mousemove">
<!--    <div class="tag-nav-wrapper">-->

<!--    </div>-->
    <!--左侧菜单栏-->
    <Layout v-if="hideHeadAndLeft===0" class="main">
      <!--      <Sider hide-trigger collapsible :width="!collapsed?(menuType==='drawer'?180:200):60" :collapsed-width="64" v-model="collapsed"-->
<!--      :style="{overflow: 'hidden',cursor:!collapsed?'ew-resize':'' }"-->
      <Sider hide-trigger collapsible :width="!collapsed?siderWidth:60" :collapsed-width="64" v-model="collapsed"
             :class="'left-sider ' + (menuType==='tree'?'left-sider-menu-tree':'') "
             :style="{overflow: 'hidden'}"
             @mouseleave.native="leaveDrawer" @mousedown.native="startDrag">
        <div>
          <side-menu @on-collapsed-change="collapseChange" :mouse-position="mousePosition" accordion ref="sideMenu"
                     :active-name="$route.name" :collapsed="collapsed" @on-select="turnToPage"
                     :menu-list="menuList"
                      :enable-flag="!dragging">
          </side-menu>
        </div>
      </Sider>
      <Layout>
        <Header class="header">
          <div style="display: flex;height: 64px;">
            <!--打开的菜单-->
            <tags-nav :value="$route" @input="handleClick" :list="tagNavList" @on-close="handleCloseTag"
                      @nextTag="handleNextTag" @previousTag="handlePreviousTag" ref="tags"/>
            <!--右侧的我的-->
            <header-bar :collapsed="collapsed" @on-coll-change="handleCollapsedChange"
                        style="width: 20%;min-width: 452px ;background: rgba(23, 80, 189, 1);display: flex;align-items: center;color: #ffffff; ">
              <user :user-avator="userAvator"/>
              <!--        <language v-if="$config.useI18n" @on-lang-change="setLocal" style="margin-right: 10px;" :lang="local"/>-->
              <!--        <error-store v-if="$config.plugin['error-store'] && $config.plugin['error-store'].showInHeader"-->
              <!--                     :has-read="hasReadErrorPage" :count="errorCount"></error-store>-->
              <!--        <fullscreen v-model="isFullscreen" style="margin-right: 10px;"/>-->
              <p style="font-size: 14px;margin:0 10px;width: 135px;overflow: hidden;height: 40px;text-align: left;">
                {{ this.time }}，{{ this.$store.state.user.userName }}
                <!--审批提示-->
<!--                <Badge :count="approvalCount" class-name="badge-class">-->
<!--                  <Icon type="ios-notifications" class="audit-class" @click="handleClickAudit"/>-->
<!--                </Badge>-->

                <Tooltip v-if="!maxFlag" :content="$t('max')">
                  <icon style="padding-left: 5px;cursor: pointer;font-size: 18px"
                        type="iconfont iconfont icon-max1"
                        @click="enterFullScreen"></icon>
                </Tooltip>
                <Tooltip v-else :content="$t('min')">
                  <icon style="padding-left: 5px;cursor: pointer;font-size: 18px" type="iconfont iconfont icon-min"
                        @click="exitFullscreen"></icon>
                </Tooltip>
              </p>
              <Select v-model="cpId" style="width:200px;margin-right: 10px" ref="selCp" default-label="东科" @on-change="cpChange" >
                <Option v-for="item in joinedCpList" :value="item.cpId" :key="item.cpId">{{ item.cpName }}</Option>
              </Select>
            </header-bar>
          </div>

        </Header>
        <Content class="main-content-con" style="height: calc(100% - 5px);overflow-x: auto">
          <Layout class="main-layout-con">
            <!--            <div style="height: 3px;width: 100%"/>-->
            <Content class="content-wrapper">
              <keep-alive :include="cacheList">
                <router-view></router-view>
              </keep-alive>
              <ABackTop :height="100" :bottom="80" :right="50" container=".content-wrapper"></ABackTop>
            </Content>
          </Layout>
        </Content>
      </Layout>
    </Layout>

    <keep-alive v-else :include="cacheList">
      <router-view></router-view>
    </keep-alive>
  </div>
</template>
<script>
import SideMenu from './components/side-menu'
import HeaderBar from './components/header-bar'
import TagsNav from './components/tags-nav'
import User from './components/user'
import ABackTop from './components/a-back-top'
import Fullscreen from './components/fullscreen'
import Language from './components/language'
import ErrorStore from './components/error-store'
import {mapMutations, mapActions, mapGetters} from 'vuex'
import {
  getNewTagList,
  getNextRoute,
  getPreviousRoute,
  localRead,
  localRemove,
  localSave,
  routeEqual
} from '@/libs/base/util'
import minLogo from '@/assets/images/logo-min.jpg'
import maxLogo from '@/assets/images/dongke_logo.png'
import logo from '@/assets/images/dklogo.png'
import dk_logo from '@/assets/images/dongke_logo.png'

import mainService from '@/api/main'
import './main.less'

export default {
  name: 'Main',
  components: {
    SideMenu,
    HeaderBar,
    Language,
    TagsNav,
    Fullscreen,
    ErrorStore,
    User,
    ABackTop,
  },
  provide() {
    return {
      dkMain: this,
    }
  },
  data() {
    let self = this
    return {
      cpId:null,
      logo,
      dk_logo,
      time: '',
      collapsed: false,
      minLogo,
      maxLogo,
      maxFlag: false,// 最大化标识
      isFullscreen: false,
      hideHeadAndLeft: 0,
      quickNavList: [],
      mousePosition: null,
      drawerShow: false,
      approvalCount: 0,
      startX: 0,
      dragging: false,
      siderWidth: 200,
      minSiderWidth:200,
      maxSiderWidth:300,
      joinedCpList:self.$store.state.user.joinedCpList,
    }
  },
  computed: {
    ...mapGetters([
      'errorCount'
    ]),
    tagNavList() {
      return this.$store.state.app.tagNavList
    },
    tagRouter() {
      return this.$store.state.app.tagRouter
    },
    userAvator() {
      return this.$store.state.user.imagePath ? this.$store.state.user.imagePath : this.$store.state.user.avatorImgPath
    },
    cacheList() {
      // 分开 是因为关闭最后一个页面会把缓存存到ParentView
      if (this.tagNavList.length) {
        const list = ['ParentView', ...this.tagNavList.length ? this.tagNavList.filter(item => !(item.meta && item.meta.notCache)).map(item => item.name) : []]
        return list;
      } else {
        const list = [...this.tagNavList.length ? this.tagNavList.filter(item => !(item.meta && item.meta.notCache)).map(item => item.name) : []]
        return list;
      }
    },
    menuList() {
      return this.$store.getters.menuList
    },
    local() {
      return this.$store.state.app.local
    },
    hasReadErrorPage() {
      return this.$store.state.app.hasReadErrorPage
    },
    unreadCount() {
      return this.$store.state.user.unreadCount
    },
    //菜单类型
    menuType() {
      let sideMenuType = localRead('sideMenuType');
      if(sideMenuType){
        return sideMenuType
      }else{
        return this.$store.state.app.menuType
      }
    }
  },
  activated() {
  },
  created() { // 页面创建生命周期函数
    this.getTimeInfo();  // 显示时间提示语
    // 读取缓存中的左侧宽度
    // let siderWidth = localRead('siderWidth');
    // if(siderWidth){
    //   this.siderWidth = siderWidth;
    // }
    // localRemove('siderWidth')

  },
  destroyed: function () { // 离开页面生命周期函数
    mainService.websocketclose();
  },
  methods: {
    ...mapMutations([
      'setBreadCrumb',
      'setTagNavList',
      'addTag',
      'setLocal',
      'setHomeRoute',
      'closeTag'
    ]),
    ...mapActions([
      'handleLogin',
      'updateCompany',
      'updateToken',
      'changeCp',
      'getInfoAfterLogin',
      'handleAfterLoginInfo'
    ]),
    /**
     * @desc   : 开始拖动
     * @author : 周兴
     * @date   : 2024/1/17 14:51
     */
    startDrag(event) {
      // 先注释掉
      // this.startX = event.clientX; // 记录初始点击位置
      // this.dragging = true;
    },
    /**
     * @desc   : 拖动
     * @author : 周兴
     * @date   : 2024/1/17 14:52
     */
    drag(event) {
      // 如果没有在拖动，就直接返回
      if (!this.dragging) return;
      // 计算移动距离，更新宽度
      const dx = event.clientX - this.startX;
      this.siderWidth += dx;
      // 把边框宽度缓存记录到缓存
      localSave('siderWidth',this.siderWidth);
      if(this.siderWidth < this.minSiderWidth || this.siderWidth > this.maxSiderWidth){
        this.dragging = false;
        return;
      }
      // 更新初始位置
      this.startX = event.clientX;
    },
    /**
     * @desc   : 停止拖动
     * @author : 周兴
     * @date   : 2024/1/17 14:52
     */
    stopDrag() {
      this.dragging = false; // 结束拖动
    },
    /**
     * @desc   : 打开审批
     * @author : 周兴
     * @date   : 2023/9/15 10:53
     */
    handleClickAudit() {
      this.drawerShow = true;
    },
    /**
     * @desc   : 获取时间
     * @author : 周兴
     * @date   : 2022/12/21 14:58
     */
    getTimeInfo() {
      let myDate = new Date()
      let hour = myDate.getHours()
      if ((0 <= hour && 4 >= hour) || hour >= 22) {
        this.time = this.$t('evening')
      }
      if (5 <= hour && hour <= 10) {
        this.time = this.$t('morning')
      }
      if (11 <= hour && hour <= 13) {
        this.time = this.$t('noon')
      }
      if (12 <= hour && hour <= 18) {
        this.time = this.$t('afternoon')
      }
      if (19 <= hour && hour <= 21) {
        this.time = this.$t('night')
      }
    },
    collapseChange(flag) {
      this.collapsed = flag
    },
    leaveDrawer() {
      // console.log('leaveDrawer')
      this.$refs.sideMenu.showCard = false
    },
    toDongkeIndex() {
      window.open('http://www.dongkesoft.com/public/')
    },
    /**
     * @desc   : 跳转到某个页面
     * @author : 周兴
     * @date   : 2022/5/20 8:36
     */
    turnToPage(route) {
      let {name, params, query} = {}
      if (typeof route === 'string') name = route
      else {
        name = route.name
        params = route.params
        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
    },
    /**
     * @desc   : 跳转到前一个tab(都不要了，向前向后都不需要打开页签)
     * @author : 周兴
     * @date   : 2022/5/23 9:28
     */
    handlePreviousTag(tagIndex, currentRoute) {
      // if (tagIndex >= 0) {
      //   const previousRoute = getPreviousRoute(this.tagNavList, currentRoute)
      //   this.turnToPage(previousRoute)
      // } else {
      //   //跳转到首页
      //   let homePage = {}
      //   homePage.name = vm.$config.homeName
      //   this.turnToPage(homePage)
      // }
    },
    /**
     * @desc   : 跳到下一个Tag(都不要了，向前向后都不需要打开页签)
     * @author : 周兴
     * @date   : 2022/5/23 8:59
     */
    handleNextTag(tagIndex, currentRoute) {
      // if (tagIndex <= this.tagNavList.length - 1) {
      //   const nextRoute = getNextRoute(this.tagNavList, currentRoute)
      //   this.turnToPage(nextRoute)
      // }
    },
    /**
     * @desc   : 关闭Tag
     * @author : 周兴
     * @date   : 2022/4/2 21:02
     */
    handleCloseTag(res, type, route) {
      // 如果当前页面需要是关闭提示，需要给出question询问
      if (type === undefined && this.$route.meta && this.$route.meta.closeQuestion) {
        this.$IBMessage({
            content: this.$t('Q_002', {'param': this.$t('close')}),
            title: this.$t('systemQuestion')
          },
          {
            ok: () => {
              // 执行关闭，页面跳转操作
              this._turnToPage(res, type, route);
            },
            cancel: () => {
            }
          })
      } else {
        // 执行关闭，页面跳转操作
        this._turnToPage(res, type, route);
      }
    },
    /**
     * @desc   : 执行跳转页面
     * @author : 周兴
     * @date   : 2023/7/14 17:09
     */
    _turnToPage(res, type, route) {
      //关闭当前
      if (type === undefined) {
        if (routeEqual(this.$route, route)) {
          this.closeTag(route)
        }
        // 如果全部都关闭就跳转到主页
        if (!res || res.length === 0) {
          this.turnToPage({name: this.$config.homeName})
        }
      }
      //关闭所有
      else if (type === 'all') {
        // 打开首页
        this.turnToPage(this.$config.homeName)
      }
      // 关闭其他和关闭右侧，关闭左侧，都要重新定位当前页面，因为有可能不是在当前页面上操作的
      else {
        this.turnToPage(route.name)
      }
      this.setTagNavList(res)
    },
    /**
     * @desc   : 关闭所有窗体
     * @author : 周兴
     * @date   : 2022/12/21 15:05
     */
    handleAllClose() {
      // 打开首页
      this.turnToPage(this.$config.homeName)
      this.setTagNavList([])   // 关闭所有页签
      this.getTimeInfo();  // 重新显示时间提示语
    },
    /**
     * @desc   : 点击菜单
     * @author : 周兴
     * @date   : 2022/4/3 14:09
     */
    handleClick(item) {
      this.turnToPage(item)
    },
    /**
     * @desc   : 退出全屏
     * @author : 周兴
     * @date   : 2023/4/19 11:15
     */
    handleExitMax(e) {
      let flag = this.checkFull();
      // 退出全屏
      if (!flag) {
        this.maxFlag = false;
      }
    },
    /**
     * @desc   : 进入全屏模式
     * @author : 周兴
     * @date   : 2023/4/19 13:08
     */
    enterFullScreen() {
      this.maxFlag = true;
      document.documentElement.webkitRequestFullScreen();
    },
    /**
     * @desc   : 退出全屏模式
     * @author : 周兴
     * @date   : 2023/4/19 13:08
     */
    exitFullscreen() {
      this.maxFlag = false;
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      }
    },
    /**
     * @desc   : 监听解决F11打开后无法esc退出同时退出全屏的按钮也失效问题
     * @author : 周兴
     * @date   : 2023/4/19 13:07
     */
    handleKeyDown(event) {
      // console.log('333',event)
      if (event.keyCode === 122) {
        event.returnValue = false;
        this.enterFullScreen(); //这里方的是触发全屏的方法
      } else if (event.keyCode === 13) {
        // 如果是多行文本不用拦截
        if (event.target.type != 'textarea') {
          event.returnValue = false;
        }
      }
    },
    /**
     * @desc   : 判断是不是全屏
     * @author : 周兴
     * @date   : 2023/4/19 11:31
     */
    checkFull() {
      //判断浏览器是否处于全屏状态 （需要考虑兼容问题）
      //火狐浏览器
      let isFull =
        document.mozFullScreen ||
        document.fullScreen ||
        //谷歌浏览器及Webkit内核浏览器
        document.webkitIsFullScreen ||
        document.webkitRequestFullScreen ||
        document.mozRequestFullScreen ||
        document.msFullscreenEnabled;
      if (isFull === undefined) {
        isFull = false;
      }
      return isFull;
    },
    changeFullscreenVar() {
      // console.log('t')
    },
    /**
     * @desc   : 鼠标移动
     * @author : 周兴
     * @date   : 2023/4/19 11:15
     */
    mousemove(e) {
      this.mousePosition = e.path
    },
    /**
     * @desc   : 打开审批一览页面
     * @author : 洪旭东
     * @date   : 2023-09-20 13:39
     */
    openApprovalIndex() {
      this.drawerShow = false
      this.$router.push('/bpm/waiting-for-approval/index');
    },
    /**
     * @desc   : 获取待审中心条数
     * @author : 洪旭东
     * @date   : 2023-09-20 14:49
     */
    getApprovalCount() {
      // 参数设置
      let params = {
        ftyId: this.$store.state.user.ftyId,
        userId: this.$store.state.user.id,
        querys: Object.assign({treeFlag: true}, this.searchList)
      }
      this.excute(this.$service.waitingForApprovalService, this.$service.waitingForApprovalService.listCount, params, false).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.approvalCount = res.data
        } else {
          this.$Message.error(res.message)
        }
      })
    },
    /**
     * @desc   : 公司改变
     * @author : 付斌
     * @date   : 2024-06-13 17:14
     */
    async cpChange(cpId){
      if (cpId) {
        let item = this.joinedCpList.filter(it=>it.cpId == cpId);
        if(!item || item.length == 0){
          return;
        }

        await this.updateCompany(item[0]);
        // 点击切换公司
        this.changeCp(this.joinedCps).then(res => {
          // 更新token
          this.updateToken(res.data);
          setTimeout(() => {
            // 登录后获取信息
            this.getInfoAfterLogin().then(r => {
              if (r.code == this.$config.SUCCESS_CODE) {
                this.handleAfterLoginInfo(r.data);
                // 关闭所有的窗体
                if (this.dkMain) {
                  this.dkMain.handleAllClose();
                }
                // 刷新页面
                location.reload();
              }
            });
          }, 50)
        })
      }
    }
  },
  watch: {
    '$route'(newRoute, oldRoute) {
      const {name, query, params, meta} = newRoute
      //如果是首页不加入，因为已经在最前方单独
      if (name === 'home') {
        return;
      }
      this.addTag({
        route: {name, query, params, meta},
        type: 'push',
        lastName: oldRoute.name
      })
      this.setBreadCrumb(newRoute)
      this.setTagNavList(getNewTagList(this.tagNavList, newRoute))
    },
    maxFlag(n, o) {
      // 如果最小化时记录
      if (!n) {
        localSave('restore', 'restore')
      }
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleExitMax);
    window.removeEventListener('keydown', this.handleExitMax);
    // 移除监听事件
    window.removeEventListener('mousemove', this.drag);
    window.removeEventListener('mouseup', this.stopDrag);
  },
  mounted() {
    /**
     * @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
      })
    }
    //这里是监听F11案件的
    window.addEventListener("keydown", this.handleKeyDown, true); // 监听按键事件
    window.addEventListener('resize', this.handleExitMax);
    /* 是否展示头部和左侧 */
    this.hideHeadAndLeft = (this.$route.query.hideHeadAndLeft && this.$route.query.hideHeadAndLeft.toString() === '1') ? 1 : 0;
    // 监听 mousemove 和 mouseup 事件
    window.addEventListener('mousemove', this.drag);
    window.addEventListener('mouseup', this.stopDrag);
    this.cpId = this.$store.state.user.cpId
    console.log('fff',this.$refs.selCp,this.$store.state.user.cpId)
  },
}
</script>

<style lang="less">
.ivu-layout-header{
  padding: 0 !important;
  //margin: 0 24px;
  background: rgba(23, 80, 189, 1)!important;
  height: 64px!important;
}
.fade-enter {
  opacity: 0;
}

.fade-leave {
  opacity: 1;
}

.fade-enter-active {
  transition: opacity 1s;
}

.fade-leave-active {
  opacity: 0;
  transition: opacity 1s;
}


.header-item > div {
  cursor: pointer;
}

.header-item > div:nth-child(n+2) {
  margin-left: 20px;
}


//hxd:修复页面滚动条异常
.ivu-layout-has-sider {
  height: 100%;
}

.audit-class {
  font-size: 18px !important;
  margin: 5px;
  cursor: pointer;
}

.badge-class {
  transform: scale(0.6) !important;
  top: 2px !important;
  right: -8px !important;
}

//drawer在本页实际渲染时，.ivu-drawer-bottom属性被覆盖，所以重新附加bottom属性
.wait-approval .ivu-drawer {
  bottom: 0;
  width: 100%;
  top: unset;
}




</style>
