<!-- 添加空间 -->
<template>
    <el-dialog
        custom-class="space-detail-dialog"
        append-to-body
        title="添加显示空间"
        :visible="dialogTableVisible"
        @close="close"
        :close-on-press-escape="false"
    >
        <div class="header">
            <!-- 空间分区类型 菜单 -->
            <Select
                width="220"
                tipPlace="top"
                multiple
                caption="分区类型:"
                @confirm="spacePartitionTypeConfirm"
                v-model="spacePartitionType"
                :selectdata="spacePartitionTypeData"
                :placeholder="'请选择'"
            />
            <!-- 空间 分区下实例 菜单 -->
            <Select
                width="220"
                tipPlace="top"
                multiple
                caption="分区下实例:"
                @confirm="selectConfirm"
                :disabled="!spacePartitionType.length"
                v-model="spacePartitionInstance"
                :selectdata="selectData"
                :placeholder="'请选择'"
            />
            <!-- 空间功能类型 树 -->
            <TreeSelect
                title="已选项"
                unit="个"
                placeholder="请选择"
                :width="240"
                :height="300"
                :caption="'空间功能类型:'"
                :notNull="true"
                :returnParentNode="false"
                :isShowAllChoice="true"
                :selectedIds="selectedIds3"
                :choseArea="true"
                :disabled="!spacePartitionType.length"
                :data="dataTree3"
                @change="treeChange3"
                id="treeSelect"
            />
        </div>
        <!-- 表格 -->
        <el-table
            v-show="tableData.length"
            :data="tableData"
            max-height="420"
            :span-method="objectSpanMethod"
            style="width: 100%; margin-top: 10px"
            :row-class-name="tableRowClassName"
        >
            <el-table-column prop="codeName" label="业务分区名称" style="width: 30%"> </el-table-column>
            <el-table-column prop="total" label="空间实例数量" tyle="width: 30%"> </el-table-column>
            <el-table-column prop="classCode" label="操作">
                <template slot-scope="scope">
                    <el-link type="primary" @click="editInfo(scope.row)" :underline="false">编辑信息点</el-link>
                </template>
            </el-table-column>
        </el-table>
        <!-- 无数据 -->
        <div class="no-data-body" v-show="!tableData.length">
            <img src="@/assets/images/no-data.png" style="width: 116px; height: 116px" />
            <p style="font-size: 16px; margin-top: 15px">暂无数据</p>
        </div>
        <!-- 确定,取消按钮 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button :disabled="!tableData.length" :type="tableData.length ? 'primary' : 'info'" @click="confirm">确 定</el-button>
        </div>
        <!-- 编辑信息点 -->
        <edit-info-point type="space" @closeModal="showEditInfoPoint = false" :code="currentInfo.classCode || ''" :showDialog="showEditInfoPoint" />
    </el-dialog>
</template>
<script>
/**
 * 添加显示实例
 */
import { Select, TreeSelect } from "meri-design";
import { mapState, mapMutations } from "vuex";
import editInfoPoint from "./editInfoPoint";
import { ruleCreate } from "@/api/labsl";
import { dictCategoryQuery, dictQuery, PartiInstancQuery } from "@/api/datacenter";
import { spaceQuery } from "@/api/equipcomponent";
import { array2Tree } from "@/utils/utils";
import bus from "@/bus/bus";

