<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
                                v-model:ticked="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
                                v-model:ticked="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 #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
                                v-model:ticked="chooseTreeNodeArray"
                            ></q-tree>
                        </q-item-section>
                    </q-item>
                </template>
            </q-select>
        </template>
    </div>
</template>
<script lang="ts">
import { ref, toRefs, watch } from 'vue'
interface itemParams {
    [propName: string]: any
}
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: '请选择'
        }
    },

    setup(props: itemParams, ctx: itemParams) {
        let id = ref('selectTree' + (Math.floor((Math.random() * 10000) + 1)))
        let selectList = ref<Array<itemParams>>([{
            value: "",
            label: ""
        }])//下拉框列表
        let chooseTreeNodeArray = ref<Array<itemParams>>([])//节点选择列表
        let resultObj = ref<Array<itemParams>>([])     //下拉框选择列表
        //Tree节点选中或取消选中
        watch(
            () => [...chooseTreeNodeArray.value],
            () => {
                if (!props.multiple && chooseTreeNodeArray.value && chooseTreeNodeArray.value.length > 1) {
                    let lastItem = chooseTreeNodeArray.value[chooseTreeNodeArray.value.length - 1];
                    chooseTreeNodeArray.value = [lastItem];
                }
                setTreeCheckNode()
            })
        //有默认值
        watch(
            () => [...props.defaultArray],
            () => {
                chooseTreeNodeArray.value = [];
                if (props.defaultArray && props.defaultArray.length > 0) {
                    props.defaultArray.forEach((item:any) => {
                        if (item != '') {
                            if (props.multiple) {
                                chooseTreeNodeArray.value.push(item)
                            } else {
                                chooseTreeNodeArray.value = [item];
                            }
                        }
                    })
                }
                setTreeCheckNode();
            })

        watch(
            () => [...resultObj.value],
            () => {
                let resultStr = ref("");
                if (resultObj.value && resultObj.value.length > 0) {
                    if (props.multiple) {
                        let newarr = Array.from(new Set(resultObj.value)) //数组去重
                        resultStr.value = newarr.toString();
                    } else {
                        resultStr.value = resultObj.value[0].toString();
                    }
                }
                ctx.emit('getChild', resultStr);
            })

        //清空数据
        let clearData = () => {
            selectList.value = [{
                value: "",
                label: ""
            }];
            chooseTreeNodeArray.value = [];
            resultObj.value = [];
        }
        //设置下拉框选择
        let setTreeCheckNode = () => {
            selectList.value = [];
            resultObj.value = [];
            let nodes = findTreeNode(props.treeData);
            if (chooseTreeNodeArray.value.length > 0 && nodes && nodes.value.length > 0) {
                chooseTreeNodeArray.value.forEach(id => {
                    nodes.value.forEach((item) => {
                        if (item.value == id) {
                            selectList.value.push({
                                value: item.value,
                                label: item.label
                            });
                            if (props.multiple) {
                                resultObj.value.push(item.value);
                                console.log(214, resultObj.value)
                            } else {
                                resultObj.value = [item.value];
                            }
                        }
                    })
                })
            }
            if (selectList.value.length == 0) {
                selectList.value = [{
                    value: "",
                    label: ""
                }];
            }
        }
        //获取树中所有节点
        let findTreeNode = (tree: Array<any>) => {
            let temp = ref<Array<any>>([]);
            //获取子节点
            var getChildNodes = function (tree: Array<any>) {
                if (tree && tree.length > 0) {
                    for (var i = 0; i < tree.length; i++) {
                        temp.value.push({
                            label: tree[i][props.labelKey],
                            value: tree[i][props.nodeKey]
                        });
                        if (tree[i][props.childrenKey]) {
                            getChildNodes(tree[i][props.childrenKey]);
                        }
                    }
                }
            };
            getChildNodes(tree);
            return temp;
        }
        return {
            ...toRefs(props),
            id,
            selectList,
            chooseTreeNodeArray,
            resultObj,
            clearData,
            setTreeCheckNode,
            findTreeNode
        }
    }
}
</script>