<template>
  <el-container style="height: 100%">
    <el-header class="header" v-show="flag">
      <div v-if="userinfo.logo">
        <img
          :src="userinfo.logo"
          alt="jktype"
          style="position: absolute; left: 20px; top: 20px; max-width: 250px"
        />
      </div>
      <!-- 用户 -->
      <div class="userinfo">欢迎您，{{ username }}</div>
      <!-- 标题 -->
      <div class="sysName">
        <h2 v-if="userinfo.user_header">{{ userinfo.user_header }}</h2>
        <h2 v-else>可视农业应用系统</h2>
        <p>Agricultural Visualization Monitoring System</p>
      </div>
      <div class="site" v-if="userinfo.site && flag">
        <i class="iconfont icon-jidi"></i>
        <span>{{ userinfo.site }}</span>
      </div>
      <span class="header_btn" @click="hCheckFun">[隐藏]</span>
    </el-header>
    <el-header class="header2" v-show="!flag">
      <h3 v-if="userinfo.user_header">{{ userinfo.user_header }}</h3>
      <h3 v-else>可视农业应用系统</h3>

      <!-- <ul class="header_ul" style="margin: -55.5px 85px 0 0">
        <li
          style="padding: 15px 20px 15px 20px; color: #fff; cursor: pointer"
          @click="headerTitle(index)"
          :class="{ indexActive: tltIndex == index }"
          v-for="(item, index) in menuList1"
          :key="index"
        >
          {{ item.purview_name }}
        </li>
      </ul> -->
      <span class="header_btn" @click="hCheckFun">[展开]</span>
    </el-header>

    <!-- <div style="background: #474e60" v-show="flag">
      <ul class="header_ul">
        <li
          style="padding: 15px 20px 15px 20px; color: #fff; cursor: pointer"
          @click="headerTitle(index)"
          :class="{ indexActive: tltIndex == index }"
          v-for="(item, index) in menuList1"
          :key="index"
        >
          {{ item.purview_name }}
        </li>
      </ul>
    </div> -->
    <el-container style="overflow: auto">
      <el-aside width="200px">
        <!-- 选中站点标题 -->
        <div
          style="
            background: #242527;
            line-height: 46px;
            height: 46px;
            color: #fff;
          "
        >
          <img
            style="
              width: 12px;
              height: 16px;
              margin: -3.5px 0 0 11.5%;
              vertical-align: middle;
            "
            src="../assets/images/dingwei.png"
            alt=""
          />
          <span style="font-size: 13px; margin: 0 0 0 1.5px">{{
            siteNameTitle
          }}</span>
        </div>

        <el-menu
          :default-active="$route.path"
          :collapse-transition="false"
          class="el-menu-vertical-demo"
          :router="isRouter"
          @select="handleOpen"
          active-text-color="rgb(57, 249, 190)"
        >
          <el-menu-item index="/index/monitor1">
            <i :class="iconObj[20]"></i>
            <span slot="title">可视农业应用系统</span>
          </el-menu-item>
          <el-menu-item index="/index/list1">
            <i :class="iconObj[22]"></i>
            <span slot="title">设备列表</span>
          </el-menu-item>
          <el-menu-item index="/index/userManger1">
            <i :class="iconObj[23]"></i>
            <span slot="title">用户管理</span>
          </el-menu-item>
        </el-menu>

        <div v-if="isTree" style="margin: 13px 0 0 0; width: 95%">
          <ul>
            <li style="display: flex; justify-content: space-between">
              <div style="display: flex; margin: 0 0 0 5px">
                <img
                  style="width: 13px; height: 13px; margin: 3px 3px 0 0"
                  src="../assets/images/zhankai.png"
                  alt=""
                />
                <div
                  style="
                    font-weight: 550;
                    color: #fff;
                    font-size: 13px;
                    margin: 0px 0px 0px 4px;
                  "
                >
                  站点管理
                </div>
              </div>
              <img
                style="
                  width: 16px;
                  height: 16px;
                  margin: 3px 0 0 0;
                  cursor: pointer;
                "
                src="../assets/images/tianjia.png"
                alt=""
                @click="addStation"
                v-if="userinfo.staff == '1'"
              />
            </li>

            <li id="tree">
              <el-tree
                ref="treeRef"
                :data="data"
                :props="defaultProps"
                node-key="id"
                :current-node-key="firstItem"
                :default-expand-all="true"
                @node-click="handleNodeClick"
                @node-contextmenu="rightClick"
                highlight-current
              ></el-tree>
            </li>
          </ul>
        </div>
      </el-aside>

      <!-- 右键信息 -->
      <div v-show="menuVisible">
        <ul id="menuList" class="menu">
          <li class="menu_item" @click="addrInformation()">增加</li>
        </ul>
      </div>
      <el-main>
        <router-view ref="mychild" :flag="dataObj"></router-view>
      </el-main>
    </el-container>

    <!-- 添加站点 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="新增站点"
      :visible.sync="addSite"
      width="25%"
    >
      <ul>
        <li style="margin: 10px 0 0 0">
          <span>站点名称：</span>
          <el-input style="width: 49%" v-model="siteName"></el-input>
        </li>
        <li style="margin: 10px 0 0 0">
          <span>站点地址：</span>
          <el-cascader
            clearable
            v-model="siteAddr"
            :options="options"
          ></el-cascader>
        </li>
      </ul>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addSite = false">取 消</el-button>
        <el-button type="primary" @click="addrData()">确 定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>
