<template>
    <div class="treeData" :style="{'height': height}">
        <div class="treeSeach">
            <el-input v-model="filterText" style="height: 30px" placeholder="输入关键字过滤" :suffix-icon="Search" />
            <div class="treeShuax" @click="refreshFn">
                <img :src="tree_shuaxing">
            </div>
        </div>
        <div class="treeMain">
            <div class="treeMainTit">
                <span>数据</span>
            </div>
            <!-- <div v-for="node in data" :key="node.id" class="treeMainMsg">
                <span>{{node.label}}</span>
                <tree-node :node="node.children" :data="data" :show-checkbox="showCheckbox"
                    :dropdownMenu="dropdownMenu">
                </tree-node>
            </div> -->
            <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 }">
                    <el-dropdown ref="dropdown1" size="small" trigger="contextmenu" @command="funCommand"
                        style="margin-right: 30px"
                        :class="!node.expanded || (node.isLeaf && !node.isCurrent) ? '' : 'eldropdownCla'">
                        <span class="el-dropdown-link">
                            {{ 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>
                <template #empty>
                    <div class="nodata">
                        <img :src="nodata" alt="">
                        <p class="nodataText">暂无数据，敬请期待</p>
                    </div>
                </template>
            </el-tree>
        </div>
    </div>
</template>
<script>
    import httpRequest from '@/utils/request.js'
    import tree_shuaxing from '@/assets/menuImg/tree_shuaxing.png'
    import nodata from '@/assets/images/noData.png'
    import TreeNode from './treeStyle.vue'
    import {
        Search
    } from '@element-plus/icons-vue'
    import {
        saveAs
    } from 'file-saver'
    import {
        apiGetExportMsg
    } from '@/api/gengra'
    import {
        DebugCameraPrimitive
    } from 'cesium'
    export default {
        components: {
            TreeNode
        },
        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: '',
                Search: Search,
                nodata: nodata,
                tree_shuaxing: tree_shuaxing,
                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;
            },
            refreshFn() {
                this.$emit("refresh")
            },
            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("/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("/data/option/delete", {
                                    params: {
                                        ids: deleteArr.join(",")
                                    },
                                }); //删除当前节点
                            } else {
                                res = await httpRequest.delete("/delete/files", {
                                    data: {
                                        filename: deleteArr.join(",")
                                    },
                                }); //删除当前节点
                            }
                            if (res.code === 200) {
                                ElMessage.success(res.msg);
                                this.$emit("refresh");
                            }
                        });

                        break;
                }
            },
            funCheckChange(current, checkedNodes) {
                this.$emit("checkChange", {
                    current,
                    checkedNodes
                })
            }
        },
    }
</script>
<style lang="less" scoped>
    .treeData {
        overflow-y: auto;

        .treeSeach {
            width: 100%;
            display: flex;
            margin-bottom: 5px;

            .treeShuax {
                cursor: pointer;
                margin-left: 5px;
                height: 30px;
                width: 30px;
                background: #5473E8;
                border-radius: 2px;
                text-align: center;

                img {
                    width: 25px;
                    height: 25px;

                    position: relative;
                    top: 2px;
                    left: -1px;
                }
            }

        }

        .treeMain {
            .treeMainTit {
                width: calc(100% - 10px);
                height: 22px;
                background: #1E3F9A;
                color: #fff;
                font-size: 12px;
                padding: 8px 0 0 10px;
            }

            .treeMainMsg {
                span {
                    font-family: Microsoft YaHei;
                    font-weight: 400;
                    font-size: 14px;
                    color: #121212;
                    line-height: 30px;
                }
            }

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

                .is-current {
                    width: 100%;
                    height: 20px;
                    background: #fff !important;
                }

                .el-tree__empty-block {
                    img {
                        margin-top: 20px;
                    }

                    .nodataText {
                        line-height: 50px;
                        font-size: 14px;
                        color: #8C8E91;
                    }
                }

            }
        }

    }
</style>