<!-- 添加显示实例(设备) -->
<template>
    <el-dialog
        custom-class="equipment-detail-dialog"
        @click.native="showPopover && (showPopover = false)"
        append-to-body
        title="添加显示实例"
        :visible="dialogTableVisible"
        @close="close"
        :close-on-press-escape="false"
    >
        <div class="header">
            <span class="text1">
                <el-popover v-model="showPopover" width="240" placement="bottom-start" trigger="manual" popper-class="init-popover">
                    <p>请先选择需展示的设备实例范围</p>
                    <el-button size="mini" class="m-btn" @click="showPopover = false">我知道了</el-button>
                    <span slot="reference">选择设备:</span>
                </el-popover>
            </span>
            <!-- 设备实例范围 树 -->
            <TreeSelect
                title="已选项"
                unit="个"
                placeholder="请选择"
                :width="240"
                :height="300"
                :caption="'设备实例范围'"
                :notNull="true"
                :returnParentNode="false"
                :isShowAllChoice="true"
                :selectedIds="selectedIds1"
                :choseArea="true"
                :data="dataTree1"
                @change="treeChange1"
            />
            <span class="text2">选择空间:</span>
            <!-- 空间分区类型 菜单 -->

            <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"
            />
        </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>
        <!-- TODO:  -->
        <edit-info-point type="equipment" @closeModal="showEditInfoPoint = false" :showDialog="showEditInfoPoint" />
    </el-dialog>
</template>
<script>
/**
 * 添加显示实例
 */