<script>
import city from "../components/citydata.js";
export default {
  data() {
    return {
      siteId: "",
      isTree: true,
      firstItem: "",
      firstShow: true,
      isRouter: true,
      iconObj: {
        20: "iconfont icon-jiankong",
        22: "iconfont icon-shebei",
        23: "iconfont icon-xitong",
      },
      flag: true,
      active: 1,
      userinfo: {},
      username: "",
      userphoto: "",
      menuList1: [
        {
          purview_name: "可视农业应用系统",
          menu: "monitor1",
          parent_perm_id: 1,
          pur_id: 1,
        },
        {
          purview_name: "设备列表",
          menu: "list1",
          parent_perm_id: 2,
          pur_id: 2,
        },
        {
          purview_name: "用户管理",
          menu: "userManger1",
          parent_perm_id: 3,
          pur_id: 3,
        },
      ],

      // 站点
      tltIndex: 0,
      addSite: false,
      siteName: "", // 站点名称
      siteAddr: [], // 站点地址
      options: [],
      data: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      menuVisible: false,

      siteNameTitle: "全 部",
      req: "", // 站点列表是否显示有无设备的站点
      equip_type: "", //选中的设备类型

      dataObj: {
        flag: true,
        siteID: null,
        allList: [],
        cid :null
      },
    };
  },
  created: function () {
    this.getuserinfo();
  },
  watch: {
    addSite(val) {
      if (val == false) {
        this.siteName = "";
        this.siteAddr = [];
        this.operateObj = {};
      }
      // else if (val == true) {
      // 	if (this.operateObj.label) {
      // 		console.log(this.operateObj)

      // 	} else {
      // 	}
      // }
    },
    // 监听路由变化，如果变化就将展示选中的站点名称归零为全部
    $route(to, from) {
      if (to.path == "/index/monitor1") {
        console.log(this.$refs.mychild);
      }
      this.siteNameTitle = "全 部";
    },

    equip_type(val) {
      console.log(val);
      this.siteListData();
    },
  },
  computed: {},
  mounted() {
    if (sessionStorage.getItem("tltIndex")) {
      this.tltIndex = sessionStorage.getItem("tltIndex");
    }
    this.siteListData();
    this.options = city;

    var url = this.$route.path;
    url = url.split("/index", 2);
    if (url[1] == "/xycb") {
      sessionStorage.setItem("tltIndex", 0);
      this.tltIndex = 0;
    }

    // 获取当前点击的设备类型
    if (url[1] == "/monitor1") {
      // 性诱测报
      this.req = "hide";
      this.equip_type = "6";
    } else {
      this.req = "";
      this.equip_type = "";
    }
  },
  methods: {
    hCheckFun() {
      this.flag = !this.flag;
      this.dataObj.flag = this.flag;
    },
    getuserinfo() {
      this.$axios({
        method: "post",
        url: "userinfo_",
      }).then((res) => {
        this.username = res.data.username;
        this.userphoto = res.data.userphoto;
        localStorage.setItem("username", res.data.username); // 0管理员  1用户
      });
      this.$axios({
        method: "get",
        url: "user_detail",
      }).then((res) => {
        this.userinfo = res.data;
        localStorage.setItem("have_type", this.userinfo.have_type); // 0管理员  1用户
        localStorage.setItem("staff", this.userinfo.staff); // 1是admin
        localStorage.setItem('site_id', this.userinfo.site_id) // 站点id
				localStorage.setItem('siteName', this.userinfo.site) // 站点name
      });
    },

    headerTitle(i) {
      this.tltIndex = i;
      console.log(i);
      sessionStorage.setItem("tltIndex", i);
      this.$router.push("/index/" + this.menuList1[i].menu);
    },

    // 添加新站点
    addStation() {
      this.addSite = true;
      this.operateObj = {};
    },

    // 站点名称列表
    siteListData() {
      this.$axios({
        method: "GET",
        url: "site_manage",
        params: {
          req: this.req,
          equip_type: this.equip_type,
          jk_type: "2",
        },
      })
        .then((res) => {
          console.log(res);
          if (res.data) {
            var data = res.data;
            var arrList = [];
            var list = data.forEach((item) => {
              if (
                item.self_site_name !== undefined &&
                item.self_site_name == ""
              ) {
              } else {
                if (item.self_site_name == undefined) {
                  if (item.child) {
                    var obj = {};
                    var a = [];
                    obj["label"] = item.site_name;
                    obj["id"] = item.site_id;
                    for (var j in item.child) {
                      var obja = {};
                      obja["label"] = item.child[j].site_name;
                      obja["id"] = item.child[j].site_id;
                      if (
                        item.child[j].child &&
                        item.child[j].child.length == 0
                      ) {
                        obja["children"] = item.child[j].child;
                      } else if (
                        item.child[j].child &&
                        item.child[j].child.length !== 0
                      ) {
                        for (var k in item.child[j].child) {
                          var objb = {};
                          objb["label"] = item.child[j].child[k].site_name;
                          objb["id"] = item.child[j].child[k].site_id;
                        }
                        obja["children"] = [objb];
                      }
                      a.push(obja);
                      obj["children"] = a;
                    }
                  }
                  arrList.push(obj);
                } else if (item.self_site_name !== undefined) {
                }
              }
            });
            this.data = arrList;
            console.log(arrList);
            // 默认选中第一个站点
            // this.siteNameTitle = data[0].child[0].site_name;
            // this.firstItem = data[0].child[0].site_id;
            if(localStorage.getItem('siteName')=='超级管理员'){
							this.siteNameTitle = "瑞通集团总站"
						}else{
							this.siteNameTitle = localStorage.getItem('siteName');
						}
						this.firstItem = localStorage.getItem('site_id');
            let data = {};
						this.treeIterator(arrList,res => {
							if(res.id==this.firstItem){
								data = res
							}
						})
            this.$nextTick(() => {
              this.$refs.treeRef.setCurrentKey(this.firstItem);
              // const childrenItem = arrList[0].children[0];
              const childrenItem = data;
              if (this.firstShow) {
                this.handleNodeClick(childrenItem);
                this.firstShow = false;
              }
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  treeIterator(tree, func) {
			let node, curTree = [...tree]
			while ((node = curTree.shift())) {
			func(node)
			node.children && curTree.push(...node.children)
			}
		},
    // 树形插件
    handleNodeClick(data) {
      // this.operateObj = data
      var url = this.$route.path;
      this.siteId = data.id;
      this.siteNameTitle = data.label;
      url = url.split("/index/", 2);
      if (url[1] == "monitor1") {
        this.$refs.mychild.getJkList(data, 1);
        this.$refs.mychild.$data.siteVal = "";
        this.$refs.mychild.plotList(data, 1);
      } else {
        this.$refs.mychild.getList(data, 1);
      }
    },

    // 树形插件右键点击事件
    rightClick(MouseEvent, object, Node, element) {
      console.log(object);
      this.menuVisible = false; // 先把模态框关死，目的是 第二次或者第n次右键鼠标的时候 它默认的是true
      this.menuVisible = true; // 显示模态窗口，跳出自定义菜单栏
      var menu = document.querySelector("#menuList");
      document.addEventListener("click", this.foo); // 给整个document添加监听鼠标事件，点击任何位置执行foo方法
      menu.style.display = "block";
      menu.style.left = MouseEvent.clientX - 0 + "px";
      menu.style.top = MouseEvent.clientY - 0 + "px";
      this.operateObj = object;
    },
    foo() {
      // 取消鼠标监听事件 菜单栏
      this.menuVisible = false;
      document.removeEventListener("click", this.foo); // 要及时关掉监听，不关掉的是一个坑，不信你试试，虽然前台显示的时候没有啥毛病，加一个alert你就知道了
    },
    // 指定新增
    addrInformation() {
      this.addSite = true;
    },

    addrData() {
      console.log(this.operateObj.id);
      console.log(this.operateObj);
      if (this.siteName == "") {
        this.$message({
          message: "未填写站点名称，请填写！",
          type: "warning",
          duration: 1500,
        });
      } else if (this.siteAddr.length == 0) {
        this.$message({
          message: "未填写站点地址，请填写！",
          type: "warning",
          duration: 1500,
        });
      } else {
        if (this.siteAddr.length < 3) {
          var sheng = "";
          var shi = this.siteAddr[0];
          var xian = this.siteAddr[1];
        } else {
          var sheng = this.siteAddr[0];
          var shi = this.siteAddr[1];
          var xian = this.siteAddr[2];
        }
        var postData = this.qs.stringify({
          site_name: this.siteName, // 站点名称
          site_pro: sheng, // 省
          site_city: shi, // 市
          site_area: xian, // 县或区
          site_parent_id:
            this.operateObj.id !== undefined ? this.operateObj.id : "", // id
        });
        this.$axios({
          method: "POST",
          url: "/site_manage",
          data: postData,
        })
          .then((res) => {
            console.log(res.data);
            if (res.data.status == 0) {
              this.$message({
                message: res.data.msg,
                type: "success",
                duration: 1500,
              });
              this.addSite = false;
              this.siteListData();
            } else {
              this.$message({
                message: res.data.msg,
                type: "error",
                duration: 1500,
              });
            }
          })
          .catch((err) => {
            console.log(err);
            this.$message({
              message: "添加失败请重试！",
              type: "error",
              duration: 1500,
            });
          });
      }
    },

    // 获取到当前点击菜单的数据
    handleOpen(key, keyPath) {
      this.isTree = true;
      var data = key;
      var typeIndex = data.split("/index/");
      if (typeIndex[1] == "monitor1") {
        // 性诱测报
        this.req = "hide";
        this.equip_type = "6";
        this.siteId = this.firstItem;
        console.log(localStorage.getItem('site_id')=="0");
        if(localStorage.getItem('site_id')=="0"){
          this.dataObj.cid = '';
        }else{
          this.dataObj.cid = this.siteId;
        }
        
      } else if (typeIndex[1] == "userManger1") {
        console.log(this.$refs.mychild);
        this.isTree = false;
      } else {
        this.req = "";
        this.equip_type = "";
      }
    },

    // 点击获取全部站点名称列表
    allSiteListData() {
      this.req = "";
      this.equip_type = "";
      this.siteListData();
    },
  },
};
</script>

<style scoped lang="less">
.header {
  position: relative;
  width: 100%;
  height: 177px !important;
  border-bottom: 2px solid #272b3a;
  background: #272b3a no-repeat center / 100% 100%
    url(../assets/images/monitor/h_bg.jpg);
  .userinfo {
    color: #fff;
    position: absolute;
    top: 10px;
    right: 10px;
    .userheadImg {
      width: 35px;
      height: 35px;
      border-radius: 50%;
      vertical-align: middle;
      margin-right: 6px;
    }
  }
  .sysName {
    color: #fff;
    text-align: center;
    h2 {
      font-size: 26px;
    }
    p {
      font-size: 14px;
    }
    margin-top: 50px;
  }
  .logInfo {
    color: #fff;
    position: absolute;
    top: 10px;
    left: 20px;
    display: flex;
    flex-direction: row;
    align-items: center;
    img {
      width: auto;
      height: 40px;
    }
    h3 {
      margin: 0;
      margin-left: 20px;
    }
  }
}
.header2 {
  border-bottom: 2px solid #272b3a;
  position: relative;
  background-color: #323749;
  color: #fff;
}
.site {
  position: absolute;
  right: 8px;
  top: 30px;
  z-index: 888;
  font-size: 14px;
  color: #ffffff;
  span {
    color: #fff;
    letter-spacing: 1px;
    font-size: 13px;
  }
}
.header_btn {
  position: absolute;
  color: #727272;
  font-size: 14px;
  right: 20px;
  bottom: 10px;
  cursor: pointer;
}
.header_btn:hover {
  color: #fff;
}

.el-aside {
  background: #474e60;
  .el-menu {
    background: #232735;
    .el-menu-item {
      color: #909399;
    }
    .is-active {
      background-color: rgba(45, 111, 102, 0.4);
    }
    .el-menu-item:focus,
    .el-menu-item:hover {
      color: #39f9be;
      background-color: rgba(45, 111, 102, 0.4);
      i {
        color: #39f9be;
      }
    }
  }
}
.el-main {
  padding: 0;
  background-color: #f6f6f6;
}

// 新改
.header_ul {
  display: flex;
  justify-content: flex-end;
  margin: 0 85px 0 0;
}

.indexActive {
  border-bottom: 2px solid #fff;
}

#tree {
  margin: 15px 0 0 0;
  div {
    background: #474e60;
  }
}

.el-tree {
  // color: #fff !important;
  color: #8c8989 !important;
}
.el-tree-node__content:hover {
  background-color: #55575a !important;
}

// 右键信息
#menuList {
  height: 40px;
  width: 80px;
  position: absolute;
  border-radius: 10px;
  border: 1px solid #d8d6d6;
  background-color: #fff;
  z-index: 1;
  .menu_item {
    line-height: 20px;
    text-align: center;
    margin-top: 10px;
    cursor: pointer;
  }
  li:hover {
    background-color: #14a478;
    color: white;
  }
  li {
    font-size: 15px;
  }
}
</style>
