<!-- 农林植保 -->
<template>
  <el-container style="height: 100%">
    <el-header height="80px">
      <div class="headMenu">
        <!-- {{currTopMenuId}} -->
        <!-- logo -->
        <div class="logoinfo">
          <div>
            <img :src="$imghost + logoIcon" width="40" alt v-if="!loginInfo.role_logo" />
            <img :src="loginInfo.role_logo" v-else width="40px" />
            <span>{{ loginInfo.role_header || "河南省高标准农田管理系统" }}</span>
          </div>
          <!-- {{menuTabs}} -->
        </div>
        <!-- 菜单 -->
        <ul class="topMenu">
          <li
            v-for="(item,index) in menuList"
            :key="item.index"
            :class="{'active':item.name==currTopMenuId}"
            :id="'nav' + index"
            v-trigger="(that)"
            @click="topMenuClick(item,index)"
          >
            <div class="navContent">
              <div class="a1">
                <div class="blueMenu">
                  <img src="../../static/images/indexTab.png" alt="" >
                </div>
              </div>
              <div class="a2">
                <div class="blueMenu indexTabActive">
                  <img src="../../static/images/indexTabActive.png" alt="" >
                </div>
              </div>
              
              <div class="navTxt">{{item.name}}</div>
            </div>
          </li>
          <!-- <li
            v-for="(item,index) in menuList"
            :key="item.index"
            :class="{'active':item.name==currTopMenuId}"
            :id="'nav' + index"
            v-trigger
            @click="topMenuClick(item,index)"
          >
            <img v-if="item.id" :src="iconimgs[item.id]" alt />
            <div>{{item.name}}</div>
          </li> -->
        </ul>
        <div class="userInfo">
          欢迎您！
          <el-dropdown  @command="dropdownHandle" >
            <span class="el-dropdown-link">
              {{username}}
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="personMsg">个人中心</el-dropdown-item>
                <el-dropdown-item command="editPwd">修改密码</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="exit" @click="outSys()">
            <i class="iconfont icon-exit"></i>
          </div>
          <!-- <div> -->
          <!-- <button></button> -->
          <!-- <el-button type="primary" icon="el-icon-search">搜索</el-button> -->
          <!-- </div> -->
        </div>
      </div>
    </el-header>
    <!-- 修改密码对话框 -->
    <el-dialog
      title="修改密码"
      :visible.sync="resetPassDialogVisible"
      width="500px"
      top="180px"
      @close="resetPassDialogClosed"
    >
      <el-form
        ref="resetPassFormRef"
        :model="resetPassForm"
        label-width="104px"
        :rules="resetPassFormRules"
      >
        <el-form-item label="原始密码 : " prop="oldPass">
          <el-input type="password" v-model="resetPassForm.oldPass"></el-input>
        </el-form-item>
        <el-form-item label="新密码 : " prop="newPass">
          <el-input type="password" v-model="resetPassForm.newPass"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码 : " prop="checkNewPass">
          <el-input
            type="password"
            v-model="resetPassForm.checkNewPass"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetPassDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="resetPassSubm">确认</el-button>
      </span>
    </el-dialog>
    <el-container style="overflow: auto">
      <el-aside width="85px">
        <ul class="leftMenu">
          <li
            v-for="(item, index) in leftMenuList"
            :key="item.path"
            :class="{'active':item.name==currLeftMenuId}"
            @click="leftMenuClick(item,index)"
          >
            <i :class="['iconfont', iconimgs[item.pur_id]]"></i>
            <div>{{item.name}}</div>
          </li>
        </ul>
      </el-aside>
      <el-main>
        <div class="tabsNav">
          <el-tabs v-model="menuTabsValue" type="card" closable @tab-click="clickTab" @tab-remove="removeTab">
            <el-tab-pane
              v-for="(item, index) in menuTabs"
              :key="item.path"
              :label="item.name"
              :name="item.name"
            ></el-tab-pane>
          </el-tabs>
        </div>
        <div class="content">
            <!-- <div>{{menuTabsValue}}</div> -->
            <!-- <keep-alive> -->
              <router-view></router-view>
            <!-- </keep-alive> -->
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import '@/plugin/flexible.js'
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    var validateNewPass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else {
        if (this.resetPassForm.checkPass !== "") {
          this.$refs.resetPassFormRef.validateField("checkNewPass");
        }
        callback();
      }
    };
    var validateCheckPass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.resetPassForm.newPass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    //这里存放数据
    return {
      that: this,
      logoIcon: "/images/logo.png",
      menuList: [],
      leftMenuList: [],
      currTopMenuId: '农林植保',
      currLeftMenuId: '设备列表',
      iconimgs: {
        "1": 'icon-dingdianxuncha',
        "2": 'icon-dingdianxuncha',
        "100": 'icon-dingdianxuncha',
        "3": 'icon-shipinwulian',
        "4": 'icon-shipinwulian',
        "5": 'icon-yujing',
        "101": 'icon-yujing',
        "6": 'icon-yujing',
        "7": 'icon-shebeibaoyan',
        "8": 'icon-xingxiang',
        "9": 'icon-rizhi',
        "10": 'icon-shuizhi',
        "102": 'icon-shuizhi',
        "11": 'icon-shuizhi',
        "12": 'icon-rizhi',
        "13": 'icon-rizhi',
        "14": 'icon-1',
        "15": 'icon-1',
        "16": 'icon-yen-2',
        "17": 'icon-inbox-1',
        "18": 'icon-inbox-1',
        "19": 'icon-inbox-1',
        "20": 'icon-yonghu2',
        "21": 'icon-yonghu2',
        "22": 'icon-moxingguanli',
        "23": 'icon-shiming',
        "24": 'icon-BIM',
      },
      //动态标签
      // menuTabs:[{ "path": "/plantGuard/base", "name": "设备列表", "par": "农林植保", "order": 0 } ],
      menuTabs:[],
      menuTabsValue:'',
      username:"",
      // 用户信息
      loginInfo:{},
      resetPassDialogVisible:false,
      resetPassForm: {
        oldPass: "",
        newPass: "",
        checkNewPass: "",
      },
      resetPassFormRules: {
        oldPass: [
          { required: true, message: "请输入原始密码", trigger: "blur" },
        ],
        newPass: [
          { required: true, message: "请输入新密码" },
          { validator: validateNewPass, trigger: "blur" },
        ],
        checkNewPass: [
          { required: true, message: "请确认密码" },
          { validator: validateCheckPass, trigger: "blur" },
        ],
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    '$route' (to, from) {
      let flag = false
      for (let item of this.menuTabs) {
        if (item.name === to.meta.navname) {
          this.menuTabsValue = to.meta.navname
          flag = true
          break
        }
      }
      console.log(this.menuList);
      
      if (!flag) {  
        var breakFlag = false;
        for(var i = 0 ;i<this.menuList.length;i++){
          if(!this.menuList[i].children){
            continue;
          }
          for(var j = 0 ;j<this.menuList[i].children.length;j++){
            if(this.menuList[i].children[j].name == to.meta.navname){
              console.log(i);
              
              var order = i;
              breakFlag = true;
              break;
            }
          }
          if(breakFlag){
            break;
          }
        }

        
        this.add_tabs({path: to.path, name: to.meta.navname,par:to.meta.title,order:order})
        this.menuTabsValue = to.meta.navname
      }

      sessionStorage.setItem("menuTabs", JSON.stringify(this.menuTabs));
      sessionStorage.setItem("menuTabsValue", this.menuTabsValue);
    }
  },
  //vue自定义指令
  directives: {
    trigger: {
      inserted(el, binging) {
        var menuTabsValue = sessionStorage.getItem("menuTabsValue");
        var menuTabs = sessionStorage.getItem("menuTabs");
        if(menuTabs){
          binging.value.that.menuTabs = JSON.parse(menuTabs)
          binging.value.that.menuTabsValue = menuTabsValue
          binging.value.that.leftMenuList = JSON.parse(sessionStorage.getItem("leftMenuList"));
          binging.value.that.currLeftMenuId = sessionStorage.getItem("currLeftMenuId");
          
        }else{
          el.id == "nav0" ? el.click() : null; // 只点击第一个，id是在循环中手动添加的
          console.log(2);
        }
      },
    },
  },
  //方法集合
  methods: {
    topMenuClick(item, index) {
      console.log(item);
      
      if(item.children){
        this.currTopMenuId = item.name;
        this.leftMenuList = item.children;
        this.currLeftMenuId = item.children[0].name;
        sessionStorage.setItem("leftMenuList", JSON.stringify(item.children));
        sessionStorage.setItem("currLeftMenuId", item.children[0].name);
        this.$router.push({ path: '/plantGuard/'+item.children[0].path });
      }else if(item.name == '产品溯源'){
        var routeUrl = this.$router.resolve({
          path: '/index/farmBaseManger'
        })
        window.open(routeUrl.href, '_blank')
      }else{
        this.$message({
          message: '系统开发中',
          type: 'warning'
        });
      }
      
    },
    leftMenuClick(item, index) {
      this.currLeftMenuId = item.name;
      sessionStorage.setItem("currLeftMenuId", item.name);
      console.log(item)
      if(item.path=="/operatData"){
        this.$store.commit('setData',{
          name:'ele_operat_id',
          val:''
        })
      }
      this.$router.push({ path: '/plantGuard/'+item.path });
    },
    //添加tab标签
    add_tabs (data) {
      this.menuTabs.push(data)
      console.log(data);
    },
    //移除tab标签
    removeTab(targetName) {
        let tabs = this.menuTabs;
        let activeName = this.menuTabsValue;
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
                this.$router.push({ path: nextTab.path });
                this.menuList.forEach((item)=>{
                  if(item.name == nextTab.par){
                    this.leftMenuList = item.children;
                    sessionStorage.setItem("leftMenuList", JSON.stringify(item.children));
                  }
                })
                this.currTopMenuId=nextTab.par;
                this.currLeftMenuId=nextTab.name;
                sessionStorage.setItem("currLeftMenuId", nextTab.name);
              }
            }
          });
        }
        
        this.menuTabsValue = activeName;
        this.menuTabs = tabs.filter(tab => tab.name !== targetName);
    },
    //切换标签
    clickTab(tab) {
      console.log('tab')
      console.log(tab)
      this.$router.push({path: this.menuTabs[tab.index].path})
      this.menuList.forEach((item)=>{
        if(item.name == this.menuTabs[tab.index].par){
          this.leftMenuList = item.children;
          sessionStorage.setItem("leftMenuList", JSON.stringify(item.children));
        }
      })
      this.menuTabsValue = this.menuTabs[tab.index].name
      this.currTopMenuId=this.menuTabs[tab.index].par;
      this.currLeftMenuId=this.menuTabs[tab.index].name;
      sessionStorage.setItem("currLeftMenuId", this.menuTabs[tab.index].name);
    
    },
    // 获取用户主题
    getUserInfo() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=home.homes.user_theme",
      }).then((res) => {
        if (res.data.message == "") {
          this.loginInfo = res.data.data[0];
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 获取用户菜单列表
    getNavList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=user.login.user_login_info",
      }).then((res) => {
        if (res.data.message == "") {
          var menuLists=res.data.data.children;
          
          let userType = res.data.data.myuser_type; //用户类型 管理员1 普通用户4
          let userName = res.data.data.username; //用户名
          let myuid = res.data.data.myuid; //用户id
          
          this.$store.commit('setData',{
            name:'myuser_type',
            val:userType
          })
          this.$store.commit('setData',{
            name:'user_id',
            val:myuid
          })
          console.log(menuLists);
          if(userType == 4){
            menuLists.forEach((item,index)=>{
              console.log(item);
              console.log(index);
              if(item.name == '农林植保'){
                item.children = [{
                  "name": "植保示范点",
                  "path": "base",
                  "pur_id": "100"
                }]
              }
              if(item.name == '灾害预警'){
                item.children = [{
                  "name": "预警示范点",
                  "path": "disasterWarn",
                  "pur_id": "101"
                }]
              }

              if(item.name == '智能灌溉'){
                item.children = [{
                  "name": "灌溉示范点",
                  "path": "irrigate",
                  "pur_id": "102"
                }]
              }
              
            })
            console.log(menuLists);
            if(menuLists[0].children){
              var path = "/plantGuard/"+menuLists[0].children[0].path;
              var name = menuLists[0].children[0].name;
              var parName =  menuLists[0].name;
              this.menuTabs = [{ "path": path, "name": name, "par": parName, "order": 0}]
            }else{
              for(var i = 0;i<menuLists.length;i++){
                if(menuLists[i].children){
                  var path = "/plantGuard/"+menuLists[i].children[0].path;
                  var name = menuLists[i].children[0].name;
                  var parName =  menuLists[i].name;
                  this.menuTabs = [{ "path": path, "name": name, "par": parName, "order": i}];
                  break;
                }
              }
              
            }
            

          }else{
            var path = "/plantGuard/"+menuLists[0].children[0].path;
            var name = menuLists[0].children[0].name;
            var parName =  menuLists[0].name;
            this.menuTabs = [{ "path": path, "name": name, "par": parName, "order": 0}]
          }
          
          
          // if(menuLists[0].name=='农林植保'){
          //   if(userType == 4){
          //     menuLists[0].children= [
          //       {
          //         "name": "植保示范点",
          //         "path": "base",
          //         "id": "2"
          //       }
          //     ]
          //     this.menuTabs = [{ "path": "/plantGuard/base", "name": "植保示范点", "par": "农林植保", "order": 0 }]
          //   }else{
          //     menuLists[0].children= [
          //       {
          //         "name": "植保监测",
          //         "path": "baseAll",
          //         "id": "19"
          //       },
          //     ]
          //     this.menuTabs = [{ "path": "/plantGuard/baseAll", "name": "植保监测", "par": "农林植保", "order": 0 }]
          //   }
          // }
          this.menuList = menuLists;
          console.log(this.menuList);
          
        }
      });
    },
    dropdownHandle(command) {
      if (command == "editPwd") {
        this.changePass();
      } else if (command == "outSys") {
        this.outSys();
      } else {
        this.$router.push({ path: "/plantGuard/personMsg" });
      }
    },
    outSys() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=user.login.logout_user",
      }).then((res) => {
        if (res.data.message == "") {
          window.sessionStorage.clear()
          window.localStorage.clear()
          this.$router.push("/login");
        }
      });
    },
    changePass() {
      this.resetPassDialogVisible = true;
    },
    resetPassSubm() {
      this.$refs.resetPassFormRef.validate((valid) => {
        if (!valid) return;
        this.$axios({
          method: "POST",
          url: "/api/api_gateway?method=user.login.changepwd",
          data: this.qs.stringify({
            old_password: this.resetPassForm.oldPass,
            new_password: this.resetPassForm.newPass,
            confirm_password: this.resetPassForm.checkNewPass,
          }),
        }).then((res) => {
          if (res.data.message == "") {
            this.$message({
              message: "密码修改成功！",
              type: "success",
            });
            this.resetPassDialogVisible = false;
          }
        });
      });
    },
    resetPassDialogClosed() {},

  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getNavList();
    this.getUserInfo();
    this.username = localStorage.getItem("cUsername");
    // window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {
    // window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
  }, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped lang="less">
