<template>
  <transition
    appear
    name="animate__animated animate__move"
    enter-active-class="animate__slideInDown"
    leave-active-class="animate__slideOutUp"
  >
    <div class="widget-bigScreenHeader">
      <div class="header">
        <div class="title">
          <div class="sysIcon"></div>
          <div class="titleInfo">
            <div class="maintitle">
              <div class="caption">{{ title }}</div>
              <div class="splitLine"></div>
              <el-select
                class="autoWidth-select"
                ref="select"
                v-model="treeSelectText"
                placeholder=""
                :popper-append-to-body="false"
              >
                <template slot="prefix">{{ treeSelectText }}</template>
                <el-option
                  :value="treeValue.value"
                  :label="treeValue.label"
                  style="max-width: 1.354167rem /* 260/192 */; height: auto; padding: 0"
                >
                  <!-- style="max-width: 1.354167rem /* 260/192 */; height: auto; padding: 0" -->
                  <el-tree
                    :data="treeDatas"
                    :props="defaultProps"
                    :expand-on-click-node="false"
                    default-expand-all
                    node-key="name"
                    highlight-current
                    @node-click="nodeClick"
                    ref="tree"
                  />
                </el-option>
              </el-select>
            </div>
            <!-- <div class="subtitle" :title="subtitle">{{ subtitle }}</div> -->
          </div>
        </div>
        <!-- <div class="menu" v-show="treeValue.pid === 2"> -->
        <div class="menu" v-show="menuList.length > 0">
          <ul class="main">
            <li v-for="item in menuList" :key="item.name">
              <a
                :name="item.name"
                :class="currentProjectActive === item.name ? 'pick-on' : ''"
                @click="currentProjectActive = item.name"
                >{{ item.label }}</a
              >
            </li>
          </ul>
        </div>
        <div class="otherItem">
          <div class="specificTime">{{ specificTime }}</div>
          <!-- <div class="entrySys" v-if="!isShowGroupPage && !isSearching" @click="enterSys()">{{ operationName }}</div> -->
        </div>
      </div>
      <div class="underline"></div>
    </div>
  </transition>
</template>

