<template>
  <div :class="classStr" :id="id">
    <!--多选-->
    <template v-if="multiple">
      <q-select filled v-model="resultObj" :options="selectList" clearable @clear="clearData()" :label="tipText"
        :multiple="multiple" emit-value map-options>
         <template v-slot:option="scope">
          <q-item v-if="scope.index==-1">
            <q-item-section>
              <q-tree :nodes="treeData" :node-key="nodeKey" :label-key="labelKey" :children-key="childrenKey"
                tick-strategy="strict" :default-expand-all="defaultExpandAll" no-connectors
                :ticked.sync="chooseTreeNodeArray">
              </q-tree>
            </q-item-section>
          </q-item>
        </template>
        <template v-slot:after-options>
          <q-item>
            <q-item-section>
              <q-tree :nodes="treeData" :node-key="nodeKey" :label-key="labelKey" :children-key="childrenKey"
                tick-strategy="strict" :default-expand-all="defaultExpandAll" no-connectors
                :ticked.sync="chooseTreeNodeArray">
              </q-tree>
            </q-item-section>
          </q-item>
        </template>
      </q-select>
    </template>
    <!--单选-->
    <template v-else>
      <q-select filled v-model="resultObj[0]" :options="selectList" clearable @clear="clearData()" :label="tipText"
        :multiple="multiple" emit-value map-options>
        <template v-slot:option="scope">
          <q-item v-if="scope.index==0">
            <q-item-section>
              <q-tree :nodes="treeData" :node-key="nodeKey" :label-key="labelKey" :children-key="childrenKey"
                tick-strategy="strict" :default-expand-all="defaultExpandAll" no-connectors
                :ticked.sync="chooseTreeNodeArray">
              </q-tree>
            </q-item-section>
          </q-item>
        </template>
      </q-select>
    </template>
  </div>
</template>
<script>
  export default {
    props: {
      //样式字符串
      classStr: {
        type: String,
        default: ''
      },
      //树形结构列表
      treeData: {
        type: Array,
        required: true
      },
      //是否默认展开
      defaultExpandAll: {
        type: Boolean,
        default: false
      },
      //是否多选
      multiple: {
        type: Boolean,
        default: false
      },
      //默认选中值
      defaultArray: {
        type: Array,
        required: true,
      },
      //节点Key
      nodeKey: {
        type: String,
        default: 'id'
      },
      //节点名称
      labelKey: {
        type: String,
        default: 'name'
      },
      //子节点名称
      childrenKey: {
        type: String,
        default: 'children'
      },
      //下拉框提示信息
      tipText: {
        type: String,
        default: '请选择'
      }
    },
    data() {
      return {
        id: 'selectTree' + (Math.floor((Math.random() * 10000) + 1)),
        //下拉框列表
        selectList: [{
          value: "",
          label: ""
        }],
        //节点选择列表
        chooseTreeNodeArray: [],
        //下拉框选择列表
        resultObj: [],
      }
    },
    watch: {
      //Tree节点选中或取消选中
      chooseTreeNodeArray(val) {
        if (!this.multiple && this.chooseTreeNodeArray && this.chooseTreeNodeArray.length > 1) {
          var lastItem = this.chooseTreeNodeArray[this.chooseTreeNodeArray.length - 1];
          this.chooseTreeNodeArray = [lastItem];
        }
        this.setTreeCheckNode()
      },
      //有默认值
      defaultArray: {
        handler(newValue) {
          this.chooseTreeNodeArray = [];
          if (this.defaultArray && this.defaultArray.length > 0) {
            this.defaultArray.forEach(item => {
              if (item != '') {
                if (this.multiple) {
                  this.chooseTreeNodeArray.push(item)
                } else {
                  this.chooseTreeNodeArray = [item];
                }
              }
            })
          }
          this.setTreeCheckNode();
        },
        immediate: true
      },
      resultObj(val) {
        var resultStr = "";
        if (this.resultObj && this.resultObj.length > 0) {
          if (this.multiple) {
            let newarr = Array.from(new Set(this.resultObj)) //数组去重
            resultStr = newarr.toString();
          } else {
            resultStr = this.resultObj[0];
          }
        }
        this.$emit('getChild', resultStr);
      }
    },
    mounted() {},
    methods: {
      //清空数据
      clearData() {
        this.selectList = [{
          value: "",
          label: ""
        }];
        this.chooseTreeNodeArray = [];
        this.resultObj = [];
      },
      //设置下拉框选择
      setTreeCheckNode() {
        var that = this;
        this.selectList = [];
        this.resultObj = [];
        var nodes = this.findTreeNode(this.treeData);
        if (this.chooseTreeNodeArray && this.chooseTreeNodeArray.length > 0 && nodes && nodes.length > 0) {
          this.chooseTreeNodeArray.forEach(id => {
            nodes.forEach((item, index) => {
              if (item.value == id) {
                this.selectList.push({
                  value: item.value,
                  label: item.label
                });
                if (this.multiple) {
                  this.resultObj.push(item.value);
                  this.$forceUpdate();
                } else {
                  this.resultObj = [item.value];
                  this.$forceUpdate();
                }
              }
            })
          })
        }
        if (this.selectList && this.selectList.length == 0) {
          this.selectList = [{
            value: "",
            label: ""
          }];
        }
      },
      //获取树中所有节点
      findTreeNode(tree) {
        var that = this;
        var temp = [];
        //获取子节点
        var getChildNodes = function (tree) {
          if (tree && tree.length > 0) {
            for (var i = 0; i < tree.length; i++) {
              var item = tree[i];
              temp.push({
                label: tree[i][that.labelKey],
                value: tree[i][that.nodeKey]
              });
              if (tree[i][that.childrenKey]) {
                getChildNodes(tree[i][that.childrenKey]);
              }
            }
          }
        };
        getChildNodes(tree);
        return temp;
      }
    }
  }

</script>
