<template>
    <el-tabs class="multi_level_query_table" v-if="store.state.query_pick_pane.length > 0" v-model="activeName"
        @tab-click="handleClick" @tab-remove="removeTab">


        <el-tab-pane :label="store.state.query_pick_last_pane.name" name="second">
            <el-table :header-cell-style="{
                background: 'rgba(10, 25, 38, 0.6)',
                color: '#66b1ff',
                fontSize: '14px',
                fontFamily: 'Microsoft YaHei',
                fontWeight: '400',
            }" :data="store.state.query_pick_last_pane.value" style="width: 100%">
                <el-table-column show-overflow-tooltip="true" prop="filedZH" label="属性" width="140"
                    v-if="filedZH != '空间信息'">
                </el-table-column>
                <el-table-column show-overflow-tooltip="true" prop="data" label="属性值">
                </el-table-column>
            </el-table>
        </el-tab-pane>

        <el-tab-pane :closable="item.close" :label="item.name" :name="item.name"
            v-for="(item, index) in store.state.query_pick_pane" :key="index">

            <div v-if="item.name != '权属'">
                <el-table :data="tableData" style="width: 100%" :header-cell-style="{
                    background: 'rgba(10, 25, 38, 0.6)',
                    color: '#66b1ff',
                    fontSize: '14px',
                    fontFamily: 'Microsoft YaHei',
                    fontWeight: '400',
                }">
                    <el-table-column show-overflow-tooltip="true" width="150" v-for="header in headers" :key="header"
                        :label="header" :prop="header" v-if="header != '空间信息'">
                    </el-table-column>
                </el-table>
                <pie class="echart" unit="亩" :ref="`echartRef`"></pie>
            </div>
            <div v-else>
                <el-tabs @tab-click="handleClickQwnership">

                    <el-tab-pane v-for="(item, index) in qwnershipTabs" :key="index" :label="item.dataname"
                        :name="item.dataname">
                        <el-table :data="tableData_qwnership" style="width: 100%" :header-cell-style="{
                            background: 'rgba(10, 25, 38, 0.6)',
                            color: '#66b1ff',
                            fontSize: '14px',
                            fontFamily: 'Microsoft YaHei',
                            fontWeight: '400',
                        }">
                            <el-table-column show-overflow-tooltip="true" width="150" v-for="header in headers_qwnership"
                                :key="header" :label="header" :prop="header" v-if="header != '空间信息'">
                            </el-table-column>
                        </el-table>

                        <pie class="echart" unit="亩" :ref="`qwnership_pie`"></pie>

                    </el-tab-pane>
                </el-tabs>
            </div>

        </el-tab-pane>

        <el-tab-pane label="自定义" name="自定义">
            <!-- <el-input clearable v-model="state" @input="change_witch" class="search" placeholder="请输入内容"></el-input> -->
            <el-checkbox-group v-model="activecheckList">
                <el-checkbox :label="item.label" v-for="(item, index) in check_list" :key="index"
                    :disabled="item.ckeck"></el-checkbox>

            </el-checkbox-group>
            <div style="margin-bottom: 20px;">
                <el-button size="small" @click="addTab()">
                    添加
                </el-button>
            </div>
        </el-tab-pane>
    </el-tabs>
</template>

<script>
//这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
import { GetTabsData, GetTabsPane } from '@/api/cockpitNew'
import * as wellknown from "wellknown";
import * as turf from "@turf/turf";
import pie from "@/components/echartsTemplate/pie.vue";

let manager_multi_level_query = null;
let pick_entity = null;

let manager_multi_level_vector = null;
let query_click_by_iserver = null;

