<template>
  <div>
    <!--顶级按钮-->
    <div class="btn-group mr-1" 
      v-if="jiBie == 0"
    >
      <button
        type="button"
        @click="selectAgency"
        class="btn btn-sm btn-outline-secondary"
      >
        {{ $store.state.user.agentFlag ? $store.state.user.nickName : "智慧易加"}}
      </button>
      <button
        type="button"
        class="
          btn btn-sm btn-outline-secondary
          dropdown-toggle dropdown-toggle-split
        "
        data-toggle="dropdown"
        aria-expanded="false"
      >
        <span class="sr-only"></span>
      </button>
      <div
        class="dropdown-menu"
        style="overflow-y: auto; max-height: 400px; max-width: 280px"
      >
        <form class="px-4 py-3">
          <input
            type="email"
            class="form-control"
            id="exampleDropdownFormEmail1"
            placeholder=""
            autocomplete="off"
            @input="filterMethod"
            v-model="filterText"
          />
        </form>
        <div class="dropdown-divider"></div>
        <a
          class="dropdown-item"
          href="#"
          v-for="ele in filteredGroups"
          :key="ele.deptId"
          @click="selectGroup(ele)"
          >{{ ele.deptName }}</a
        >
      </div>
    </div>
    <!--集团按钮-->
    <div class="btn-group mr-1" 
      v-show="!!currentGroup"
      v-if="jiBie == 0 || jiBie == 1 "
    >
      <button
        @click="selectGroup(currentGroup)"
        type="button"
        class="btn btn-sm btn-outline-secondary"
      >
        {{ (currentGroup||{}).deptName }}
      </button>
      <button
        type="button"
        class="
          btn btn-sm btn-outline-secondary
          dropdown-toggle dropdown-toggle-split
        "
        data-toggle="dropdown"
        aria-expanded="false"
      >
        <span class="sr-only"></span>
      </button>
      <div
        class="dropdown-menu"
        style="overflow-y: auto; max-height: 400px; max-width: 280px"
      >
        <form class="px-4 py-3">
          <input
            type="email"
            class="form-control"
            id="exampleDropdownFormEmail2"
            placeholder=""
            autocomplete="off"
            @input="filterMethod"
            v-model="filterText"
          />
        </form>
        <div class="dropdown-divider"></div>
        <a
          class="dropdown-item"
          href="#"
          v-for="ele in filteredStations"
          :key="ele.deptId"
          @click="selectStation(ele)"
          >{{ ele.deptName }}</a
        >
      </div>
    </div>
    <!--站点-->
    <button type="button" class="btn btn-sm btn-primary"  style="background-color:#1890ff">
      {{ tip  + (jiBie !=2 ? "：" : "") + currentShow.deptName }}
    </button>
  </div>
</template>

