<template>
  <div class="navigation">
    <div class="filterArea">
      <!-- <div class="demonstration">搜索建筑</div> -->
      <div class="search">
        <!-- <el-input v-model="filterText" placeholder="建筑名称/ID"></el-input>
        <el-button type="primary" icon="search" @click="filterSearch"></el-button> -->
        <el-autocomplete
          placeholder="机构名称/ID"
          v-model="filterText"
          :fetch-suggestions="querySearchAsync"
          popper-class="my-autocomplete"
          @select="handleSearchSelect"
        >
          <template slot="prepend" ><i class="el-icon-search"></i></template>
        </el-autocomplete>
      </div>
    </div>
    <div class="tree">
      <el-tree
        :data="treeData"
        :props="defaultProps"
        :load="loadNode"
        lazy
        highlight-current
        node-key="id"
        ref="tree"
        accordion
        auto-expand-parent
        :current-node-key="currentNodeKey"
        @current-change="handleNodeLocationClick"
        :default-expanded-keys="defaultExpanded"
        :expand-on-click-node="true"
        :filter-node-method="filterNode">
      </el-tree>
    </div>
  </div>
</template>

<script>
  import Api from '@/api/index.js'

  export default {
    data () {
      return {
        timeout: null,
        filterText: '', // 搜索文本
        defaultProps: { // 默认节点标签
          children: 'children',
          label: 'name',
          isLeaf: 'isLeaf' // 设置下钻箭头
        },
        treeData: [{ // 树结构数据结构
          parentId: 0,
          grade: 0,
          id: 1,
          name: '广东省',
          children: []
        }],
        currentNodeKey: '', // 当前选中节点的 key -> string, number
        defaultExpanded: [] // 默认展开的节点的 key 的数组 -> array
      }
    },
    computed: {
      gisopUserInfo () {
        return this.$store.state.gisopUserInfo
      }
    },
    /* watch: {
      gisopUserInfo () {
        this.init()
      }
    },
    mounted () {
      this.init()
    }, */
    methods: {
      init () {
        // console.log(this.gisopUserInfo)
        let orgId = this.gisopUserInfo.organGuid
        /* if (this.$route.query.UserAccount) {
          orgId = this.userInfo.organGuid
        } */
        var orgId2 = orgId || 1
        Api.getUserTree(orgId2)
        .then(data => { 
          this.treeData = [{
            parentId: data.parentId,
            grade: data.grade,
            id: data.id,
            name: data.name
          }]
          this.defaultExpanded = [data.id]
        }).catch(res => { 
          // error callback
          this.$message({
            showClose: true,
            message: '[导航树]加载数据有错，请重试。',
            type: 'warning'
          })
          this.treeData = []
          // console.log('error:',res)
        })
      },
      loadNode (node, resolve) { // 加载节点
        // let vm = this
        // console.log(node)
        if (node.level === 0) {
          return false
        }

        var getTreeItemsByOrgId = (id, parentId, grade) => {
          let arr = []
          Api.getTreeItemsByOrgId(id, parentId, grade)
          .then(body => { 
            // console.log(body)
            if (body instanceof Array) {
              body.forEach((item) => {
                arr.push({
                  parentId: item.parentId,
                  grade: item.grade,
                  id: item.id,
                  name: item.name,
                  isLeaf: node.data.grade >= 2 // 控制几级后不能出现三角，点击加载下级
                })
              })
            } else {
              arr = []
            }
            // 省级加载下级
            let data = (node.data.grade >= 0) ? arr : []
            // console.log(data)
            setTimeout(() => {
              resolve(data)
            }, 300)
          }).catch(res => { 
            console.log('error:', res)
          })
        }
        getTreeItemsByOrgId(node.data.id, node.data.parentId, node.data.grade)
      },
      querySearchAsync (queryString, cb) { // 搜索， 回调处理显示
        var gisopUserInfo  = this.$store.state.gisopUserInfo
        var grade = gisopUserInfo.grade
        var orgId = gisopUserInfo.organGuid
        // console.log(grade,orgId);
        // let vm = this
        // console.log(queryString)
        if (queryString === '') {
          let arr = []
          cb(arr)
          this.init()
        } else {
          clearTimeout(this.timeout)
          this.timeout = setTimeout(() => {
            /* this.$http.get(Api.navApi+'/getListByKey?key='+queryString+"&grade="+grade+"&orgId="+orgId)
              .then(response => {
                if (response.data != []) {
                  var restaurants = response.data,
                    arr = []
                  restaurants.forEach((item, index) => {  //fql20170628修改获取的数据名称
                      arr.push({
                        id: item.id,
                        value: item.name,
                        grade: item.grade,
                        parentId: item.parentId
                      })
                  })
                  cb(arr)
                }else {
                  cb([])
                }             
              }).catch(response => {
                // error callback
                console.log('error:',response)
            }) */
            Api.getListByKey(queryString, grade, orgId)
            .then(data => { 
              if (data !== []) {
                var restaurants = data,
                  arr = []
                restaurants.forEach((item, index) => { // fql20170628修改获取的数据名称
                    arr.push({
                      id: item.id,
                      value: item.name,
                      grade: item.grade,
                      parentId: item.parentId
                    })
                })
                cb(arr)
              } else {
                let arr = []
                cb(arr)
              }      
            }).catch(res => { 
              console.log('error:', res)
            })
          }, 500)
        }
      },
      handleSearchSelect (item) { // 下拉框选择，回调函数
        // console.log("点击搜索结果：",item);
        this.filterText = item.name
        this.filterSearch(item.id, item.grade)
      },
      filterSearch (...arg) { // 对搜索关键字，API调用，返回数据
        Api.getListByKey(arg[0], arg[1])
        .then(data => { 
          let datas = data.data
          let defaultExpanded = [],
              arr = []
          // console.log(data)
          for (let i = 0; i < datas.length - 1; i++) {
            // console.log(data[i])
            defaultExpanded.push(datas[i].id)
            datas[i + 1].children = [datas[i]]
            // console.log(data);
          }
          arr = [data[datas.length - 1]]
          // console.log(arr, defaultExpanded);
          this.treeData = arr
          this.defaultExpanded = defaultExpanded
          this.currentNodeKey = defaultExpanded[0]
          // console.log(this.currentNodeKey)     
        }).catch(res => { 
          console.log('error:', res)
        })
        // console.log(arg)
        /* this.$http.get(Api.navApi+'/getParentListById',{
          params: {
            id: arg[0],
            grade: arg[1]
          }
        }).then(response => {
          let data = response.data,
              defaultExpanded = [],
              arr = []
          // console.log(data)
          for (let i=0; i<data.length-1; i++) {
            // console.log(data[i])
            defaultExpanded.push(data[i].id)
            data[i+1].children = [data[i]];
            // console.log(data);
          }
          arr = [data[data.length-1]]
          //console.log(arr, defaultExpanded);
          this.treeData = arr
          this.defaultExpanded = defaultExpanded
          this.currentNodeKey = defaultExpanded[0]
          console.log( this.currentNodeKey )
        }, response => {
          console.log("err: ", response)
        }) */
      },
      filterNode (value, data, node) { // 节点过滤当前节点
        // if (!value) this.loadNode(node);
        return data.name.indexOf(value) !== -1
      },
      handleNodeLocationClick (data, node, self) { // 绑定点击节点父组件传递
        // console.log('node-click:', self);
        this.$emit('treeClick', data)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .navigation {
    display: flex;
    flex-direction: column;
    width: 230px;
    max-height: 100%;
    height: 100%;
    padding: 12px 0;
    margin-right: 0;
    float: left;

    .filterArea {
      padding: 0 4px 10px;
    }

    .tree {
      display: flex;
      flex-direction: column;
      flex: 1;
      overflow-y: auto;
    }
  }
</style>
