<template>
    <div class="relation-ship" v-loading="loading">
        <section style="margin-top: 20px">
            <el-button style="padding: 10px" icon="el-icon-back" @click="back" />
            <el-button type="primary" @click="addBtn">添加关系 </el-button>
            <el-button type="default" style="float: right" @click="excel"> Excel导出 </el-button>
        </section>
        <section>
            <el-row>
                <el-col :span="12">
                    <p class="border-left-8">
                        主对象 <span>{{ MainObject }}</span>
                    </p>
                    <label>所属建筑楼层：</label>
                    <el-select disabled v-model="buildValue">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                    <label>类型：</label>
                    <el-cascader :options="typeList" :props="props" collapse-tags clearable disabled />
                    <el-input
                        placeholder="请输入"
                        @keyup.enter.native="queryTable(1)"
                        v-model="mainValue"
                        style="margin-left: 5px"
                        class="min-margin"
                    >
                        <i slot="suffix" class="el-input__icon el-icon-search cursor" @click="queryTable(1)" />
                    </el-input>
                </el-col>
                <el-col :span="12">
                    <p class="border-left-8">
                        从对象 <span>{{ FromObject }}</span>
                    </p>
                    <label>所属建筑楼层：</label>
                    <el-select disabled v-model="buildValue">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                    <label>类型：</label>
                    <el-cascader :options="typeList" :props="props" collapse-tags clearable disabled />
                    <el-input
                        placeholder="请输入"
                        @keyup.enter.native="queryTable(2)"
                        v-model="formValue"
                        style="margin-left: 5px"
                        class="min-margin"
                    >
                        <i slot="suffix" class="el-input__icon el-icon-search cursor" @click="queryTable(2)" />
                    </el-input>
                </el-col>
            </el-row>
        </section>

        <section class="table-list" :style="tableData && tableData.length ? 'height:calc(100% - 250px)' : 'height:100%'">
            <!--              :span-method="objectSpanMethod"
      -->
            <el-table
                :data="tableData"
                :span-method="objectSpanMethod"
                :header-cell-style="{ background: '#e1e4e5', color: '#2b2b2b', lineHeight: '30px' }"
                :cell-style="cellStyle"
                class="table"
                style="width: 100%"
                height="100%"
            >
                <el-table-column prop="Name" label="全局名称" width="180" align="left" min-width="100"> </el-table-column>
                <el-table-column prop="LocalID" label="本地编码" align="left" min-width="100"> </el-table-column>
                <el-table-column prop="LocalName" label="本地名称" align="left" min-width="100"> </el-table-column>
                <el-table-column prop="CADID" label="CADID" align="left" min-width="100"> </el-table-column>
                <el-table-column label="对象详情" prop="btn" align="center" min-width="90">
                    <template slot-scope="scope">
                        <el-button type="text" size="mini" @click="lookOver(scope.$index, scope.row)">查看 </el-button>
                    </template>
                </el-table-column>
                <el-table-column class-name="td-bl" prop="cName" label="全局名称" width="180" align="left"> </el-table-column>
                <el-table-column prop="cLocalID" align="left" label="本地编码"> </el-table-column>
                <el-table-column prop="cLocalName" label="本地名称" align="left"> </el-table-column>
                <el-table-column prop="cCADID" label="CADID" align="left"> </el-table-column>
                <el-table-column label="对象详情" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" size="mini" @click="lookOver(scope.$index, scope.row)">查看 </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="left">
                    <template slot-scope="scope">
                        <el-button slot="reference" size="mini" icon="el-icon-delete" @click="deleteObject(scope.$index, scope.row)" />
                    </template>
                </el-table-column>
            </el-table>
        </section>
        <!-- 分页 -->
        <el-pagination
            class="relation-ship-pagination"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            style="float: right; margin-top: 10px; padding: 2px 5px"
        >
        </el-pagination>

        <exportExcel ref="export" :values="values" :length="length" @upDataTable="upDataTable" />
        <addRelationShip ref="addShipComponent" :values="values" @update="update" />
        <editRelationShip ref="editShipComponent" :values="values" />
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import exportExcel from "@/components/old-adm/relation/components/relationShip/Modal/exportExcel";
import addRelationShip from "@/components/old-adm/relation/components/relationShip/Modal/addRelationShip";
import editRelationShip from "@/components/old-adm/relation/components/relationShip/Modal/editRelationShip";
// import { relDelete, relQuery } from "../../../api/relation/api";
import Relation from '@/controller/old-adm/relationController'
const { relDelete, relQuery } = Relation