@keyframes step {
    0% {
        -webkit-transform: translateX(0);
        transform: translateX(0)
    }

    to {
        -webkit-transform: translate3d(-41.625rem, 0, 0);
        transform: translate3d(-41.625rem, 0, 0)
    }
}
.el-header {
  background-color: #182037;
  color: #eee;
  z-index: 3500;
  .headMenu {
    height: 80px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .logoinfo {
      >div{
        display: flex;
        align-items: center;
      }
      img {
        vertical-align: top;
      }
      span {
        font-size: .3rem;
        letter-spacing: .0375rem;
        margin-left: .125rem;
      }
    }
    .topMenu {
      height: 80px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      li {
        cursor: pointer;
        // padding: 10px 0;
        // width: 100px;
        width: 1.3875rem;
        // text-align: center;
        margin: 0 .125rem;
        // line-height: 20px;

        height: 100%;
        display: flex;
        align-items: center;
        .navContent{
          width: 100%;
          position: relative;
        }
        .blueMenu{
          position: absolute;
          width: 100%;
          height: .4875rem;
          overflow: hidden;
          // background: url(../../../static/images/indexTab.png);
          img{
            width: 41.625rem;
            animation: step 5s steps(30) infinite;
          }
        }
        // .indexTabActive{
        //   display: none;
        // }
        .a2{
          // display: none;
          visibility:hidden
        }
        .navTxt{
          line-height: .4875rem;
          padding-left: .375rem;
          font-size: .175rem;
        }
      }
      .active {
        // background: #0195ff;
        .a1{
          // display: none;
          visibility:hidden
        }
        .a2{
          // display: block;
          visibility:visible
        }
      }
      li:hover {
        .a1{
          // display: none;
          visibility:hidden
        }
        .a2{
          // display: block;
          visibility:visible
        }
        // background: #003e66;
      }
    }
    .userInfo {
      font-size: .175rem;
      .el-dropdown {
        color: #fff;
        cursor: pointer;
        margin-right: .125rem;
      }
      .exit {
        display: inline-block;
        font-size: .3rem;
        border-left: 1px solid #727272;
        padding-left: .1875rem;
        cursor: pointer;
        i{
          font-size: .25rem;
        }
        i:hover{
          color: #0195ff;
        }
      }
    }
  }
}

