<template>
    <div class="adm-space">
        <statistics :statistics-msg="statisticsMsg"/>
        <el-divider class="small-divider"></el-divider>
        <div class="tabs">
            <el-tabs v-model="activeName" type="card" @tab-click="tabChange">
                <el-tab-pane label="列表" name="table"></el-tab-pane>
                <el-tab-pane label="平面图" name="picture"></el-tab-pane>
            </el-tabs>
            <div class="tab-content">
                <div class="search" :class="{ 'borderBottom': activeName==='picture' }">
                    <el-cascader clearable ref="floorCascader" placeholder="请选择建筑楼层" :options="options"
                                 v-model="building" filterable size="small"
                                 @change="changeCascader" style="margin-right: 12px"
                                 v-if="activeName==='table'"></el-cascader>
                    <admSearch @SearchValue="searchValue" class="item" v-if="activeName==='table'"/>

                    <el-cascader clearable ref="graphCascader" placeholder="请选择建筑楼层" :options="graphOptions"
                                 v-model="graphBuilding" filterable
                                 size="small" @change="changeGraphCascader" style="margin-right: 12px"
                                 v-if="activeName==='picture'" :props="graphProps">
                    </el-cascader>
                    <el-cascader v-model="zoneTypeVal" :options="zoneTypeOption" @change="changeZoneType"
                                 placeholder="请选择分区" class="item"
                                 v-if="activeName==='picture'"></el-cascader>
                </div>
                <div v-if="activeName==='table'" v-loading="loading" style="height: calc(100% - 100px);padding: 0 12px">
                    <template style="height: 100%;" v-if="building.length > 0">
                        <admMultiTable
                            @handleCurrentEdit="handleCurrentEdit"
                            :currentHeader="currentHeader"
                            :headersStage="headersStage"
                            :tableData="tableData"/>
                        <Pagination v-if="tableData.length > 0" :paginationList="paginationList"
                                    @handleCurrentChange="handleCurrentChange"
                                    @handleSizeChange="handleSizeChange"/>
                    </template>
                    <div v-else class="void align">
                        <svg-icon name="void" :width="String(120)" :height="String(123)"/>
                        <p class="void-title">暂无内容</p>
                        <p class="void-tips">可点击左上角选择设备类型</p>
                    </div>
                </div>
                <div class="graph" v-if="activeName==='picture'">
                    <spaceGraph ref="spaceGraph"/>
                </div>
            </div>
        </div>
        <el-dialog title="编辑空间信息" :visible.sync="dialogVisible" @close="close">
            <baseDataForm :objectHeaders="spaceHeaders"
                          :currRowContent="currRowContent"
                          ref="baseDataForm"/>
            <span slot="footer" class="dialog-footer">
                 <el-button type="primary" @click="handleDataForm">完成</el-button>
                 <el-button @click="dialogVisible = false">取消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { AdmMultiTable, AdmSearch, baseDataForm, Pagination, Statistics } from "../components/index";
import spaceGraph from "./components/spaceGraph.vue";
import { buildingQuery, dictQuery, floorQuery, queryCountSpace, queryZone, updateZone } from "@/api/datacenter";
import tools from "@/utils/maintain";
import { BeatchQueryParam } from "@/api/equipComponent";
import { UserModule } from "@/store/modules/user";

@Component({
    name: "adm-space",
    components: {
        Statistics,
        AdmSearch,
        AdmMultiTable,
        spaceGraph,
        Pagination,
        baseDataForm
    },
})
export default class spaceIndex extends Vue {
    // loading
    loading = false;
    private statisticsMsg = {
        title: "全部空间",
        total: 93640,
    };
    currentHeader = "租赁系统";
    activeName = "table";
    building = ["all"];

    zoneTypeVal = ["GeneralZone"];
    // 分页
    private paginationList = {
        page: 1,
        size: 50,
        sizes: [10, 30, 50, 100, 150, 200],
        total: 0,
    };
    options = [];
    graphOptions = [];
    zoneTypeOption = [
        {
            value: "GeneralZone",
            label: "功能分区",
        },
        {
            value: "Zone",
            label: "业务分区",
            children: [
                {
                    value: "FireZone",
                    label: "防火空间",
                },
                {
                    value: "PowerSupplyZone",
                    label: "供电空间",
                },
            ],
        },
    ];