<script>
import Config from './config.json'
import { appconfig } from '@/config/bigScreenConfig'
import { getUserMenu } from '@/api/user'
import { setParams } from 'staticPub/config'
import { fetchProjects, setProjectKey } from '@/api/common'
import { findByCode } from '../apis'
import { setSessionStorage } from '@/utils/auth'
import { forEach } from 'lodash'
export default {
  name: 'bigScreenHeader', //大屏头部菜单栏
  data() {
    return {
      initRender:false,
      title: null, //标题
      subtitle: null, //副标题
      menuList: [], //菜单栏配置
      currentActive: '', //当前激活模块版块
      currentProjectActive: '', //当前项目级激活功能模块
      specificTime: null, //系统当前时间
      operationName: null,
      //
      treeSelectText: '',
      treeValue: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      isSearching: true
    }
  },
  computed: {
    routerData() {
      return this.$store.state.routeSetting.addRoutes
    },
    currentX() {
      return this.$store.state.bigScreen.currentActive
    },
    currentMenuItem() {
      return this.$store.state.bigScreen.currentMenuItem
    },
    treeDatas() {
      return this.$store.state.bigScreen.projectTreeData
    },
    currentProjectInfo() {
      return this.$store.state.bigScreen.currentProjectInfo
    },
    isShowGroupPage() {
      return this.$store.state.bigScreen.isShowGroupPage
    }
  },
  mounted() {
    document.getElementById("app").setAttribute('style','')
    this.title = Config.title
    this.subtitle = Config.subtitle
    this.showCurrentTime()
    this.getEnterText()
  },
  watch: {
    treeValue: {
      handler(val) {
        this.switchingItems(val)
      },
      deep: true
    },
    currentProjectActive: {
      handler(n, o) {
        this.activeModule(n)
        this.$store.state.bigScreen.currentActive = n
      }
    },
    currentX: {
      handler(n, o) {
        this.currentProjectActive = n
      }
    },
    currentMenuItem: {
      handler(val) {
        if (val) this.setTreeValue(val)
      },
      deep: true
    },
    treeDatas:{
      handler(val) {
        if(!this.initRender&&this.treeDatas){
          this.initRender=true;
          if(window.defaultSys&&window.defaultSys.sysCode){
            this.getProject(window.defaultSys.sysCode);
          }
        }
      },
    }
  },
  methods: {
    //项目切换
    async switchingItems(val) {
      console.log('项目切换', val)
      const { label, value, pid } = val
      this.treeSelectText = label
      if (pid == 2) {
        this.isSearching = true
        const currentPrj = await this.setCurrentPrj(value)
        if (!currentPrj) {
          this.$message.info('暂未查询到此项目信息')
          return
        } else {
          const { geo_info, id } = currentPrj
          if (!geo_info) {
            this.$message.info('暂无此项目GIS信息')
            return
          }
          this.getUserActiveModule()
          appconfig.bigScreenMapSettings.initPosition = geo_info && JSON.parse(geo_info)
          this.$store.state.bigScreen.currentProjectInfo = currentPrj //设置当前项目信息
          this.$store.state.bigScreen.currentPrjId = id //设置项目id
          this.$store.state.bigScreen.isShowGroupPage = false //切换显示为项目级大屏
          this.$store.state.bigScreen.currentProjectCode = value //设置指标代码
          this.isSearching = false
        }
      } else {
        this.menuList = []
        this.$store.state.bigScreen.groupName = label
        this.$store.state.bigScreen.groupCodeValue = pid == 0 ? value : label //设置指标代码，总公司为null，分公司为指标名称
        this.$store.state.bigScreen.isShowGroupPage = true //切换显示为公司级大屏
      }
    },
    // 点击tree节点
    nodeClick(item) {
      if(this.$store.state.bigScreen.currentActive==""||this.$store.state.bigScreen.currentActive==null){
        this.$store.state.bigScreen.currentActive = 'ProjectPanoramic'
      }
      this.setTreeValue(item)
      this.$refs.select.blur()
    },
    flatten(data) {
      return [].concat(...data.map((item) => [].concat(item, ...this.flatten(item.children))))
    },



    /**
     * 根据项目获取项目数据并跳转至项目，例如宜昌编码HB06
    */
    getProject(value){
      const getValue=(e)=>{
        if(e.value&&e.value==value){
          return e
        }else if(e.children||e.length>0){
          let tempValue=null;
          let tempArr=e.children||e;
          for(let i=0;i<tempArr.length;i++){
            if(!tempValue){
              tempValue=getValue(tempArr[i]);
            }
            if(tempValue){
              break;
            }
          }
          return tempValue
        }else{
          return null
        }
      }
      let currentItem=getValue(this.treeDatas);
      if(currentItem){
        this.setTreeValue(currentItem);
      }
    },
    setTreeValue(item) {
      const { name, value, pid, id } = item
      if (!this.flatten(this.treeDatas).find((e) => e.name == name)) {
        this.$message.info('暂无此项目信息')
        return
      }
      // this.$set(this.treeValue, 'value', value)
      // this.$set(this.treeValue, 'label', name)
      // this.$set(this.treeValue, 'pid', pid)
      this.treeValue = { value, label: name, pid, id, data: item }
      this.treeSelectText = name
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(name)
      })
    },
    //获取用户激活模块
    getUserActiveModule() {
      const userId = sessionStorage.getItem('userId') || this.$store.state.user.userId
      this.menuList = []
      getUserMenu(userId)
        .then((res) => {
          this.menuList=[];
          let arr = res.result.filter((item) => item.type === 'groupPage')
          let sort = 0
          arr[0].childrens.forEach((item) => {
            if (item.statusFlag === '1') {
              if (item.sort > sort) {
                this.menuList.push({
                  name: item.name,
                  label: item.label
                })
              } else {
                this.menuList.unshift({
                  name: item.name,
                  label: item.label
                })
              }
              sort = item.sort
            }
          })
          let tempIndex=0;
          if(window.defaultSys && window.defaultSys.currentActive){
            if(["ProjectPanoramic","StatisticalAnalysis","WisdomWarning","DecisionSupport"].includes(window.defaultSys.currentActive)){
              if(window.defaultSys.currentActive){
                tempIndex=this.menuList.findIndex(e=>{return e.name==window.defaultSys.currentActive});
              }
              this.currentProjectActive = this.menuList[tempIndex].name;
              document.getElementById("app").setAttribute('style','');
            }else{
              // this.$router.push('/map')
              this.$router.push({name:window.defaultSys.currentActive})
              // this.$router.push({name:"engineer"})
              // const temp=this.$store.state.routeSetting.routes.filter(e=>{
              //   return e.type!="rightTopTool"&&e.type!="rightBottomTool"&&e.type!="leftTopTool"&&e.type!="leftBottomTool"
              // })
              // this.$store.state.routeSetting.routes
            }
          }else{
            this.currentProjectActive = this.menuList[tempIndex].name;
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    //进入系统
    enterSys() {
      if (
        !this.routerData.some((item) => item.label === '首页') &&
        !this.routerData.some((item) => item.label === '地图')
      ) {
        this.logout()
      } else {
        // this.$router.push({ path: '/' })
        this.onProjectSelect()
      }
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push('/login')
    },
    getEnterText() {
      if (
        !this.routerData.some((item) => item.label === '首页') &&
        !this.routerData.some((item) => item.label === '地图')
      ) {
        this.operationName = '退出系统'
      } else {
        this.operationName = '进入系统'
      }
    },
    //当前项目级页面激活模块
    activeModule(module) {},
    //系统时间显示
    showCurrentTime() {
      this.specificTime = getnow()
      //时间显示
      function getnow() {
        let mynow = new Date() //默认的获取的是当前时间
        //通过调用日期对象的方法来重新获取当前的日期时间
        //mynow.setFullYear(2016);
        let year = mynow.getFullYear() //获取年
        let month = mynow.getMonth() + 1 //获取月
        let day = mynow.getDate() //获取日
        let hour = mynow.getHours() //获取小时
        let minute = mynow.getMinutes() //获取分钟
        let second = mynow.getSeconds() //获取秒
        let strdate =
          year +
          '年' +
          (month < 0 ? '00' : ('0' + month).slice(-2)) +
          '月' +
          (day < 0 ? '00' : ('0' + day).slice(-2)) +
          '日 ' +
          (hour < 0 ? '00' : ('0' + hour).slice(-2)) +
          ':' +
          (minute < 0 ? '00' : ('0' + minute).slice(-2)) +
          ':' +
          (second < 0 ? '00' : ('0' + second).slice(-2)) +
          ''
        return strdate
      }
      //动态显示时间
      setInterval(() => {
        this.specificTime = getnow()
      }, 100)
    },
    async setCurrentPrj(code) {
      const res = await findByCode({ prjCode: code })
      const { result } = res || {}
      if (res.code != 1 || result.length == 0) return false
      else {
        const { id } = result[0]
        const isSetting = await setProjectKey(id)
        if (isSetting.result) {
          return result[0]
        } else return false
      }
    },
    async onProjectSelect() {
      const row = this.currentProjectInfo
      const { id, geo_info, gcfw, wkid } = row || {}
      if (!geo_info || !wkid) {
        this.$message.info('此项目暂未设置GIS信息(geo_info,wkid)')
        return
      }
      // 这里设置当前项目信息
      setParams(row)
      this.$store.commit('project/UPDATE', row)
      setSessionStorage('initPosition', geo_info) //项目初始位置
      setSessionStorage('currentPrj', id) //项目ID
      if (id) {
        const { result } = await setProjectKey(id)
        if (result) {
          this.$router.push('/dashboard')
        }
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.animate__slideInDown,
.animate__slideOutUp {
  animation-duration: 3s; //动画持续时间
  animation-delay: 0s; //动画延迟时间
}
.widget-bigScreenHeader {
  width: 100%;
  position: absolute;
  z-index: 3;
  background: linear-gradient(#021a2a, rgba(2, 26, 42, 0.3));
  font-family: Source Han Sans CN;
  //public size
  $size20: 0.104167rem /* 20/192 */;
  $size16: 0.083333rem /* 16/192 */;
  $size14: 0.072917rem /* 14/192 */;
  $size10: 0.052083rem /* 10/192 */;
  $size8: 0.041667rem /* 8/192 */;
  user-select: none;
  .header {
    width: 100%;
    height: 0.375rem /* 72/192 */;
    display: flex;
    flex-flow: row nowrap;
    .title {
      width: 3.385417rem /* 650/192 */;
      padding: 0 $size20;
      display: flex;
      justify-content: center;
      align-items: center;
      filter: hue-rotate(0deg);
      transition: all 1s linear;
      .sysIcon {
        background: url('~@/views/groupPage/images/标题/sysIcon.png') no-repeat;
        background-size: 100% 100%;
        width: 0.239583rem /* 46/192 */;
        height: 0.239583rem /* 46/192 */;
        margin-right: 0.052083rem /* 10/192 */;
      }
      .titleInfo {
        display: flex;
        flex-flow: column;
        justify-content: center;
        align-items: center;
        height: 100%;
        width: calc(100% - 0.291667rem /* 56/192 */);
        overflow: hidden;
        .maintitle {
          height: calc(100% - 0.208333rem /* 40/192 */);
          width: 100%;
          display: flex;
          align-items: center;
          overflow: hidden;
          .caption {
            white-space: nowrap;
            font-size: $size20;
            font-weight: bold;
            color: #ffffff;
            text-shadow: 0 0 10px rgba(65, 105, 225, 0.3), 0 0 20px rgba(65, 105, 225, 0.3),
              0 0 30px rgba(65, 105, 225, 0.3), 0 0 40px rgba(65, 105, 225, 0.3);
          }
          .splitLine {
            width: 0.005208rem /* 1/192 */;
            height: 60%;
            background: #ffffff;
            opacity: 0.6;
            margin: 0 0.0625rem /* 12/192 */;
          }
          /deep/ .el-select {
            // display: block;
            min-width: 0.479167rem /* 92/192 */;
            // width: 0.78125rem /* 150/192 */;
            // width: 1.09375rem /* 210/192 */;
            font-size: 0.104167rem /* 20/192 */;
            font-weight: 500;
            font-family: Source Han Sans CN-MEDIUM;
            .el-input__inner {
              font-family: Source Han Sans CN-MEDIUM;
              padding-left: 0;
              // padding-right: 0.260417rem /* 50/192 */;
              background: transparent;
              border: none;
              color: #2ba7ff;
            }
            .el-input {
              font-size: inherit;
            }
            // .el-input__suffix {
            //   display: none;
            //   right: 0.104167rem /* 20/192 */;
            // }
            .el-select__caret {
              display: flex;
              align-items: center;
              justify-content: center;
            }
            .el-icon-arrow-up:before {
              content: '';
              display: block;
              width: 0;
              height: 0;
              border-top: 0.052083rem /* 10/192 */ solid #2ba7ff;
              border-right: 0.036458rem /* 7/192 */ solid transparent;
              border-left: 0.036458rem /* 7/192 */ solid transparent;
              transform: rotate(180deg);
            }
            input {
              position: absolute;
            }
            .el-input__prefix {
              position: relative;
              left: 0;
              padding-right: 30px;
              line-height: 40px;
              visibility: hidden;
            }
          }

          /deep/ .el-tree {
            background: #023c5d;
            color: #f9fdff;
            .el-tree-node__content {
              background: transparent;
            }
            .el-tree-node__content:hover {
              background: transparent;
              color: #2ba7ff;
            }
          }
          /deep/ .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
            background: transparent;
            color: #2ba7ff;
          }
        }
        .subtitle {
          // height: 0.0625rem /* 12/192 */;
          display: inline-block;
          width: 100%;
          font-size: 0.057292rem /* 11/192 */;
          font-weight: 400;
          color: #feffff;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }
      }
    }
    .menu {
      // width: 60%;
      white-space: nowrap;
      ul {
        list-style: none;
        padding: $size10;
        margin: 0 0 0 $size10;
      }
      .main {
        width: 100%;
        display: flex;
      }
      .main > li {
        margin: $size8 $size20;
        float: left;
      }
      .main > li a {
        text-align: center;
      }
      a {
        text-decoration: none;
        color: #fefefe;
        text-transform: capitalize;
        display: block;
        padding: $size10 0;
        transition: background-color 0.5s ease-in-out;
        font-size: $size16;
        font-weight: 400;
      }
      a:hover,
      .pick-on {
        cursor: pointer;
        color: #0ea7ff;
        font-weight: bold;
        border-bottom: 2px solid;
      }
    }
    .otherItem {
      // width: 20%;
      height: 100%;
      font-size: $size16;
      font-weight: 400;
      display: flex;
      align-items: center;
      position: absolute;
      right: 0.104167rem /* 20/192 */;
      .specificTime {
        //   flex: 2;
        //   top: 25%;
        text-align: center;
        font-family: Source Han Sans CN;
        color: #a8d3f1;
      }
      .entrySys {
        // flex: 0.6;
        width: 0.46875rem /* 90/192 */;
        color: #a8d3f1;
        background: url('~@/views/groupPage/images/entrySys.png') no-repeat;
        background-size: 100% 100%;
        height: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        white-space: nowrap;
      }
      .entrySys:hover {
        cursor: pointer;
        color: #a8d3f1;
        background: url('~@/views/groupPage/images/entrySysHover.png') no-repeat;
        background-size: 100% 100%;
      }
    }
  }
  .underline {
    width: 9.796875rem /* 1881/192 */;
    height: 0.010417rem /* 2/192 */;
    background: url('~@/views/groupPage/images/标题/顶部线.png') no-repeat center center;
    background-size: 100% 100%;
    margin: 0 $size20;
  }
}
</style>