.el-aside {
  background-color: #182037;
  color: #eee;
  .leftMenu {
    text-align: center;
    li {
      padding: .125rem 0;
      cursor: pointer;
      line-height: .275rem;
      i{
        font-size: .325rem;
        line-height: 27px;
      }
    }
    li:hover {
      background: #000;
    }
    .active {
      background: #000;
    }
  }
}

.el-main {
  background-color: #fff;
  color: #333;
  padding: 0!important;
  .tabsNav{
    position: fixed;
    background: #fff;
    z-index: 3000;
    width: 100%;
  }
  .content{
    padding-top: 56px;
    height: calc(100vh - 136px);
    .innerMargin{
      padding: 0px 20px 20px;
    }
  }
}
/deep/.el-tabs__nav .el-tabs__item:nth-child(1) span{
      display: none;
  }




  /deep/.el-tabs__item.is-active,
  /deep/.el-tabs__item:hover{
    color: #0295ff;
  }
  /deep/.el-radio__input.is-checked .el-radio__inner{
    border-color: #0195ff;
    background: #0195ff;
  }
  /deep/.el-radio__input.is-checked + .el-radio__label {
    color: #0195ff;
  }
  .el-dropdown-menu{
    z-index:99999 !important
  }
.el-dropdown-menu__item:not(.is-disabled):hover, .el-dropdown-menu__item:focus {
    background-color: #dff1ff;
    color: #0295ff;
}
</style>