export default {
    name: "addSpaceDialog",
    props: {
        showDialog: {
            type: Boolean,
            required: true,
        },
    },
    components: { Select, TreeSelect, editInfoPoint },
    data() {
        return {
            dataTree3: [],
            selectedIds3: [],
            spacePartitionType: [],
            spacePartitionTypeData: [],
            curentSelectTree3: [], //选中的空间 功能类型
            dialogTableVisible: false,
            spacePartitionInstance: [], //选中的空间分区下实例
            selectData: [
                // { id: "test1", name: "选择项" },
            ],
            tableData: [],
            tableDataBak: [],
            currentInfo: {}, //点击的设备类数据
            showEditInfoPoint: false, //显示编辑信息点弹窗
        };
    },
    computed: {
        ...mapState(["buildingId", "floorId", "id", "graphId"]),
    },
    watch: {
        // 是否打开弹窗
        showDialog(val) {
            this.dialogTableVisible = val;
            if (val) {
                this.initModal();
            }
        },
        /**
         * 监听分区类型变化(点击下拉框删除按钮,触发表格数据查询)
         */
        spacePartitionType: {
            handler(newV, oldV) {
                if (!newV.length && oldV.length) {
                    this.spacePartitionInstance = [];
                    this.curentSelectTree3 = [];
                    // this.getTableData();
                    this.tableData = [];
                    this.tableDataBak = [];
                }
            },
            deep: true,
        },
        /**
         * 监听分区类型值,修复treeSelect禁用时,点击caption仍然能点击开的问题
         */
        "spacePartitionType.length"(val) {
            // 分区类型无数据
            if (!val) {
                this.$nextTick(() => {
                    const el = document.querySelector("#treeSelect .p-select-input-caption");
                    const elClone = el.cloneNode(true);
                    el.parentNode.replaceChild(elClone, el);
                });
            } else {
                // 分区类型有数据
                this.$nextTick(() => {
                    const el = document.querySelector("#treeSelect .p-select-input-caption");
                    const elClone = el.cloneNode(true);
                    el.parentNode.replaceChild(this.el, el);
                });
            }
        },
        /**
         * 监听分区下实例变化(点击下拉框删除按钮,触发表格数据查询)
         */
        spacePartitionInstance: {
            handler(newV, oldV) {
                if (!newV.length && oldV.length) {
                    this.getTableData();
                }
            },
            deep: true,
        },
    },
    mounted() {
        //
    },
    methods: {
        ...mapMutations(["ADDRULE"]),
        /**
         * 空间 分区类型
         */
        spacePartitionTypeConfirm(data) {
            // 查询分区下实例列表
            if (this.spacePartitionType.length) {
                this.getPartiInstance();
            }
            // 查询表格
            this.getTableData();
        },
        /**
         * 空间 分区下实例
         */
        selectConfirm(data) {
            // 查询表格
            this.getTableData();
        },

        /**
         * 空间功能类型
         */
        treeChange3(data, dataObj) {
            if (!dataObj) {
                this.curentSelectTree3 = [];
            } else {
                // 筛选树的最后一级,按照组件返回数组的name中/的个数
                this.curentSelectTree3 = dataObj.filter((v) => v.name.split("/").length === 3).map((v) => v.id);
            }
            // 查询表格
            this.getTableData();
        },
        /**
         * 显示弹窗时的处理
         */
        initModal() {
            this.spacePartitionType = [];
            this.spacePartitionInstance = [];
            this.tableDataBak = [];
            this.tableData = [];
            // 分区类型 列表
            this.getType();
            // 空间功能类型
            this.getDict();
            this.$nextTick(() => {
                const el = document.querySelector("#treeSelect .p-select-input-caption");
                this.el = el;
                const elClone = el.cloneNode(true);
                el.parentNode.replaceChild(elClone, el);
            });
        },
        /**
         * 空间分区类型 列表
         */
        async getType() {
            const res = await dictCategoryQuery({ type: "space" });
            const data = res?.content || [];
            data.map((v) => (v.id = v.code));
            //  name,code-->    { id: "test1", name: "选择项" },
            this.spacePartitionTypeData = data;
        },
        /**
         * 空间分区实例
         */
        async getPartiInstance() {
            const postParams = {
                pageNumber: 1,
                pageSize: 1000,
                floorId: this.floorId, // "Fl11010500296bc7ca3a0d5d41419cf95c5b45116400",
                buildingId: this.buildingId, // "Bd1101050029cb77fbd1846611eaac87cd1cd6a961c6",
                zoneTypeList: this.spacePartitionType,
            };
            const res = await PartiInstancQuery(postParams);
            const data = res.content.map((v) => {
                return { id: v.id, name: v.localName || "--" };
            });
            this.spacePartitionInstance = [];
            if (data.length) {
                this.selectData = data;
            } else {
                this.selectData = [{ disabled: true, name: "暂无数据", id: "" }];
            }
        },
        // 空间功能类型
        async getDict() {
            const res = await dictQuery({
                filters: "code='roomFuncType'",
                type: "GeneralZone",
            });
            const data = res?.content[0]?.dataSource || [];
            data.map((v) => (v.id = v.code));
            // 构造树
            this.dataTree3 = array2Tree(data, "parentCode");
        },
        async getTableData() {
            // console.trace("getTableData");
            // 东坝地上二层
            const postParams = {
                zoneTypes: this.spacePartitionType, //空间类型
                spaceIds: this.spacePartitionInstance, //空间实例id
                funcTypes: this.curentSelectTree3, //空间功能区类型
                floorId: this.floorId, // "Fl1101050029ecc5d3aec0644d7f88647618f7bdd023",
                buildingId: this.buildingId, // "Bd1101050029cb77fbd1846611eaac87cd1cd6a961c6",
            };
            const res = await spaceQuery(postParams);
            const data = res.content || [];
            this.tableDataBak = data;
            const map = {};
            data.map((item) => {
                if (!map[item.classCode]) {
                    map[item.classCode] = {
                        classCode: item.classCode,
                        codeName: item.codeName,
                        total: 1,
                    };
                } else {
                    map[item.classCode].total++;
                }
            });
            const tableData = Object.values(map);
            tableData.length && tableData.unshift({ codeName: "实例总数量: " + data.length });
            this.tableData = tableData;
            console.log(tableData);
        },
        /**
         * 合并第一行
         */
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            if (rowIndex === 0) {
                if (columnIndex === 0) {
                    return {
                        rowspan: 1,
                        colspan: 3,
                    };
                } else {
                    return {
                        rowspan: 1,
                        colspan: 0,
                    };
                }
            }
        },
        /**
         * 行样式
         */
        tableRowClassName({ row, rowIndex }) {
            if (rowIndex === 0) {
                return "";
            }
            return "m-row";
        },
        /**
         * 编辑信息点
         */
        editInfo(data) {
            this.currentInfo = data;
            this.showEditInfoPoint = true;
        },
        /**
         *  关闭弹窗
         */
        close() {
            this.dialogTableVisible = false;
            this.$emit("closeModal");
        },
        /**
         * 点击弹窗确定,提交接口
         */
        async confirm() {
            const postParams = {
                content: [
                    {
                        graphCoding: this.id,
                        graphId: this.graphId,
                        returnType: "zone", // 返回类型(equip: 设备, equipGroup: 设备组, zone: 空间)
                        commond: "query", // 命令类型(query: 查询, delete: 删除)
                        params: {
                            equipTypes: [], //设备类型,添加空间无此字段
                            zoneTypes: this.spacePartitionType, //空间类型
                            spaceIds: this.spacePartitionInstance, //空间实例id
                            funcTypes: this.curentSelectTree3, //空间功能区类型
                        },
                    },
                ],
            };
            const res = await ruleCreate(postParams);
            if (res.result === "success") {
                this.$message.success("添加成功");
                // 在vuex中添加规则
                if (res.entityList && res.entityList[0]) {
                    this.ADDRULE(res.entityList[0]);
                    // 接口成功之后,发出添加空间指令
                    // TODO: 添加空间指令
                    bus.$emit("addZone", this.tableDataBak);
                }
                this.dialogTableVisible = false;
                this.showPopover = false;
            } else {
                this.$message.error(res.message || "添加失败");
            }
        },
    },
};
</script>
<style lang='less' scoped>
/deep/ .space-detail-dialog {
    margin-top: 8vh !important;
    width: 1200px;
    height: 648px;
    // background-color: blueviolet;
    .header {
        display: flex;
        align-items: center;
        .text1,
        .text2 {
            margin-right: 10px;
        }
        .text2 {
            margin-left: 15px;
        }
        & > div {
            margin-right: 10px;
        }
    }
    .m-row {
        color: #1f2429;
        font-weight: 600;
    }
    .no-data-body {
        width: 100%;
        height: 420px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }
    /deep/ .el-dialog__footer {
        position: absolute;
        right: 0;
        bottom: 0;
    }
}
</style>