    // 信息点集合（表头）
    all = [];
    codeToDataSource = {};
    tableData = [];
    // 表头阶段信息结合
    headersStage = {};
    // 搜索框字段
    inputSearch = "";
    // 楼层映射
    floorToMap = {};
    //
    graphProps = {
        label: "localName",
        value: "id",
        children: "floor",
    };
    graphBuilding = [];
    spaceHeaders = {}
    // 当前行数据
    currRowContent = {}
    // 弹窗开关
    dialogVisible = false
    //
    // 项目id
    private get projectId(): string {
        return UserModule.projectId;
    }

    created() {
        this.getData();
        this.dataCount();
        // 默认显示全部建筑信息
        this.changeCascader();
    }

    //查询统计数量
    dataCount() {
        queryCountSpace({}).then((res) => {
            this.statisticsMsg.total = res.count;
        });
    }

    //获取楼层数据
    getData() {
        let data,
            buildParams = {
                pageNumber: 1,
                pageSize: 1000,
                orders: "localName asc",
                projection: ["id", "localName"],
            },
            floorParams = {
                orders: "floorSequenceId desc",
                pageNumber: 1,
                pageSize: 1000,
            };
        let promise1 = new Promise((resolve) => {
            buildingQuery(buildParams).then((res) => {
                resolve(res);
            });
        });
        let promise2 = new Promise((resolve) => {
            floorQuery(floorParams).then((res) => {
                resolve(res);
            });
        });
        Promise.all([promise1, promise2]).then((values) => {
            let buildData = values[0].content,
                floorData = values[1].content;
            this.floorToMap = {};
            data = buildData.map((build) => {
                return {
                    value: build.id,
                    label: build.localName,
                };
            });
            data.unshift(
                {
                    value: "all",
                    label: "全部",
                },
                {
                    value: "noKnow",
                    label: "未明确建筑",
                }
            );
            data.forEach((build) => {
                floorData.forEach((floor) => {
                    this.floorToMap[floor.id] = floor;
                    if (
                        build.value == floor.buildingId &&
                        floor.id &&
                        floor.localName
                    ) {
                        if (build.children) {
                            build.children.push({
                                value: floor.id,
                                label: floor.localName,
                                FloorSequenceID: floor.floorSequenceId,
                                infos: floor.infos || {},
                                outline: floor.outline || null,
                            });
                        } else {
                            build.children = [];
                            build.children.push(
                                {
                                    value: "all",
                                    label: "全部",
                                },
                                {
                                    value: "noKnow",
                                    label: "未明确楼层",
                                },
                                {
                                    value: floor.id,
                                    label: floor.localName,
                                    FloorSequenceID: floor.floorSequenceId,
                                    infos: floor.infos || {},
                                    outline: floor.outline || null,
                                }
                            );
                        }
                    }
                });
            });
            this.options = data;
            let arr = data.filter((item) => item.children);
            console.log(arr);
        });

        const pa = {
            pageSize: 1000,
            orders: "localName asc",
            cascade: [{ name: "floor", orders: "floorSequenceId desc" }],
        };
        buildingQuery(pa).then((res) => {
            try {
                this.graphOptions = res.content.map((t) => {
                    if (!t.floor) {
                        t.floor = [];
                    }
                    return t;
                });
            } catch (err) {
                this.graphOptions = [];
            }
            if (this.graphOptions.length) {
                if (this.graphOptions[0].floor.length) {
                    this.graphBuilding = [
                        this.graphOptions[0].id,
                        this.graphOptions[0].floor[0].id,
                    ];
                }
            }
        });
    }
    //改变楼层
    changeCascader(value) {
        //todo delete
        // if (value && value.length > 0  && this.building[0] != 'all') {
        //     this.buildingLabel = this.$refs['floorCascader'].getCheckedNodes()[0].pathLabels
        // }
        if (this.building.length > 0) {
            this.loading = true;
            let param = {
                type: "GeneralZone",
                orders: "sort asc, name desc",
                pageNumber: 1,
                pageSize: 1000,
            };
            let param2 = {
                // 级联查建筑楼层信息
                cascade: [
                    { name: "building" },
                    { name: "floor", orders: "floorSequenceId desc" },
                ],
                zoneType: "GeneralZone",
                pageNumber: this.paginationList.page,
                pageSize: this.paginationList.size,
                orders: "createTime asc, localName asc, localId desc, id asc",
            };

            if (this.building.length === 1) {
                param2.filters = "";
                switch (this.building[0]) {
                    case "noKnow":
                        param2.filters = `buildingId='isnull'`;
                        break;
                    case "all":
                        delete param2.filters;

                        break;
                }
            } else if (this.building.length === 2) {
                switch (this.building[1]) {
                    case "noKnow":
                        param2.filters = `buildingId='${this.building[0]}';floorId='isnull'`;

                        break;
                    case "all":
                        param2.filters = `buildingId='${this.building[0]}'`;
                        break;
                    default:
                        param2.filters = `buildingId='${this.building[0]}';floorId='${this.building[1]}'`;
                }
            }

            let promise = new Promise((resolve) => {
                dictQuery(param).then((res) => {
                    resolve(res);
                });
            });
            let promise2 = new Promise((resolve) => {
                queryZone(param2).then((res) => {
                    resolve(res);
                });
            });
            Promise.all([promise, promise2]).then((res) => {
                let tableData = [];
                this.loading = false;
                // 类型下信息点,重组数据
                let basicInfos = [],
                    dictStages = [];
                this.all = res[0].content;
                res[0].content.forEach((item) => {
                    let i = ["localName", "localId", "building", "floor"];
                    if (i.includes(item.path)) {
                        basicInfos.push(item);
                    } else {
                        dictStages.push(item);
                    }
                });
                dictStages.map((val, index) => {
                    if (val.path == "outline") {
                        dictStages.splice(index, 1);
                    }
                    return val;
                });
                basicInfos.map((item) => {
                    if (item.path == "building") {
                        item.path = "buildingSign";
                    }
                    if (item.path == "floor") {
                        item.path = "floorSign";
                    }
                    return item;
                });

                this.headersStage = {
                    basicInfos: {
                        name: "模型解析",
                        data: basicInfos,
                    },
                    dictStages: {
                        name: "租赁系统",
                        data: dictStages,
                    },
                };
                this.paginationList.total = res[1].total;
                tableData = res[1].content; // 主体数据
                // 处理 outline BIM模型中轮廓坐标 展示
                // 添加建筑，楼层展示（从下拉框获取）
                this.tableData = tableData.map((item) => {
                    if (item.building) {
                        item.buildingSign = item.building.localName;
                    }
                    if (item.floor) {
                        item.floorSign = item.floor.localName;
                    }
                    // 删除轮廓线
                    if (item.outline) {
                        delete item.outline;
                    }
                    // const category = ['ENUM', 'MENUM', 'BOOLEAN']
                    // if (item.category == 'STATIC' && item.dataType.includes(category) && item.dataSource) {
                    //     console.log(item, item.path)
                    // }

                    // item = {
                    //     ...item,
                    //     outline: JSON.stringify(item.outline),
                    // };

                    return item;
                });
                //  列表信息展示,获取动态数据
                this.codeToDataSource = {};
                this.all.forEach((item) => {
                    const category = ['ENUM', 'MENUM', 'BOOLEAN']
                    console.log(item.category,item.dataType)
                    if (item.category == 'STATIC' && item.dataType.includes(category) && item.dataSource) {
                        console.log(21)
                    }
                    if (item.dataSource) {
                        try {
                            this.codeToDataSource[item.code] = {};
                            item.dataSource.forEach((dic) => {
                                this.codeToDataSource[item.code][dic.code] =
                                    dic.name;
                            });
                        } catch (e) {
                            console.log(e);
                        }
                    }
                    console.log(this.codeToDataSource,' this.codeToDataSource')
                });
                this.getBatch(this.tableData);
            });
        } else {
            console.log("void");
        }
    }
    // 图建筑楼层修改
    changeGraphCascader(value) {
        this.toGraph();
    }
    // 动态信息点
    getBatch(data) {
        let param = {
            groupCode: "WD",
            appId: "datacenter",
            projectId: this.projectId,
            data: [],
        };
        this.all.forEach((head) => {
            if (head.category != "STATIC") {
                data.forEach((item) => {
                    let cur = tools.dataForKey(item, head.path);
                    if (cur) {
                        param.data.push({
                            objectId: item.id,
                            infoCode: head.code,
                        });
                    }
                });
            }
        });
        if (param.data.length) {
            BeatchQueryParam(param).then((res) => {
                this.tableData = data.map((item) => {
                    res.data.map((child) => {
                        if (item.id == child.objectId) {
                            if (!!child.data || child.data == 0) {
                                this.all.map((head) => {
                                    if (head.code == child.infoCode) {
                                        let contentVal = child.data;
                                        if (this.codeToDataSource[child.infoCode]) {
                                            contentVal = this.codeToDataSource[child.infoCode][child.data];
                                        }
                                        tools.setDataForKey(
                                            item,
                                            head.path,
                                            contentVal
                                        );
                                    }
                                });
                            } else {
                                this.all.map((head) => {
                                    if (head.code == child.infoCode) {
                                        tools.setDataForKey(
                                            item,
                                            head.path,
                                            child.error
                                        );
                                    }
                                });
                            }
                        }
                    });
                    return item;
                });
            });
        }
    }

