<template>
  <div style="margin-right: 16px;">
    <!--树形下拉框-->
    <el-select :value="valueTitle" :clearable="clearable" @clear="clearHandle">
      <el-option :value="valueTitle" :label="valueTitle" :key="valueId">
        <el-tree id="tree-option" ref="selectTree" :accordion="accordion" :data="options" :props="props" :node-key="props.value" :default-expanded-keys="defaultExpandedKey" @node-click="handleNodeClick">
        </el-tree>
      </el-option>
    </el-select>
  </div>
</template>

<script lang="ts">
import {
  Vue,
  Component,
  Prop,
  Model,
  Emit,
  Inject,
} from "vue-property-decorator";
import { Subject } from "rxjs";

@Component({})
export default class AppTreeselectRefreshview extends Vue {
  /**
   * 树数据
   *
   * @type {Array<*>}
   * @memberof AppTreeselectRefreshview
   */
  public options: any[] = [];

  /**
   * 树显示说明
   *
   * @type {*}
   * @memberof AppTreeselectRefreshview
   */
  public props: any = {
    value: "id", // ID字段名
    label: "label", // 显示名称
    children: "apps", // 子级字段名
  };

  /**
   * 下拉框初始值的key
   *
   * @type {*}
   * @memberof AppTreeselectRefreshview
   */
  public valueId: any = null;

  /**
   * 下拉框初始值
   *
   * @type {*}
   * @memberof AppTreeselectRefreshview
   */
  public valueTitle: any = "";

  /**
   * 默认展开节点key
   *
   * @type {Array<any>}
   * @memberof AppTreeselectRefreshview
   */
  public defaultExpandedKey: any[] = [];

  /**
   * 是否每次只打开一个同级树节点展开
   *
   * @type {boolean}
   * @memberof AppTreeselectRefreshview
   */
  public accordion: boolean = false;

  /**
   * 可清空选项
   *
   * @type {boolean}
   * @memberof AppTreeselectRefreshview
   */
  public clearable: boolean = true;

  /**
   * vue创建
   *
   * @memberof AppTreeselectRefreshview
   */
  created(): void {}

  /**
   * vue挂载
   *
   * @memberof AppTreeselectRefreshview
   */
  mounted(): void {
    // 初始化数据
    this.initHandle();
  }

  /**
   * 获取初始化数据
   *
   * @memberof AppTreeselectRefreshview
   */
  public initHandle() {
    let url: any = "/dst/sysapps";
    this.$http
      .get(url)
      .then((response: any) => {
        if (response && response.status == 200) {
          const data: any = response.data;
          if (data && data.length > 0) {
            // 处理数据，生成有相同结构的父子节点结构
            let tempData: any = [];
            data.forEach((item: any) => {
              let tempItem: any = item;
              if (tempItem.pssystemid) {
                tempItem.id = tempItem.pssystemid;
                tempItem.systemId = tempItem.pssystemid;
              }
              if (tempItem.pssystemname) {
                tempItem.label = tempItem.pssystemname;
              }
              tempData.push(tempItem);
            });

            // 给树赋值
            this.options = tempData;
            // 下拉树
            let tree: any = this.$refs.selectTree;
            // 第一个叶子节点
            let firstNode: any = {};
            if (tempData[0].apps) {
              firstNode = tempData[0].apps;
            } else {
              firstNode = tempData[0];
            }

            // 从local中拿刷新前选中值
            if (localStorage.getItem("localdata")) {
              const localdata: any = JSON.parse(
                localStorage.getItem("localdata") as string
              );
              this.valueId = localdata.dstappid;
              this.valueTitle = localdata.title;
              this.defaultExpandedKey.push(localdata.dstappid);
              // 设置下拉树选中值
              tree.setCurrentKey(localdata.dstappid);
            } else {
              // 设置下拉框默认值
              this.valueId = firstNode[0].id;
              this.valueTitle =
                firstNode[0].systemId + "-" + firstNode[0].label;
              this.defaultExpandedKey.push(firstNode[0].id);
              // 设置下拉树选中值
              tree.setCurrentKey(firstNode[0].id);
            }
          }
        } else {
          console.warn("加载数据错误");
        }
      })
      .catch((error: any) => {
        console.warn(
          "加载数据错误," + typeof error == "string"
            ? error
            : JSON.stringify(error)
        );
      });
  }

  /**
   * 注入加载行为
   *
   * @type {*}
   * @memberof AppTreeselectRefreshview
   */
  @Inject("reload")
  reload!: any;

  /**
   * 处理下拉框选中项
   *
   * @param {*} node 节点对象
   * @memberof AppTreeselectRefreshview
   */
  public handleNodeClick(node: any) {
    // 父级节点不进行处理
    if (node.apps) {
      return;
    }
    // 从local中拿刷新前选中值
    if (localStorage.getItem("localdata")) {
      const localdata: any = JSON.parse(
        localStorage.getItem("localdata") as string
      );
      if (localdata.dstappid == node[this.props.value]) {
        return;
      }
    }
    // 重新赋值
    this.valueId = node[this.props.value];
    const dstsystemid: any = node.systemId;
    this.valueTitle = dstsystemid + "-" + node[this.props.label];
    // 添加本地应用数据
    const localdata: any = {
      dstsystemid: dstsystemid,
      dstappid: this.valueId,
      title: this.valueTitle,
    };
    this.$store.commit("addLocalData", localdata);
    // 调用App.vue的加载行为
    // this.reload();
    // 浏览器window的加载行为
    window.location.reload();
  }

  /**
   * 清空选中项
   *
   * @memberof AppTreeselectRefreshview
   */
  public clearHandle() {
    this.valueId = null;
    this.valueTitle = "";
    this.defaultExpandedKey = [];
    // 清空当前选中节点
    let tree: any = this.$refs.selectTree;
    tree.setCurrentKey(null);
    // 收缩所有节点
    this.$nextTick(() => {
      for (let i = 0; i < this.options.length; i++) {
        tree.store.nodesMap[this.options[i].id].expanded = false;
      }
    });
  }

  /**
   * vue销毁之前
   *
   * @memberof AppTreeselectRefreshview
   */
  beforeDestroy(): void {
    this.valueId = null;
    this.valueTitle = "";
    this.defaultExpandedKey = [];
    this.options = [];
  }
}
</script>

<style lang='less'>
@import "app-treeselect-refreshview.less";
</style>