<template>
    <el-container class="home">
        <!-- 顶部导航栏 -->
        <el-header class="header">
            <Select width="200" radius @change="testClick" :selectdata="dataSelect3" :placeholder="'请选择'" :hideClear="true" />
            <DropDownButton
                @click="createCanvas"
                type="primary"
                drop-down-type="split-drop"
                interactive="tap"
                :drop-down-list="dropDownList"
                @input="batchCreateCanvas"
                >新建画布</DropDownButton
            >
            <!-- <el-popover placement="bottom" width="320" v-model="popVisible" popper-class="createPopper" trigger="manual">
                <p>点击这里即可快速创建画布。</p>
                <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="popVisible=false">我知道了</el-button>
                </div>
            </el-popover> -->
        </el-header>
        <!-- body部分 -->
        <el-container class="bodys">
            <!-- 左侧树状导航栏部分 -->
            <el-aside class="aside" width="240px">
                <left-folder ref="leftFolder" @changeFolder="changeFolder"></left-folder>
                <!-- 
                <div class="recycle" @click="showRecycleDialog">
                    <img :src="require('@/assets/images/recycle.png')" />
                    <span>回收站</span>
                </div> -->
            </el-aside>
            <!-- 展示部分 -->
            <el-main class="main">
                <div class="main-head" v-if="noTreeFlag">
                    <div class="showType" v-show="!selectCard.length">
                        <el-radio-group v-model="isPub" size="small" @change="changePub">
                            <el-radio-button :label="1">已发布</el-radio-button>
                            <el-radio-button :label="0">未发布</el-radio-button>
                        </el-radio-group>
                        <div class="head-right">
                            <el-input
                                placeholder="搜索"
                                prefix-icon="el-icon-search"
                                size="small"
                                v-model="queryText"
                                @keyup.native.enter="changeQueryText"
                                clearable
                                @clear="changeQueryText"
                            >
                            </el-input>
                            <!-- 不显示筛选下拉框 -->
                            <!-- <Dropdown class="Dropdown" v-model="selVal" :data="dataSelect">
                                <span class="drop-text">{{ selText }}</span>
                            </Dropdown> -->
                        </div>
                    </div>
                    <div class="showAction" v-show="selectCard.length">
                        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
                        <span style="margin-left: 10px">|</span>
                        <span class="sum"
                            >已选择<span style="color: #252b30; margin: 0 5px">{{ selectCard.length }}</span
                            >项目</span
                        >
                        <el-button size="mini" @click="groupMove">移动到</el-button>
                        <!-- <el-button size="mini" @click="groupDownload" v-if="isPub">下载</el-button> -->
                        <el-button size="mini" @click="groupDelete">删除</el-button>
                        <i class="el-icon-close" style="float: right; line-height: 28px; margin-right: 5px" @click="handleCheckAllChange(false)"></i>
                    </div>
                </div>
                <div class="main-body" v-loading="cardLoading">
                    <div class="has-data-body" v-if="cardTree.length">
                        <div class="building" v-for="buildingData in cardTree" :key="buildingData.buildingId">
                            <!-- 建筑名称 -->
                            <p class="buinding-name"><span class="border-left"></span> {{ buildingData.localName }}</p>
                            <div class="floor" v-for="floor in buildingData.floorList" :key="floor.floorId">
                                <!-- 楼层名称 -->
                                <p class="floor-name">{{ floor.localName }}</p>
                                <template v-for="t in floor.planarGraphList">
                                    <planImageCard
                                        :isPub="isPub"
                                        :data="t"
                                        :key="`${Math.random()}_${t.id}`"
                                        @changeCheck="changeCheck"
                                        @rename="rename"
                                        @publishSuc="updateSuc"
                                        @moveTo="moveTo"
                                        @delete="deleteGraph"
                                        @editTag="editTag"
                                        @toEdit="toEdit(t, floor.localName, floor.infos || {})"
                                        @download="download"
                                    ></planImageCard>
                                </template>
                            </div>
                        </div>
                    </div>
                    <div class="no-data-body" v-else style="margin-top: 112px">
                        <img src="@/assets/images/no-data.png" style="width: 116px; height: 116px" />
                        <p style="font-size: 16px; margin-top: 15px">暂无数据</p>
                    </div>
                </div>
            </el-main>
        </el-container>

        <!-- 创建画布 -->
        <createPlanarDialog ref="createPlanarDialog" @createPlanar="createPlanarCallback"></createPlanarDialog>
        <!-- 重命名 -->
        <rename ref="rename" :isPub="isPub" @updateSuc="updateSuc"></rename>
        <!-- 移动到 -->
        <move ref="move" :isPub="isPub" @moveSuc="moveSuc"></move>
        <!-- 删除二次确认 -->
        <deleteDialog ref="deleteDialog" :isPub="isPub" @deleteSuc="deleteSuc"></deleteDialog>
        <!-- 修改标签 -->
        <tagDialog ref="tagDialog" :isPub="isPub" @updateSuc="updateSuc"></tagDialog>
        <!-- 回收站全屏弹窗 -->
        <recycle ref="recycle" @recycleDialogClose="recycleDialogClose"></recycle>
        <!-- <equipment-deatil /> -->
    </el-container>