    // 修改分区类型
    changeZoneType(val) {
        this.toGraph();
    }

    // 当前分页
    handleCurrentChange(val: number) {
        this.paginationList.page = val;
        this.changeCascader();
    }

    // close
    close() {
        // this.next = true;
    }

    // 添加/编辑 事件处理
    handleDataForm() {
        let from = tools.formatData(this.$refs.baseDataForm.form)
        let param = {
            content: [from]
        }
        updateZone(param).then(res => {
            res.result == 'success' && this.$message.success('更新成功')
            this.dialogVisible = false
            // this.getData();
            // this.dataCount();
            // 默认显示全部建筑信息
            this.changeCascader();
        })
    }

    handleSizeChange(val: number) {
        this.paginationList.size = val;
        this.changeCascader();
    }

    // 搜索
    searchValue(val: string) {
        this.inputSearch = val;
        this.changeCascader();
    }

    // 编辑当前行
    handleCurrentEdit(val) {
        // this.next = false
        this.currRowContent = val
        this.spaceHeaders = this.headersStage
        // this.handleNext()
        this.dialogVisible = true
    }

    // tab页切换
    tabChange() {
        if (this.activeName == "picture") {
            this.$nextTick(() => {
                this.toGraph();
            });
        }
    }

    // 切换至图
    toGraph() {
        if (this.graphBuilding.length) {
            if (
                this.graphBuilding.indexOf("noKnow") < 0 &&
                this.graphBuilding.indexOf("all") < 0
            ) {
                this.$refs.spaceGraph.getData(
                    this.floorToMap[this.graphBuilding[1]],
                    this.zoneTypeVal
                );
            } else {
                this.$refs.spaceGraph.noMap();
            }
        } else {
            this.$refs.spaceGraph.noMap();
        }
    }
}
</script>

<style lang="scss" scoped>
.void {
    margin-top: 200px;
}

.align {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    flex-wrap: wrap;
}

.adm-space {
    background: #fff;
    padding: 12px;
    height: 100%;

    .small-divider {
        margin: 12px 0;
    }

    .tabs {
        position: relative;
        height: calc(100% - 92px);

        ::v-deep .el-tabs__header {
            margin: 0;
        }

        .tab-content {
            height: calc(100% - 41px);
            border: 1px solid #e1e7ea;
            border-top: none;
            padding-bottom: 12px;

            .search {
                padding: 16px;
                //border-bottom: 1px solid #e1e7ea;
                & > .item + .item {
                    margin-left: 16px;
                }
            }
            .borderBottom {
                border-bottom: 1px solid #e1e7ea;
            }
            .graph {
                height: calc(100% - 64px);
            }
        }
    }

    .adm-pagination {
        right: 10px;
        position: absolute;
        bottom: 10px;
    }
}
</style>
<style lang="scss">
.adm-space {
    .el-dialog {
        .el-dialog__body {
            max-height: 500px !important;
            min-height: 100px;
            overflow-y: auto;
            overflow-x: hidden;
        }
    }

    .el-select, .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 100%;
    }
}
</style>
