<template>
    <div class="treeData" :style="{'height': height}">
        <el-input class="pb-[10px]" v-model="filterText" placeholder="输入关键字过滤" />
        <el-tree :data="data" :props="defaultProps" default-expand-all highlight-current
            :filter-node-method="filterNode" ref="tree" @node-click="funCurrentChange" :show-checkbox="showCheckbox"
            @check="funCheckChange" node-key="id" :expand-on-click-node="false" :current-node-key="''">
            <template #default="{ node, data }">
                <p v-if="node.level === 1" style="width: 100%;display: flex;justify-content: space-between;">
                    <span>{{ node.label }}</span>
                    <el-icon size="14" title="刷新">
                        <RefreshRight />
                    </el-icon>
                </p>
                <el-dropdown ref="dropdown1" v-else size="small" trigger="contextmenu" @command="funCommand"
                    style="margin-right: 30px">
                    <span class="el-dropdown-link text-[12px] flex items-center">
                        <el-icon class="mr-[4px] !text-[#E6A23C]">
                            <Folder v-if="!node.expanded || (node.isLeaf && !node.isCurrent)" />
                            <FolderOpened v-else />
                        </el-icon>
                        {{ node.label }}
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item class="text-[#409EFF]" v-if="dropdownMenu.includes('save')"
                                :command="{ type: 'save', data, node }">保存</el-dropdown-item>
                            <el-dropdown-item class="text-[#409EFF]"
                                v-if="data.childs && data.childs.length && dropdownMenu.includes('export')"
                                :command="{ type: 'export', data, node }">导出
                            </el-dropdown-item>
                            <el-dropdown-item class="text-[#F56C6C]" v-if="dropdownMenu.includes('delete')"
                                :command="{ type: 'delete', data, node }">删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </template>
        </el-tree>
    </div>
</template>
<script>
    import httpRequest from '@/utils/request.js'
    import {
        saveAs
    } from 'file-saver'
    import {
        apiGetExportMsg
    } from '@/api/gengra'
    import {
        DebugCameraPrimitive
    } from 'cesium'
    export default {
        props: {
            data: {
                type: Array,
                default: () => {
                    return [];
                },
            },
            height: {
                type: String,
                default: () => {
                    return '';
                },
            },
            type: {
                type: String,
                default: () => {
                    return 'wind';
                },
            },
            dropdownMenu: {
                type: Array,
                default: () => {
                    return ['export',
                        'delete',
                    ];
                },
            },
            showCheckbox: {
                type: Boolean,
                default: () => {
                    return false;
                },
            },
        },
        data() {
            return {
                filterText: '',
                defaultProps: {
                    children: 'children',
                    label: 'label'
                }
            }
        },
        watch: {
            filterText(val) {
                this.$refs.tree.filter(val);
            }
        },
        methods: {
            filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            },
            funCurrentChange(current, currentNode) {
                this.$emit("currentChange", {
                    current,
                    currentNode
                })
            },
            async funCommand({
                type,
                data,
                node
            }) {
                switch (type) {
                    case 'save':
                        /**该保存功能目前暂用于风电场, combine页 */
                        if (this.type !== 'wind') {
                            return false
                        }
                        ElMessageBox.confirm("确认保存当前节点的拟合功率?", "保存", {
                            confirmButtonText: "确认",
                            cancelButtonText: "取消",
                            type: "warning",
                        }).then(async () => {
                            let saveArr = [];
                            const repeatArr = (arr, saveArr) => {
                                for (const unit of arr) {
                                    if (unit.childs.length) {
                                        saveArr.push(...unit.childs.map((o) => o.id));
                                    } else if (unit.children.length) {
                                        repeatArr(unit.children, saveArr);
                                    }
                                }
                            };
                            if (data.childs.length) {
                                saveArr = data.childs.map((o) => o.id);
                            } else if (data.children.length) {
                                repeatArr(data.children, saveArr);
                            }
                            let res = {
                                code: 500
                            }
                            res = await httpRequest.get("/generat/power/fitting/curve/save", {
                                params: {
                                    ids: saveArr.join(",")
                                },
                            }); //删除当前节点

                            if (res.code === 200) {
                                ElMessage.success(res.msg);
                            }
                        });
                        break;
                    case "export":
                        ElMessageBox.confirm("确认导出当前节点的所有数据?", "导出", {
                            confirmButtonText: "确认",
                            cancelButtonText: "取消",
                            type: "warning",
                        }).then(() => {
                            const a = document.createElement("a");
                            let childs = []
                            childs = this.type === 'wind' ? data.childs.map((o) => o.id) : data.childs.map(
                                (o) => o.path)
                            const url = this.type === 'wind' ? '/data/option/download?ids=' :
                                '/export/files?filename='
                            a.href =
                                // config.baseURL + url + childs.join(",");
                                process.env.VUE_APP_GENERAT_URL + url + childs.join(",");
                            a.download = "";
                            a.target = '_blank'
                            a.click();

                            // let that = this
                            // let childs = []
                            // childs = this.type === 'wind' ? data.childs.map((o) => o.id) : data.childs.map(
                            //     (o) => o.path)
                            // let params = {
                            //     ids: childs.join(",")
                            // }
                            // apiGetExportMsg(params).then(datas => {
                            //     let blob = new Blob([datas], {
                            //         type: `application/vnd.ms-excel;charset=utf-8`
                            //     })
                            //     saveAs(blob)
                            // }).catch((r) => {
                            //     console.error(r)
                            // })
                        });
                        break;
                    case "delete":
                        ElMessageBox.confirm("确认删除当前节点的所有数据?", "删除", {
                            confirmButtonText: "确认",
                            cancelButtonText: "取消",
                            type: "warning",
                        }).then(async () => {
                            let deleteArr = [];
                            const repeatArr = (arr, deleteArr) => {
                                for (const unit of arr) {
                                    if (unit.childs.length) {
                                        deleteArr.push(...unit.childs.map((o) => this.type ===
                                            'wind' ? o.id : o.path));
                                    } else if (unit.children.length) {
                                        repeatArr(unit.children, deleteArr);
                                    }
                                }
                            };
                            if (data.childs.length) {
                                deleteArr = data.childs.map((o) => this.type === 'wind' ? o.id : o
                                    .path);
                            } else if (data.children.length) {
                                repeatArr(data.children, deleteArr);
                            }
                            let res = {
                                code: 500
                            }
                            if (this.type === 'wind') {
                                res = await httpRequest.get("/generat/data/option/delete", {
                                    params: {
                                        ids: deleteArr.join(",")
                                    },
                                }); //删除当前节点
                            } else {
                                res = await httpRequest.delete("/generat/delete/files", {
                                    data: {
                                        filename: deleteArr.join(",")
                                    },
                                }); //删除当前节点
                            }
                            if (res.code === 200) {
                                ElMessage.success(res.msg);
                                emits("refresh");
                            }
                        });

                        break;
                }
            },
            funCheckChange(current, checkedNodes) {
                this.$emit("checkChange", {
                    current,
                    checkedNodes
                })
            }
        },
    }
</script>
<style lang="less" scoped>
    .treeData {
        .el-input {
            margin-bottom: 5px;
        }

        .el-tree {
            background: #161f1e;
            color: #fff;

        }
    }
</style>