import editInfoPoint from "./editInfoPoint";
import { Select, TreeSelect } from "meri-design";
import { cloneDeep } from "lodash";
import { ruleCreate } from "@/api/labsl";
import { dictCategoryQuery, dictQuery, PartiInstancQuery } from "@/api/datacenter";
import { categoryQuery, typeQuery, equipQuery } from "@/api/equipcomponent";
import { array2Tree, mapTree } from "@/utils/utils";
const dataTree = [
    {
        id: "0",
        name: "顶级顶级",
        open: true,

        children: [
            {
                id: "1",
                name: "一级1",
                // open: false,
                //
                children: [
                    { id: "121", name: "测试文字溢出测试文字溢出测试文字溢出测试文字溢出测试文字溢出测" },
                    { id: "122", name: "二级3111", checked: "uncheck" },
                    { id: "123", name: "二级4", checked: "uncheck" },
                    { id: "124", name: "二级1" },
                ],
            },
            {
                id: "2",
                name: "一级2",
                children: [
                    { id: "221", name: "测试222", checked: "uncheck" },
                    { id: "222", name: "二级21", checked: "uncheck" },
                    { id: "223", name: "二级22", checked: "uncheck" },
                ],
            },
            {
                id: "3",
                name: "一级3",
                children: [
                    { id: "321", name: "测试222" },
                    { id: "322", name: "二级32" },
                ],
            },
        ],
    },
];
export default {
    name: "addEquipmentDialog",
    props: {
        showDialog: {
            type: Boolean,
            required: true,
        },
    },
    components: { Select, TreeSelect, editInfoPoint },
    data() {
        return {
            timer: null,
            showPopover: false, //选择设备 popover是否显示
            dataTree1: [],
            dataTree2: [], // cloneDeep(dataTree),
            dataTree3: [], // cloneDeep(dataTree),
            selectedIds1: [],
            selectedIds2: [],
            selectedIds3: [],
            curentSelectTree1: [], //选中的设备 实例范围
            curentSelectTree2: [], //选中的空间 分区类型
            spacePartitionType: [],
            spacePartitionTypeData: [],
            curentSelectTree3: [], //选中的空间 功能类型
            dialogTableVisible: false,
            spacePartitionInstance: [], //选中的空间分区下实例
            selectData: [
                // { id: "test1", name: "选择项" },
            ],
            tableData: [
                // {
                //     date: "实例总数量 111111",
                // },
                // {
                //     date: "监控器",
                //     name: "111",
                //     address: "dfadfasdfa",
                // },
            ],
            _tableData: [],
            showEditInfoPoint: false, //显示编辑信息点弹窗
        };
    },
    watch: {
        // 是否打开弹窗
        showDialog(val) {
            this.dialogTableVisible = val;
            if (val) {
                this.initModal();
            }
        },
        /**
         * 监听分区类型变化(点击下拉框删除按钮,触发表格数据查询)
         */
        spacePartitionType: {
            handler(newV, oldV) {
                if (!newV.length && oldV.length) {
                    this.spacePartitionInstance = [];
                    // this.getTableData();
                }
            },
            deep: true,
        },
        /**
         * 监听分区下实例变化(点击下拉框删除按钮,触发表格数据查询)
         */
        spacePartitionInstance: {
            handler(newV, oldV) {
                if (!newV.length && oldV.length) {
                    this.getTableData();
                }
            },
            deep: true,
        },
    },
    created() {},
    mounted() {
        // window.vm = this;
        /*   setTimeout(() => {
            this.showPopover = true;
        }, 2000); */
    },
    methods: {
        /**
         * 设备实例范围树更改
         */
        treeChange1(data, dataObj) {
            if (!dataObj) {
                this.curentSelectTree1 = [];
            } else {
                // 筛选树的最后一级,按照组件返回数组的name中/的个数
                this.curentSelectTree1 = dataObj.filter((v) => v.name.split("/").length === 3).map((v) => v.id);
            }
            // 查询设备列表
            this.curentSelectTree1.length && this.getTableData();
        },
        /**
         * 空间 分区类型树
         */
        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.getCategory();
            // 分区类型 列表
            this.getType();
            this.getDict();
        },
        /**
         * 查询设备实例树
         */
        async getCategory() {
            let res = await dictCategoryQuery({ type: "majorSystemEquip" });
            console.log(res);
            let tree = res?.content || [];
            // 遍历tree,使其id属性变为为_id属性, code属性变成id属性
            console.time(1);
            this.dataTree1 = mapTree(tree, "id->_id", "code->id");
            console.timeEnd(1);
        },
        /**
         * 空间分区类型 列表
         */
        async getType() {
            let res = await dictCategoryQuery({ type: "space" });
            let data = res?.content || [];
            data.map((v) => (v.id = v.code));
            //  name,code-->    { id: "test1", name: "选择项" },
            this.spacePartitionTypeData = data;
        },
        /**
         * 空间分区实例
         */
        async getPartiInstance() {
            let postParams = {
                pageNumber: 1,
                pageSize: 1000,
                floorId: "Fl11010500296bc7ca3a0d5d41419cf95c5b45116400",
                buildingId: "Bd1101050029cb77fbd1846611eaac87cd1cd6a961c6",
                // floorId: "",
                // buildingId: "",
                zoneTypeList: this.spacePartitionType,
            };
            let res = await PartiInstancQuery(postParams);
            console.log("==================");
            console.log(res);
            console.log(res.content);
            let data = res.content.map((v) => {
                return { id: v.id, name: v.localName };
            });
            this.selectData = data;
            this.spacePartitionInstance = [];
            //   v-model="spacePartitionInstance"
            // :selectdata="selectData"
        },
        // 空间功能类型
        async getDict() {
            let res = await dictQuery({
                filters: "code='roomFuncType'",
                type: "GeneralZone",
            });
            let data = res?.content[0]?.dataSource || [];
            data.map((v) => (v.id = v.code));
            // 构造树
            this.dataTree3 = array2Tree(data, "parentCode");
        },
        async getTableData() {
            // console.trace("getTableData");
            // 东坝地上二层
            let postParams = {
                equipTypes: this.curentSelectTree1, //设备类型  //["FFFSSN"],
                zoneTypes: this.spacePartitionType, //空间类型
                spaceIds: this.spacePartitionInstance, //空间实例id
                funcTypes: this.curentSelectTree3, //空间功能区类型
                floorId: "Fl11010500296bc7ca3a0d5d41419cf95c5b45116400",
                buildingId: "Bd1101050029cb77fbd1846611eaac87cd1cd6a961c6",
            };
            let res = await equipQuery(postParams);
            let data = res.content || [];
            this._tableData = data;
            let map = {};
            data.map((item) => {
                if (!map[item.classCode]) {
                    map[item.classCode] = {
                        classCode: item.classCode,
                        codeName: item.codeName,
                        total: 1,
                    };
                } else {
                    map[item.classCode].total++;
                }
            });
            let tableData = Object.values(map);
            tableData.length && tableData.unshift({ codeName: "实例总数量: " + data.length });
            this.tableData = 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) {
            console.log(data);
            this.showEditInfoPoint = true;
        },
        /**
         *  关闭弹窗
         */
        close() {
            console.log("close");
            // dialogTableVisible
            this.dialogTableVisible = false;
            this.showPopover = false;
            // clearTimeout(this.timer);
            this.$emit("closeModal");
        },
        /**
         * 点击弹窗确定,提交接口
         */
        async confirm() {
            let postParams = {
                id: "48598fc65edd4f2f8402202f0b793972",
                graphId: "806a12663cb147cebefb393d49fc0357",
                returnType: "equip", // 返回类型(equip: 设备, equipGroup: 设备组, zone: 空间)
                commond: "query", // 命令类型(query: 查询, delete: 删除)
                params: {
                    equipTypes: this.curentSelectTree1, //设备类型  //["FFFSSN"],
                    zoneTypes: this.spacePartitionType, //空间类型
                    spaceIds: this.spacePartitionInstance, //空间实例id
                    funcTypes: this.curentSelectTree3, //空间功能区类型
                },
                note: "",
            };
            console.log(postParams);
            let res = await ruleCreate(postParams);
            console.log("===============");
            console.log(res);
            if (res.result === "success") {
                this.$message.success("添加成功");
                this.dialogTableVisible = false;
                this.showPopover = false;
            } else {
                this.$message.error(res.message || "添加失败");
            }
            // clearTimeout(this.timer);
        },
    },
};
</script>
<style lang="less">
.init-popover {
    width: 240px;
    height: 115px;
    background: #0091ff;
    box-shadow: 0px 2px 10px 0px rgba(31, 36, 41, 0.1);
    .popper__arrow::after {
        border-bottom-color: #0091ff !important;
    }
    p {
        text-align: center;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #ffffff;
        line-height: 22px;
    }
    .m-btn {
        display: flex;
        align-items: center;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #0091ff;
        height: 28px !important;
        position: absolute;
        bottom: 15px;
        right: 20px;
    }
}
</style>
<style lang='less' scoped>
/deep/ .equipment-detail-dialog {
    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>