export default {
    components: { pie },
    data() {
        return {
            activeName: 'second',
            activeNameQwnership: 'Qwnership',
            handler_multi_level_query: null,
            manager_multi_level_query: null,
            manager_multi_level_vector: null,
            pick_entity: null,
            pick_entity_geo: null,
            eclickname: '',
            echartList: {},
            tabIndex: 2,
            state: '',
            activecheckList: [],
            check_list: [{ label: '三调', ckeck: true }, { label: '权属', ckeck: true }, { label: '农用' }, { label: '上映' }],
            active_tabs_table: [],
            rawData: [],
            headers: [], // 用于存储所有可能的 filedZH 值 
            qwnershipTabs: [],
            rawData_qwnership: [],
            headers_qwnership: [],
        };
    },
    //监听属性 类似于data概念
    computed: {
        tableData() {
            // 首次加载时确定所有可能的 filedZH 值  
            // if (!this.headers.length) {
            this.headers = [];
            this.rawData.forEach(item => {
                item.forEach(field => {
                    if (!this.headers.includes(field.filedZH)) {
                        this.headers.push(field.filedZH);
                    }
                });
            });
            // }

            // 转换 rawData 为适合 el-table 使用的格式  
            return this.rawData.map(item => {
                // 创建一个包含所有 headers 字段的对象  
                const row = {};
                this.headers.forEach(header => {
                    // 查找当前数据项中对应 filedZH 的 data 值  
                    const field = item.find(f => f.filedZH === header);
                    row[header] = field ? field.data : ''; // 如果没有找到,则使用空字符串  
                });
                return row;
            });
        },
        tableData_qwnership() {
            // 首次加载时确定所有可能的 filedZH 值  
            // if (!this.headers.length) {
            this.headers_qwnership = [];
            this.rawData_qwnership.forEach(item => {
                item.forEach(field => {
                    if (!this.headers_qwnership.includes(field.filedZH)) {
                        this.headers_qwnership.push(field.filedZH);
                    }
                });
            });
            // }

            // 转换 rawData 为适合 el-table 使用的格式  
            return this.rawData_qwnership.map(item => {
                // 创建一个包含所有 headers 字段的对象  
                const row = {};
                this.headers_qwnership.forEach(header => {
                    // 查找当前数据项中对应 filedZH 的 data 值  
                    const field = item.find(f => f.filedZH === header);
                    row[header] = field ? field.data : ''; // 如果没有找到,则使用空字符串  
                });
                return row;
            });
        },
    },
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
        change_witch() {

        },
        removeTab(targetName) {
            let tabs = store.state.query_pick_pane;
            let activeName = this.activeName;
            if (activeName === targetName) {
                tabs.forEach((tab, index) => {
                    if (tab.name === targetName) {
                        let nextTab = tabs[index + 1] || tabs[index - 1];
                        if (nextTab) {
                            activeName = nextTab.name;
                        }
                    }
                });
            }

            this.activeName = activeName;
            store.state.query_pick_pane = tabs.filter(tab => tab.name !== targetName);
        },
        addTab() {
            // let newTabName = ++this.tabIndex + '';
            // store.state.query_pick_pane.push({

            //     name: newTabName,
            //     value: [1, 2, 3, 4],// element.data
            //     close: 'closable'

            // });
            // this.activeName = newTabName;


            this.activecheckList.forEach((res) => {

                store.state.query_pick_pane.push({

                    name: res,
                    value: [1, 2, 3, 4],// element.data
                    close: 'closable'

                });

                this.activeName = res;

            })
        },

        go(e) {
            const that = this;
            e.forEach(element => {
                if (element.filed == "geom") {
                    this.gogeojson(element.data)
                }
            });
        },
        gogeojson(data) {
            let geojson = wellknown.parse(data);

            const twoDArray = geojson.coordinates[0];
            const oneDArray = twoDArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
            this.pick_entity_geo = oneDArray;

            pick_entity.entities.add({
                polygon: {
                    // 获取指定属性(positions,holes(图形内需要挖空的区域))
                    hierarchy: {
                        positions: Cesium.Cartesian3.fromDegreesArray(oneDArray),
                    },
                    // 边框
                    outline: true,
                    // 边框颜色
                    outlineColor: Cesium.Color.RED,
                    // 边框尺寸
                    outlineWidth: 2,
                    // 填充的颜色,withAlpha透明度
                    material: Cesium.Color.GREEN.withAlpha(0),
                    // 是否被提供的材质填充
                    fill: true,
                    // 恒定高度
                    height: 1.1,
                    // 显示在距相机的距离处的属性,多少区间内是可以显示的
                    // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(1000, 10000000),
                    // 是否显示
                    show: true,
                    // 顺序,仅当`clampToGround`为true并且支持地形上的折线时才有效。
                    zIndex: 10
                }
            });

            let flag = true;
            let time = setInterval(() => {
                flag = !flag
                this.switch_show(flag);
            }, 500);
            setTimeout(() => {
                clearInterval(time);
                pick_entity.entities.values.forEach((res) => {

                    pick_entity.entities.remove(res);

                })
            }, 6000)


            // 注意:polygon首尾坐标要一致
            var polygon = turf.polygon([geojson.coordinates[0]]);

            var centroid = turf.centroid(polygon).geometry.coordinates;

            viewer.camera.flyTo({
                duration: 1,

                destination: Cesium.Cartesian3.fromDegrees(centroid[0], centroid[1], 3000),
                // destination: {
                //     x: -6283267.004204832,
                //     y: 28123682.896774407,
                //     z: 23709669.98539126
                // },
                orientation: {
                    heading: 6.149339593573709,
                    pitch: -1.539825618847483,
                    roll: 0
                },
            });
        },
        clear_data() {
            const that = this;
            store.state.query_pick_last_pane = null;
            store.state.query_pick_pane = [];

            this.remove_query_click_by_iserver();

        },
        remove_query_click_by_iserver() {
            for (var i = 0; i < 10; i++) {
                query_click_by_iserver.entities.values.forEach((res) => {

                    query_click_by_iserver.entities.remove(res);

                })
            }
        },
        init_handler() {


            const that = this;

            that.clear_data();
            if (that.handler_multi_level_query == null) {
                that.handler_multi_level_query = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
            }
            that.handler_multi_level_query.setInputAction(async event => {
                let pickObj = viewer.scene.pick(event.position);
                var position = viewer.scene.pickPosition(event.position);

                if (!position)//点击到地球之外
                    return false;
                var cartographic = Cesium.Cartographic.fromCartesian(position);


                let longitude = Cesium.Math.toDegrees(cartographic.longitude);
                let latitude = Cesium.Math.toDegrees(cartographic.latitude);
                let height = cartographic.height;
                let heading = viewer.scene.camera.heading;
                let pitch = viewer.scene.camera.pitch;

                if (!position) {
                    position = Cesium.Cartesian3.fromDegrees(0, 0, 0);
                }


                const geojsonPoint = {
                    "type": "Point",
                    "coordinates": [longitude, latitude] // 注意经纬度顺序  
                };

                const wkt = wellknown.stringify(geojsonPoint);
                // let id = store.state.vectorlayerlist[store.state.vectorlayerlist.length - 1].id
                let obj = {
                    defaultType: null,
                    // layerId: id
                }
                let data = await GetTabsData(obj);

                for (let index = 0; index < data.data.length; index++) {
                    const element = data.data[index];
                    let tableId = element.tableId;
                    let pane_obj = {
                        // sourcePointWkt: wkt,
                        // sourceLayerId: id,

                        sourcePointWkt: "POINT(109.5139541 18.3146153)",
                        sourceLayerId: "dd699f839bc04969ae2dc2e1964d0ad1",

                        sourceLayerType: '0',
                        queryTableId: tableId,

                    }
                    if (index == 0) {
                        let res = await GetTabsPane(pane_obj);

                        let filteredData = res.data.data[0].filter((res) => {
                            return res.filed != 'geom'
                        })

                        store.state.query_pick_last_pane = {
                            name: element.name,
                            value: filteredData,
                        };

                    } else {
                        let res = await GetTabsPane(pane_obj);

                        store.state.query_pick_pane.push({
                            name: element.name,
                            value: res,
                            close: 'closable'
                        });
                    }
                }

                this.highlightResults(longitude, latitude);

                that.handler_multi_level_query.destroy();
                that.handler_multi_level_query = null;
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);


        },
        handleClick(tab, event) {
            let index = Number(tab.index) - 1

            if (tab.name == '权属') {
                this.qwnershipTabsFun();
            } else {
                if (tab.closable == true) {
                    store.state.query_pick_pane.forEach((res) => {
                        if (res.name == tab.name) {
                            let data = [];

                            this.active_tabs_table = res.value.data.data;
                            this.rawData = res.value.data.data
                            res.value.data.datalist.forEach((res) => {
                                data.push({
                                    name: res.groupvalue,
                                    value: res.sumvalue
                                })
                            })
                            this.setEchart(data, "vertical", index);
                        }
                    })
                }
            }


        },
        handleClickQwnership(tab, event) {
            let index = 0;
            this.qwnershipTabs.forEach((res) => {
                if (res.dataname == tab.name) {
                    this.rawData_qwnership = res.data
                    let data = [];
                    res.datalist.forEach((res) => {
                        data.push({
                            name: res.groupvalue,
                            value: res.sumvalue
                        })
                    })
                    this.setEchart_qwnership(data, "vertical", index);
                    index++;
                }
            })
        },
        // 权属tabs
        qwnershipTabsFun() {
            store.state.query_pick_pane.forEach((res) => {
                if (res.name == '权属') {
                    this.qwnershipTabs = res.value.data.child;
                    // this.activeNameQwnership = this.qwnershipTabs[0].dataname
                }
            })


        },
        setEchart_qwnership(data, type, index) {
            this.$nextTick(() => {
                let max = index == 0 ? 3 : 10
                let legend_right = index == 0 ? "2%" : "10%"
                this.$refs.qwnership_pie[index].setOptions({ data, type, max, legend_right });
            });
        },
        setEchart(data, type, index) {
            this.$nextTick(() => {
                let max = index == 0 ? 3 : 10
                let legend_right = index == 0 ? "2%" : "10%"
                this.$refs.echartRef[index].setOptions({ data, type, max, legend_right });
            });
        },
        calcIserverURI(url) {
            let uriArr = url.split("/");
            uriArr[5] = uriArr[5].replace("map-", "data-");
            uriArr[7] = "data";
            uriArr[8] = "featureResults.rjson?returnContent=true";
            return uriArr.join("/");
        },
        convertCoordinates(coordArray) {
            return coordArray.map(coord => [coord.x, coord.y]);
        },
        isArray2D(arr) {
            // 首先检查arr是否是数组
            if (!Array.isArray(arr)) {
                return false;
            }

            // 检查数组中的每个元素是否也是数组
            for (let i = 0; i < arr.length; i++) {
                if (!Array.isArray(arr[i])) {
                    return false;
                }
            }

            // 如果所有元素都是数组,那么arr是二维数组
            return true;
        },
        async highlightResults(longitude, latitude) {
            // 高亮结果
            let queryByIDParameters = {
                getFeatureMode: "BUFFER",
                // getFeatureMode: "SPATIAL",
                spatialQueryMode: "INTERSECT",
                datasetNames: store.state.vectorlayerlist[store.state.vectorlayerlist.length - 1].source.split(","),
                geometry: {
                    parts: [1],
                    points: [{ y: latitude, x: longitude }],
                    type: "POINT",
                },
                bufferDistance: 0.00005,
                hasGeometry: true,
            };



            let response = await axios.post(this.calcIserverURI(store.state.vectorlayerlist[store.state.vectorlayerlist.length - 1].url), queryByIDParameters);


            const outputCoords = this.convertCoordinates(response.data.features[0].geometry.points);
            outputCoords.push(outputCoords[0])

            let f = { "type": "Polygon", "coordinates": [outputCoords] };
            let result = turf.buffer(f, 1 / 99999, {
                units: "kilometers",
            });
            let positions = [];
            const twoDArray = result.geometry.coordinates[0];
            const oneDArray = twoDArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);

            positions = oneDArray;


            if (this.isArray2D(oneDArray)) {
                const oneDArray2 = oneDArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
                positions = oneDArray2;

            } else {

            }

            query_click_by_iserver.entities.add({
                polygon: {
                    // 获取指定属性(positions,holes(图形内需要挖空的区域))
                    hierarchy: {
                        positions: Cesium.Cartesian3.fromDegreesArray(positions)
                    },
                    // 边框
                    outline: false,
                    // 边框颜色
                    outlineColor: Cesium.Color.RED,
                    // 边框尺寸
                    outlineWidth: 10,
                    // 填充的颜色,withAlpha透明度
                    material: Cesium.Color.RED,

                    // 是否被提供的材质填充
                    fill: true,
                    // 恒定高度
                    height: 1.1,
                    // 显示在距相机的距离处的属性,多少区间内是可以显示的
                    // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(1000, 10000000),
                    // 是否显示
                    show: true,
                    // 顺序,仅当`clampToGround`为true并且支持地形上的折线时才有效。
                    zIndex: 10
                }
            });


        },

    },
    beforeCreate() { }, //生命周期 - 创建之前
    created() { }, //生命周期 - 创建完成(可以访问当前this实例)
    beforeMount() { }, //生命周期 - 挂载之前
    mounted() {
        const that = this;
        this.$nextTick(() => {
            query_click_by_iserver = new Cesium.CustomDataSource("query_click_by_iserver");
            viewer.dataSources.add(query_click_by_iserver);
        })

    }, //生命周期 - 挂在完成
    beforeUpdate() { }, //生命周期 - 更新之前
    updated() { }, //生命周期 - 更新之后
    beforeDestroy() { }, //生命周期 - 销毁之前
    destroy() { },//生命周期 - 销毁完成
    activated() { }, //若组件实例是 <KeepAlive> 缓存树的一部分,当组件被插入到 DOM 中时调用。
    deactivated() { } //若组件实例是 <KeepAlive> 缓存树的一部分,当组件从 DOM 中被移除时调用。
};
</script>
<style lang="scss" scoped>
.el-collapse {
    // width: 95%;
    border: none;
    background-color: transparent !important;
}