<script>
import { userdepttree, getGroups, getStations  } from "@/api/system/dept";
import { mapMutations } from 'vuex'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: { Treeselect },
  data() {
    return {
      value: null,
      options: [],
      Infinity: 2,
      num: 0,
      tip:'',
      Agency: {
        deptId: 100,
        deptName: this.$store.state.user.deptName,
      },
      groups: [
      ],
      stations: [
        {
          deptId: 4,
          deptName: "李哈哈的站点1",
        },
        {
          deptId: 5,
          deptName: "李哈哈的站点2",
        },
      ],
      currentStation: undefined,
      currentGroup: undefined,
      filterText:"",
      filterStationText:"",
      filterTimer:null
    };
  },
  computed: {
    currentShow() {
      if (!!this.currentStation) {
        return this.currentStation;
      }
      if (!!this.currentGroup) {
        return this.currentGroup;
      }
      return this.Agency;
    },
    filteredGroups(){
      return this.groups.filter((ele)=>{
        return ele.deptId.toString().includes(this.filterText) || ele.deptName.includes(this.filterText)
      })
    },
    filteredStations(){
      return this.stations.filter((ele)=>{
        return ele.deptId.toString().includes(this.filterText) || ele.deptName.includes(this.filterText)
      })
    }
  },
  watch: {
    // 监听deptId
    value: "currDeptChange",
  },
  created() {
    this.init();
  },
  methods: {
    ...mapMutations({
      setLevelId:"SET_LEVELID"
    }),
    init() {
      if(this.jiBie == 0){
        this.tip = this.$store.state.user.agentFlag ? '代理' : "全站"
        this.setLevelId(undefined)
        this.selectAgency();
      }else if(this.jiBie == 1){
        this.tip = "集团"
        this.currentGroup = {
          deptId: undefined,
          deptName: this.$store.state.user.deptName
        }
        this.setLevelId(this.currentGroup.deptId) 
        this.selectGroup(this.currentGroup);
      }else if(this.jiBie == 2){
        this.setLevelId(undefined) 
      }
    },
    selectAgency() {
      this.tip = this.$store.state.user.agentFlag ? '代理' : "全站";
      this.filterText = "";
      this.currentGroup = undefined;
      this.currentStation = undefined;
      this.setLevelId(undefined)

      getGroups().then((res)=>{
        if(res.code == 200){
          this.groups = res.data
        }else{
          throw new Error("");
        }
      }).catch(()=>{
        this.msgError("拉取首页菜单的集团列表失败，请刷新网页")
      })
      this.refreshTagView();
    },
    selectGroup(group) {
      this.tip = "集团";
      this.filterText = "";
      this.currentGroup = group;
      this.currentStation = undefined;
      const id =  this.jiBie==1 ? undefined : this.currentGroup.deptId;
      this.setLevelId(id);
      getStations({
        deptId: group.deptId
      }).then((res)=>{
        if(res.code == 200){
          this.stations = res.data
        }else{
          throw new Error("");
        }
      }).catch(()=>{
        this.msgError("拉取首页菜单的站点列表失败，请刷新网页")
      })
      this.refreshTagView();
    },
    selectStation(station) {
      this.tip = "站点";
      this.filterText = "";
      this.currentStation = station;
      const id = this.jiBie==2 ? undefined : this.currentStation.deptId; 
      this.setLevelId(id) 
      this.refreshTagView();
    },
    /** 查询部门下拉树结构 */
    // getTreeselect() {
    //   userdepttree().then((response) => {
    //     this.options = response.data;
    //     if (response.data != null && response.data.length > 0) {
    //       this.value = response.data[0].id;
    //       this.$store.selectDeptName = response.data[0].label;
    //       this.$store.selectDeptId = response.data[0].id;
    //     }
    //   });
    // },
    currDeptChange(val) {
      if (val) {
        this.$store.selectDeptId = val;
        if (this.num > 0) {
          let path = this.$route.path;
          let visitedViews = this.$store.state.tagsView.visitedViews;
          let stagpath = null;
          const proArr = [];
          for (let i = 0; i < visitedViews.length; i++) {
            let view = visitedViews[i];
            proArr.push(
              this.$store.dispatch("tagsView/delCachedView", view).then(() => {
                const { fullPath } = view;
                if (path === fullPath) {
                  stagpath = view;
                } else {
                  this.$nextTick(() => {
                    this.$router.replace({
                      path: "/redirect" + fullPath,
                    });
                  });
                }
              })
            );
          }
          Promise.all(proArr).then(() => {
            if (stagpath != null) {
              this.$store
                .dispatch("tagsView/delCachedView", stagpath)
                .then(() => {
                  const { fullPath } = stagpath;
                  this.$nextTick(() => {
                    this.$router.replace({
                      path: "/redirect" + fullPath,
                    });
                  });
                });
            }
          });
        }
        this.num = this.num + 1;
      }
    },
    refreshTagView() {
      const proArr = []
      this.$store.state.tagsView.visitedViews.map((view) => {
        proArr.push(this.$store.dispatch("tagsView/delCachedView", view))
        // this.$store.dispatch("tagsView/delCachedView", view).then(() => {
        //   const { fullPath } = view;
        //   // this.$nextTick(() => {
        //   //   this.$router.replace({
        //   //     path: "/redirect" + fullPath,
        //   //   });
        //   // });
        // });
      });
      Promise.all(proArr).then(()=>{
          this.$nextTick(() => {
            this.$router.replace({
              path: "/redirect" + this.$route.path,
            });
          });
      })
    },
    filterMethod(e){
      clearTimeout(this.filterTimer);
      this.filterTimer = setTimeout(()=>{
        this.filterText = e.target.value  
      }, 800)
    },
  },
};
</script>
<style lang="scss">
.vue-treeselect__control {
  height: 20px;
  line-height: 26px;
  font-size: 12px;
  text-indent: 4px;
}
.vue-treeselect__menu-container {
  position: absolute;
  left: 0;
  width: 100%;
  overflow: visible;
  transition: 0s;
}
.vue-treeselect__menu {
  font-size: 12px;
}
</style>