export default {
    name: "index",
    data() {
        return {
            MainObject: `（限制条件：${localStorage.getItem("MainObject") || "无"}）`,
            FromObject: `（限制条件：${localStorage.getItem("FromObject") || "无"}）`,
            pageSizes: [10, 20, 50, 100],
            pageSize: 50,
            currentPage: 1,
            total: 0,
            values: {
                relation_maintenance: "关系维护",
                optionTips: `请下载最新<${localStorage.getItem("RelationTypeName")}>数据进行手动维护`, //请下载最新最新 xxxx 数据进行手动维护
                currentNum: "当前关系数量：",
                download: "下载模板（含数据）",
                lastTime: `最后更新时间为：${localStorage.getItem("ComputingTime") || ""}`, //最后更新时间为
                uploadTxt: "将Excel文件拖到此处，或<em>单击上传Excel文件<em>",
                uploadTips: "上传的Excel数据将完全覆盖当前关系表（关系表先前数据不会保留）",
                downloadFile: " 下载报告文件",
                back: "返回",
                done: "完成",
                addShip: "添加关系",
                editShip: "编辑关系",
                codeTip: "请填写主被控设备对象识别编码",
                deviceTip: "请填写主被控设备对象设备号",
                codeTitle: "识别编码对应：",
                mainObject: "主对象：",
                affiliatedObject: "从对象：",
                pleaseEnter: "请输入",
                pleaseEnterCode: "请输入识别编码",
                add: "添加",
                cancel: "取消",
                delete: "删除关系",
            },
            mainValue: "",
            formValue: "",
            options: [
                {
                    value: "all",
                    label: "全选",
                },
                {
                    value: "选项2",
                    label: "双皮奶",
                },
                {
                    value: "选项3",
                    label: "蚵仔煎",
                },
                {
                    value: "选项4",
                    label: "龙须面",
                },
                {
                    value: "选项5",
                    label: "北京烤鸭",
                },
            ],
            buildValue: "all",
            props: { multiple: true },
            typeList: [
                {
                    value: 1,
                    label: "东南",
                    children: [
                        {
                            value: 2,
                            label: "上海",
                        },
                        {
                            value: 7,
                            label: "江苏",
                        },
                        {
                            value: 12,
                            label: "浙江",
                        },
                    ],
                },
                {
                    value: 17,
                    label: "西北",
                    children: [
                        {
                            value: 18,
                            label: "陕西",
                        },
                        {
                            value: 21,
                            label: "新疆维吾尔族自治区",
                        },
                    ],
                },
            ],
            tableData: [],
            delParam: {},
            loading: false,
            needMergeArr: ["Name", "LocalID", "LocalName", "CADID", "btn"],
            rowMergeArrs: {},
            length: "",
            // needMergeArr: ['name', 'id'], // 有合并项的列
            // rowMergeArrs: {}, // 包含需要一个或多个合并项信息的对象
        };
    },
    components: { exportExcel, addRelationShip, editRelationShip },
    created() {
        this.$store.dispatch("setBreadcrumb", [
            {
                label: "全部关系总览",
                path: "/relation/overview",
            },
            {
                label: "全部关系总览",
                path: "/relation/overview",
            },
            {
                label: localStorage.getItem("RelationTypeName"),
            },
        ]);
        this.init();
    },
    watch: {
        projectId() {
            this.init();
        },
    },
    computed: {
        ...mapGetters("layout", ["projectId"]),
    },
    mounted() {
        // this.getSpanArr(this.tableData)
    },
    methods: {
        deepCopy(obj) {
            return JSON.parse(JSON.stringify(obj));
        },
        upDataTable() {
            this.init();
        },
        init() {
            this.loading = true;
            let data = {
                projectId: this.projectId,
                objectType: 1,
                relType: localStorage.getItem("RelManualType"),
                pageSize: this.pageSize,
                // PageSize: 10000000,
                pageNumber: this.currentPage,
            };
            relQuery(data, (res) => {
                this.filterTable(res);
                this.length = res.total || 0;
                this.total = res.total;
                this.loading = false;
            });
        },
        filterTable(list) {
            let arr = [];
            if (list.content.length) {
                list.content.forEach((i) => {
                    i.objectInfo &&
                        i.objectInfo.forEach((j) => {
                            arr.push({
                                Name: i.name,
                                LocalName: i.localName,
                                LocalID: i.localId,
                                CADID: i.cadId,
                                cName: j.name,
                                cLocalName: j.localName,
                                cLocalID: j.localId,
                                cCADID: j.cadId,
                                Id: i.id,
                                cId: j.id,
                            });
                        });
                });
                this.tableData = this.deepCopy(arr);
                this.rowMergeArrs = this.rowMergeHandle(this.needMergeArr, this.tableData); // 处理数据
            } else {
                this.tableData = [];
            }
            // this.length = this.tableData.length
        },
        back() {
            this.$router.go(-1);
        },

        addBtn() {
            this.$refs.addShipComponent.addShipDialog = true;
        },
        excel() {
            this.$refs.export.dialogExport = true;
        },
        queryTable(i) {
            let param = {},
                relType = localStorage.getItem("RelManualType");
            if (i === 1) {
                param = {
                    objectType: 1,
                    relType,
                    vague: this.mainValue,
                };
            } else {
                param = {
                    objectType: 2,
                    relType,
                    vagueTo: this.formValue,
                };
            }
            relQuery(param, (res) => {
                this.filterTable(res);
                // console.log(res, '==object==')
            });
        },
        //分页更换size
        handleSizeChange(val) {
            this.currentPage = 1;
            this.pageSize = val;
            this.init();
        },
        //分页更换页
        handleCurrentChange(val) {
            this.currentPage = val;
            this.init();
        },
        update() {
            this.init();
        },
        lookOver(index, row) {
            this.$message.info("开发中");
            console.log(index, row);

            return false;

            // this.$refs.editShipComponent.editShipDialog = true
        },
        deleteObject(index, row) {
            this.delParam = {
                fromId: row.Id,
                relType: localStorage.getItem("RelManualType"),
                toId: row.cId,
            };
            this.$confirm("确定删除吗?", "提示", {
                confirmButtonText: "确 定",
                cancelButtonText: "取 消",
            })
                .then(() => {
                    this.confirmDelete();
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },
        confirmDelete() {
            relDelete(this.delParam, (res) => {
                this.init();
                this.$message.success("删除成功");
            });
        },
        cellStyle({ row, column, rowIndex, columnIndex }) {
            if (column.label === "全局名称") {
                return {
                    background: "#f9f9f9",
                    color: "#606266",
                    lineHeight: "30px",
                };
            }
        },

        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            if (column.property === "Name") return this.mergeAction("Name", rowIndex, column);
            // if (column.property === 'LocalID' && row.LocalID != undefined) return this.mergeAction('LocalID', rowIndex, column);
            // if (column.property === 'LocalName' && row.LocalName != undefined) return this.mergeAction('LocalName', rowIndex, column);
            // if (column.property === 'CADID' && row.CADID != undefined) return this.mergeAction('CADID', rowIndex, column);
            if (column.property === "btn") return this.mergeAction("Name", rowIndex, column);
        },
        mergeAction(val, rowIndex, colData) {
            let _row = this.rowMergeArrs[val].rowArr[rowIndex];
            let _col = _row > 0 ? 1 : 0;
            return [_row, _col];
        },
        rowMergeHandle(arr, data) {
            if (!Array.isArray(arr) && !arr.length) return false;
            if (!Array.isArray(data) && !data.length) return false;
            let needMerge = {};
            arr.forEach((i) => {
                needMerge[i] = {
                    rowArr: [],
                    rowMergeNum: 0,
                };
                data.forEach((item, index) => {
                    if (index === 0) {
                        needMerge[i].rowArr.push(1);
                        needMerge[i].rowMergeNum = 0;
                    } else {
                        if (item[i] === data[index - 1][i]) {
                            needMerge[i].rowArr[needMerge[i].rowMergeNum] += 1;
                            needMerge[i].rowArr.push(0);
                        } else {
                            needMerge[i].rowArr.push(1);
                            needMerge[i].rowMergeNum = index;
                        }
                    }
                });
            });
            return needMerge;
        },
    },
};
</script>

<style scoped lang="less">
.relation-ship {
    @media screen and (max-width: 1500px) {
        .min-margin {
            margin-top: 10px;
        }
    }

    .cursor {
        cursor: pointer;
    }

    /deep/ .el-input__inner {
        width: 220px;
        padding-right: 25px;
    }

    /deep/ .el-input {
        width: auto;
    }

    /deep/ .el-table__body-wrappe {
    }

    .table-list {
        width: 100%;
        display: block;
        /*height: calc(100% - 71px);*/
    }

    .table {
        width: 100%;
        margin-top: 20px;

        .el-button {
            border: none;
            background: transparent;

            &:link,
            &:visited,
            &:hover,
            &:active {
                background: #f5f7fa;
            }
        }
    }

    .border-left-8 {
        border-left: 8px solid black;
        margin: 10px 0;
        font-weight: 600;
        text-indent: 10px;

        span {
            color: #aaaaaa;
            margin-left: 20px;
        }
    }

    .relation-ship-pagination {
        /deep/ .el-input__inner {
            width: auto;
            padding-right: 25px;
        }

        /deep/ .el-select .el-input {
            width: auto;
        }
    }
}
</style>