.el-scrollbar {
    border: 1px solid #0f7ac8 !important;
    // padding: 0 10px;
}

.el-collapse-item__header {
    // border-bottom: 1px solid rgba(102, 126, 143, 0.747);
    background-color: transparent !important;
    color: rgb(217, 237, 254) !important;
    border-color: transparent !important;
}

.el-collapse-item__wrap {
    background-color: transparent !important;
    border-color: transparent !important;
}

.el-collapse-item__content {
    // background-color: rgba(255, 192, 203, 0.425) !important;
    background-color: transparent !important;
    color: rgb(217, 237, 254) !important;
}
</style>
<style lang="scss" scoped>
.echart {
    width: 300px;
    height: 420px;
}

.echart1 {
    height: 280px;
}

.multi_level_query_table {
    position: absolute;
    top: 7rem;
    width: 19rem;


}

/* 去掉tabs标签栏下的下划线 */
::v-deep .el-tabs__nav-wrap::after {
    position: static !important;
    /* background-color: #fff; */
}

/* 下划线切换高亮 */
::v-deep .el-tabs__active-bar {
    background-color: #30fdff;
}

::v-deep .el-collapse-item__header {
    color: #64daff !important;
    font-weight: 600;
}


.el-tab-pane {
    height: 33rem;
    overflow: auto;
}