</template>

<script>
import { Select, DropDownButton } from "meri-design";
import leftFolder from "@/components/homeView/leftFolder.vue";
import planImageCard from "@/components/homeView/planImageCard.vue";
import { planerQuery, pubPlanerQuery, planerRead, pubPlanerRead, planerSave } from "@/api/labsl";
import rename from "@/components/homeView/rename";
import move from "@/components/homeView/move";
import deleteDialog from "@/components/homeView/deleteDialog";
import tagDialog from "@/components/homeView/tagDialog";
import recycle from "@/components/homeView/recycle";
import createPlanarDialog from "@/components/homeView/createPlanarDialog";
import { SNetUtil } from "@persagy-web/base";
import { mapState, mapMutations } from "vuex";
export default {
    name: "home",
    components: {
        Select,
        // Dropdown,
        DropDownButton,
        planImageCard,
        rename,
        move,
        deleteDialog,
        recycle,
        tagDialog,
        createPlanarDialog,
        leftFolder,
        // equipmentDeatil,
    },
    data() {
        return {
            dataSelect3: [
                { id: "test1", name: "选择项", sub: "hello111" },
                { id: "test2", name: "单平米", sub: "hola111" },
                {
                    id: "test3",
                    name: "下级分项",
                    sub: "bonjour",
                    divider: true,
                },
                { id: "test4", name: "滑动平均滑动平均", sub: "hi" },
            ], // 项目列表
            dropDownList: [
                {
                    id: "batch",
                    name: "批量新建",
                    disabled: true,
                },
            ],
            selVal: "lastUpdate", // 排序方式
            selText: "按最后修改", // 排序方式文字
            dataSelect: [
                { id: "lastUpdate", name: "按最后修改" },
                { id: "name", name: "按字母顺序" },
                { id: "createTime", name: "按创建时间" },
            ], // 排序选项
            queryText: "", // 搜索文字
            isPub: 1, // 发布类型()
            cardTree: [], // 当前显示的卡片树
            cardList: [], //卡片平铺树
            checkAll: false, // 全选
            selectCard: [], // 当前选中的卡片列表
            isIndeterminate: true, // 全选按钮
            curCategory: {}, // 当前选中的树节点
            noTreeFlag: true, // 左侧树是否有数据-默认有
            popVisible: true,
            categoryName: "", // 跳转编辑页面时分类名称
            imgUrl: "/image-service/common/image_get?systemId=dataPlatform&key=",
            cardLoading: false,
            folderId: "", //文件夹id
            folderName: "", //文件夹名称
        };
    },
    computed: {
        ...mapState(["showCheckbox"]),
    },
    methods: {
        ...mapMutations(["SETCARDSHOWCHECKBOX"]),
        testClick(data) {
            console.log(data);
        },
        // 创建画布
        createCanvas() {
            this.$refs.createPlanarDialog.showDialog();
        },
        // 新建画布成功回调
        createPlanarCallback(folder) {
            console.log("=============");
            console.log(folder);
            console.log("=============");
            /**
             * 1.
             *  folderId: "894983e26c20464e8c2e7d349d5bbc48"
                folderName: undefined
            2.
                folderId: "1cb3aa7281724617b05e60f494dd58e0"
                folderName: "dfas"
             */
            // TODO: 编辑器开发完后后解开注释
            /*  this.$router.push({
                name: "Editer",
                query: {
                    graphId: folder.graphId,
                    id: folder.id,
                    // categoryName: encodeURI(this.categoryName),
                    isPub: 0, //新建的是未发布的
                },
            });
            // 不进行文件夹的定位
            return true; */
            if (folder.folderId) {
                this.folderId = folder.folderId;
                // 是否新建文件夹
                if (folder.folderName) {
                    this.folderName = folder.folderName;
                    // 新建文件夹
                    this.$refs.leftFolder.getFolderData(folder.folderId);
                } else {
                    this.$refs.leftFolder.handleCheckFolder(folder.folderId);
                }
                // 选中未发布,查询列表
                this.isPub = 0;
                this.queryGraph();
            }
        },
        // 批量新建画布
        batchCreateCanvas(val) {
            alert(`批量创建画布${val}`);
        },
        // 选项改变
        changeCheck(v) {
            // 获取该对象在选中数组中的下标(按照id匹配)
            const index = this._.findIndex(this.selectCard, ["id", v.id]);
            if (index !== -1) {
                this.selectCard.splice(index, 1);
            } else {
                this.selectCard.push(v);
            }
            this.isIndeterminate = Boolean(this.selectCard.length) && this.selectCard.length < this.cardList.length;
            this.checkAll = this.selectCard.length === this.cardList.length;
        },
        // 全选按钮
        handleCheckAllChange(val) {
            let cardTree = [];
            cardTree = this.cardTree.map((building) => {
                building?.floorList?.map((_floor) => {
                    _floor?.planarGraphList?.map((card) => {
                        card.checked = val;
                    });
                    return _floor;
                });
                return building;
            });
            this.cardTree = cardTree;
            if (val) {
                this.selectCard = this._.cloneDeep(this.cardList);
            } else {
                this.selectCard = [];
            }
            this.isIndeterminate = false;
        },
        // 批量移动到
        groupMove() {
            this.$refs.move.showDialog(this.selectCard);
        },
        // 批量下载
        groupDownload() {
            if (this.selectCard.length) {
                this.selectCard.forEach((t) => {
                    this.download(t);
                });
            }
        },
        // 单独下载
        download(data) {
            if (data.pic) {
                SNetUtil.downLoad(data.name + ".png", this.imgUrl + data.pic);
            } else {
                // this.$message.warning(`${data.name}未绘制`)
            }
        },
        // 删除
        groupDelete() {
            this.$refs.deleteDialog.showDialog(this.selectCard);
        },
        // 重命名
        rename(data) {
            this.$refs.rename.showDialog(data);
        },
        // 移动到
        moveTo(data) {
            this.$refs.move.showDialog([data]);
        },
        // 单独删除
        deleteGraph(data) {
            this.$refs.deleteDialog.showDialog([data]);
        },
        // 更新成功-发布成功
        updateSuc() {
            this.queryGraph();
        },
        // 卡片移动事件
        moveSuc() {
            this.queryGraph();
        },
        // 删除成功
        deleteSuc() {
            this.queryGraph();
        },
        /**
         * 更改选中的文件夹
         */
        changeFolder(data) {
            console.log(data);
            // 清空搜索值
            this.queryText = "";
            // 如果没有文件夹数据,清空页面数据
            if (!data) {
                this.cardTree = [];
                this.cardList = [];
                this.folderId = "";
                return true;
            }
            this.folderId = data.id;
            this.folderName = data.name;
            this.queryGraph();
        },
        // 发布修改
        changePub() {
            this.queryGraph();
        },
        // 修改标签
        editTag(data) {
            this.$refs.tagDialog.showDialog(data);
        },
        // 输入内容变化
        changeQueryText() {
            this.queryGraph();
        },
        // 回收站点击
        showRecycleDialog() {
            this.$refs.recycle.showDialog();
        },
        // 回收站关闭
        recycleDialogClose() {
            this.queryGraph();
        },
        /**
         * 跳转编辑器
         */
        toEdit(data, floorLocalName, infos) {
            const { name, id, graphId, buildingId, floorId, version, state } = data,
                { floorMap = "" } = infos,
                { folderId, folderName } = this;
            // 已发布
            if (state === "Publish") {
                return this.handlePubImgCard(id, graphId, floorLocalName, floorMap);
            }
            // 未发布,直接跳转编辑器
            this.$router.push({
                name: "Editer",
                query: {
                    folderId,
                    folderName,
                    buildingId,
                    floorId,
                    floorLocalName,
                    name,
                    id,
                    graphId,
                    floorMap,
                    version,
                },
            });
        },
        /**
         * 点击已发布卡片.逻辑处理:
         * 如果在未发布中,有当前已发布的图的草稿,使用改未发布的草稿进行跳转
         * 没有的话,调用保存接口,生成一张未发布的草稿,使用该草稿进行跳转
         *
         * @param {string} id 图id
         * @param {string} graphId 图graphId
         * @param {string} floorLocalName 楼层本地名称
         * @param {string} floorMap floorMap
         */
        async handlePubImgCard(id, graphId, floorLocalName, floorMap) {
            // 留 id,floorLocalName,floorMap
            const { folderId, folderName } = this;
            const postParams = {
                filters: `state='Draft';id='${id}';graphId='${graphId}'`,
                PageNumber: 1,
                PageSize: 1000,
            };

            const res = await planerQuery(postParams);
            if (res.result !== "success") {
                this.$message(res.result);
            }
            // 判断 未发布中,是否有该张图的备份草稿,
            let flag = false;
            let DraftPlanarGraph = "";
            if (res.content?.length) {
                flag = true;
                DraftPlanarGraph = res.content[0].floorList[0].planarGraphList[0];
            } else {
                flag = false;
            }
            // 未发布中有该张图的备份草稿
            if (flag) {
                // 点击确认后,会继续后续流程
                let confirmRes;
                try {
                    confirmRes = await this.$confirm("未发布中有该张图,将使用未发布中的图进行编辑", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    });
                } catch (error) {
                    console.log("点击取消");
                }
                // 点击确定,跳转编辑器
                // 点击确定 confirmRes返回 confirm, 点击取消,confirmRes返回 undefined
                if (confirmRes) {
                    console.log(DraftPlanarGraph);
                    const { folderId, buildingId, floorId, id, graphId, name, version } = DraftPlanarGraph;
                    this.finalToEdit({ folderId, folderName, buildingId, floorId, floorLocalName, name, id, graphId, floorMap, version });
                }
            } else {
                // 未发布中,没有该张图的备份草稿
                // 读取该已发布的图信息
                const readRes = await pubPlanerRead({ graphId, id });
                if (readRes.result !== "success") {
                    this.$message(readRes.result);
                }
                // 保存该图,在未发布中,生成一张草稿
                const resSave = await planerSave(readRes.content);
                // 取出新建图的版本号
                if (resSave.result === "success") {
                    const resSaveData = resSave.entityList[0];
                    const { folderId, buildingId, floorId, name, id, graphId, version } = resSaveData;
                    this.finalToEdit({ folderName, floorLocalName, folderId, buildingId, floorId, name, id, graphId, version, floorMap });
                } else {
                    this.$message(resSave.result);
                }
            }
        },
        /**
         * 点击已发布,最终跳转编辑器
         */
        finalToEdit(query) {
            this.$router.push({ name: "Editer", query });
        },
        /**
         * 查询图形信息
         * @param { string } floderId 传入的文件ID,新建画布成功之后,会调用该接口
         * 如果传入floderId,使用该id,不传的话,使用全局的this.folderId
         */
        async queryGraph(floderId) {
            if (!(floderId || this.folderId)) {
                return false;
            }
            this.cardLoading = true;
            this.selectCard = [];
            // createTime: "2020-12-02 20:05:51"
            // id: "eba700e7ae7e452fb2341172d1350b77"
            // lastUpdate: "2020-12-02 20:05:51"
            // name: "能源系统"
            // projectId: "Pj1101050029"
            // statistics: {}
            const postParams = {
                filters: `folderId='${floderId || this.folderId}'`,
                PageNumber: 1,
                PageSize: 1000,
            };
            if (this.queryText) {
                postParams.filters += `;name contain '${this.queryText}'`;
            }
            /**
             * 已发布,未发布 1:已发布 0:未发布
             */
            let res;
            if (this.isPub) {
                res = await pubPlanerQuery(postParams);
            } else {
                // state Draft(未发布)，state Recyle(回收站)
                postParams.filters += ";state='Draft'";
                res = await planerQuery(postParams);
            }
            if (res.result !== "success") {
                this.cardTree = [];
                this.cardList = [];
                this.cardLoading = false;
                return false;
            }
            let cardTree = [];
            const cardList = [];
            cardTree = res?.content?.map((building) => {
                building?.floorList?.map((_floor) => {
                    _floor?.planarGraphList?.map((card) => {
                        card.checked = false;
                        // 保存建筑,楼层,卡片信息
                        cardList.push({
                            _buildingId: building.id,
                            _buildingLocalId: building.localId,
                            _buildingName: building.name,
                            _buildingLocalName: building.localName,
                            _floorId: _floor.id,
                            _floorLocalId: _floor.localId,
                            _floorName: _floor.name,
                            _floorLocalName: _floor.localName,
                            ...card,
                        });
                        return card;
                    });
                    return _floor;
                });
                return building;
            });
            this.cardTree = cardTree;
            this.cardList = cardList;
            this.cardLoading = false;
        },
    },
    watch: {
        // 排序方式修改
        selVal(n, o) {
            if (n === o) return;
            this.selText = this.dataSelect.find((d) => d.id === n).name;
            this.selectCard = [];
            this.queryGraph();
        },
        /**
         * 监听选择的卡片长度,有选择大于1时,设置所有卡片的复选框显示
         */
        selectCard: {
            handler(newV) {
                if (newV.length) {
                    console.log(newV);
                    this.SETCARDSHOWCHECKBOX(true);
                } else {
                    this.SETCARDSHOWCHECKBOX(false);
                }
            },
            deep: true,
            immediate: true,
        },
    },
};
</script>
<style lang="less" scoped>
.home {
    width: 100%;
    height: 100%;
    .header {
        width: 100%;
        height: 60px;
        background: #f7f9fa;
        padding: 0 16px 0 16px;
        border-bottom: 1px solid #e4e5e7;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .bodys {
        width: 100%;
        height: calc(100% - 60px);
        .aside {
            .recycle {
                line-height: 48px;
                border-top: 1px solid #e4e5e7ff;
                box-sizing: border-box;
                background: #f7f9fa;
                padding-left: 16px;
                cursor: pointer;
                img {
                    width: 16px;
                    height: 16px;
                    margin: -3px 8px 0 0;
                }
            }
        }
        .main {
            width: 100%;
            height: 100%;
            background: #fff;
            padding: 5px 20px;
            box-sizing: border-box;
            .main-head {
                position: relative;
                width: 100%;
                height: 46px;
                margin-bottom: 5px;
                .showType {
                    width: 100%;
                    padding: 7px 0;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    /deep/ .el-radio-button__orig-radio:checked + .el-radio-button__inner {
                        color: #0091ff;
                        border-color: #0091ff;
                        background: #e1f2ff;
                    }
                    .head-right {
                        display: flex;
                        align-items: center;
                        .Dropdown {
                            min-width: 100px;
                            margin-left: 20px;
                            .drop-text {
                                font-size: 14px;
                                color: #1f2329;
                                line-height: 16px;
                            }
                        }
                    }
                }
                .showAction {
                    background: #e1f2ff;
                    border-radius: 4px;
                    border: 1px solid #82c7fc;
                    padding: 8px;
                    span.sum {
                        margin: 0 10px;
                        color: #778089;
                    }
                }
            }
            .main-body {
                display: block;
                height: calc(100% - 51px);
                overflow: auto;
                .has-data-body {
                    // 建筑样式
                    .building {
                        // 建筑名称
                        .buinding-name {
                            display: flex;
                            align-items: center;
                            height: 30px;
                            font-size: 16px;
                            font-family: MicrosoftYaHei;
                            color: #1f2329;
                            line-height: 30px;
                            margin-bottom: 12px;
                            // 左边框竖线
                            span.border-left {
                                display: inline-block;
                                width: 2px;
                                height: 20px;
                                background: #0091ff;
                                margin-right: 4px;
                            }
                        }
                        // 楼层样式
                        .floor {
                            // padding-left: 9px;
                            display: flex;
                            flex-wrap: wrap;
                            padding-left: 20px;
                            .floor-name {
                                position: relative;
                                left: -12px;
                                width: 100%;
                                height: 31px;
                                font-size: 16px;
                                font-family: PingFangSC-Regular, PingFang SC;
                                font-weight: 400;
                                color: #646c73;
                                line-height: 31px;
                                margin-bottom: 8px;
                            }
                        }
                    }
                }

                .no-data-body {
                    display: flex;
                    flex-direction: column;
                    // justify-content: center;
                    align-items: center;
                }
            }
        }
    }
    .create-dialog {
        .dialog-bodys {
            width: 367px;
            margin: 0 auto;
        }
    }
    .create-dialog-inner {
        .inner-dialog-body {
            width: 100%;
            display: flex;
            .left {
                flex: 1;
                border-right: 1px solid #ccc;
            }
        }
    }
}
</style>
<style lang="less">
.createPopper.el-popover {
    background: #0091ffff;
    color: #fff;
    border-color: #0091ffff;
    .el-button {
        background: #ffffff;
        border-radius: 4px;
        padding: 5px 8px;
    }
    .popper__arrow::after {
        border-bottom-color: #0091ffff;
    }
}
</style>
