<!-- 农林植保 -->
<template>
  <el-container style="height: 100%">
    <el-header height="80px">
      <div class="headMenu">
        <!-- logo -->
        <div class="logoinfo">
          <div>
            <img :src="$imghost + logoIcon" width="40" alt v-if="loginInfo.role_logo" />
            <img :src="loginInfo.role_logo" v-else />
            <!-- <span>{{ loginInfo.role_header || "河南省高标准农田管理系统" }}</span> -->
            <span>河南省高标准农田管理系统</span>
          </div>
          
        </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.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": '',
        "2": 'icon-inbox-1',
        "3": 'icon-inbox-1',
        "4": 'icon-inbox-1',
        "5": 'icon-inbox-1',
        "6": 'icon-inbox-1',
        "7": 'icon-inbox-1',
        "8": 'icon-inbox-1',
        "9": 'icon-inbox-1',
        "10": 'icon-inbox-1',
        "11": 'icon-inbox-1',
        "12": 'icon-inbox-1',
        "13": 'icon-inbox-1',
        "14": 'icon-yonghu1',
        "15": 'icon-xitong',
        "16": 'icon-zhuti_tiaosepan_o',
        "17": 'icon-inbox-1',
        "18": 'icon-inbox-1',
        "19": 'icon-inbox-1',
        "20": 'icon-pin-2',
        "21": 'icon-1',
        "22": 'icon-chongzhi',
      },
      //动态标签
      // 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
        }
      }

      if (!flag) {
        console.log(to)
        this.add_tabs({path: to.path, name: to.meta.navname,par:to.meta.title,order:to.meta.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
        }else{
          el.id == "nav0" ? el.click() : null; // 只点击第一个，id是在循环中手动添加的
        }
      },
    },
  },
  //方法集合
  methods: {
    topMenuClick(item, index) {
      if(item.children.length){
        this.currTopMenuId = item.name;
        this.leftMenuList = item.children;
        this.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;
      console.log(item)
      if(item.path=="/operatData"){
        this.$store.commit('setOperatId','')
      }
      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.leftMenuList = this.menuList[nextTab.order].children;
                this.currTopMenuId=nextTab.par;
                this.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.leftMenuList = this.menuList[this.menuTabs[tab.index].order].children;
      this.menuTabsValue = this.menuTabs[tab.index].name
      this.currTopMenuId=this.menuTabs[tab.index].par;
      this.currLeftMenuId=this.menuTabs[tab.index].name;
      // sessionStorage.setItem("menuTabsValue", this.menuTabsValue);
    
    },
    // 获取用户主题
    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=[
            {
                  "name": "农林植保",
                  "id": "1",
                  "children": [
                     {
                     "name": "设备列表",
                     "path": "/base",
                     "id": "2"
                     },
                     {
                     "name": "项目基地",
                     "path": "/baseAll",
                     "id": "19"
                     },
                  ]
               },
               {
                  "name": "可视农业",
                  "id": "3",
                  "children": [
                     {
                     "name": "可视化系统",
                     "path": "/monitor",
                     "id": "4"
                     }
                  ]
               },
               {
                  "name": "智能灌溉",
                  "id": "5",
                  "children": [
                     {
                     "name": "灌溉展示",
                     "path": "/irrigate",
                     "id": "6"
                     },
                     {
                     "name": "操作记录",
                     "path": "/operatData",
                     "id": "6"
                     },
                     {
                     "name": "设备预警",
                     "path": "/wranData",
                     "id": "6"
                     },
                  ]
               },
               {
                  "name": "水价管理",
                  "id": "7",
                  "children": [
                     {
                     "name": "地图展示",
                     "path": "/page9",
                     "id": "20"
                    },
                    {
                     "name": "消费记录",
                     "path": "/page10",
                     "id": "21"
                    },
                    {
                     "name": "充值记录",
                     "path": "/page11",
                     "id": "22"
                    },
                  ]
               },
               {
                  "name": "地理信息",
                  "id": "9",
                  "children": [
                    //  {
                    //  "name": "设备列表",
                    //  "path": "/page1",
                    //  "id": "10"
                    // }
                  ]
               },
               {
                  "name": "产品溯源",
                  "id": "11",
                  "children": [
                    // {
                    //  "name": "农场管理1",
                    //  "path": "/farmFieldsManger",
                    //  "id": "23"
                    // }
                  ]
               },
               {
                  "name": "系统管理",
                  "id": "13",
                  "children": [
                     {
                     "name": "用户管理",
                     "path": "/userManage",
                     "id": "14"
                     },
                     {
                     "name": "角色管理",
                     "path": "/roleManage",
                     "id": "15"
                     },
                     {
                     "name": "主题定制",
                     "path": "/topicManage",
                     "id": "16"
                     },
                  ]
               },
               {
                  "name": "设备管理",
                  "id": "17",
                  "children": [
                     {
                     "name": "设备管理",
                     "path": "/equipManage",
                     "id": "18"
                     }
                  ]
               }
          ];
          
          let userType = res.data.data.myuser_type; //用户类型
          let userName = res.data.data.username; //用户名
          let myuid = res.data.data.myuid; //用户id
          
          sessionStorage.setItem("myuser_type", userType);
          sessionStorage.setItem("myuid", myuid);

          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;
        }
      });
    },
    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.localStorage.removeItem("isLogin");
          window.localStorage.removeItem("session");
          window.sessionStorage.removeItem("menuTabs");
          window.sessionStorage.removeItem("menuTabsValue");
          window.sessionStorage.removeItem("setHomepage");
          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;
      }
    }
    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>