.list_vector_multi {
    background-image: url("/static/images/ghzc/内容框.png");

    width: 18rem;
    border-top: 1px solid #CCC;
    font-size: 14px;
    padding: 0.1rem 0rem 0.1rem 0rem;
    border-left: 1px solid #CCC;

    border-right: 1px solid #CCC;

    // border-bottom:1px solid #CCC ;
}

.list_vector_multi:last-child {

    border-bottom: 1px solid #CCC;
}

.filed_box {
    display: inline-block;
}

.el-checkbox {
    color: white;
}

.is-disabled {
    display: inline;
}


/deep/ .el-table tr {
    background: rgba(10, 25, 38, 0.5) !important;
}

/deep/ .el-table td.el-table__cell,
.el-table th.el-table__cell.is-leaf {
    background: rgba(10, 25, 38, 0.5) !important;

    border-bottom: 0px solid #ebeef5;
}

.el-table {
    color: #fff;
    background: rgba(10, 25, 38, 0.5) !important;
}

/deep/ .el-table__fixed-right::before,
.el-table__fixed::before {
    background: rgba(10, 25, 38, 0.9) !important;
}

/deep/ .el-table__fixed-right-patch {
    background: rgba(10, 25, 38, 0.9) !important;
}

/deep/ .el-table--border::after,
.el-table--group::after,
.el-table::before {
    background: rgba(10, 25, 38, 0) !important;
}

.content_item {
    color: #30fdff;

    .item_field {
        color: #30fdff;

    }
}
</style>