<template>
    <div class="tab-content">
        <div class="search">
            <el-cascader
                :options="deviceOptions"
                clearable
                v-model="deviceList"
                :props="optionProps"
                @change="handleChangeDevice"
                class="item"
            ></el-cascader>
            <admSearch @SearchValue="searchValue" class="item" />
        </div>
        <div v-loading="loading" style="height: calc(100% - 100px); padding: 0 12px; position: relative">
            <template style="height: 100%" v-if="tableData.length">
                <admMultiTable
                    @handleCurrentEdit="handleCurrentEdit"
                    :isDynamicMap="false"
                    :currentHeader="currentHeader"
                    :headersStage="headersStage"
                    :tableData="tableData"
                />
                <Pagination
                    v-if="tableData.length"
                    :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>
</template>
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { allDevice, dictInfo } from "@/api/equipComponent";
import { queryEquip, updateEquip } from "@/api/datacenter";
import { AdmMultiTable, AdmSearch, Pagination } from "@/views/maintain/components/index";
import { UserModule } from "@/store/modules/user";

@Component({
    name: "EquipTab",
    components: {
        AdmMultiTable,
        AdmSearch,
        Pagination,
    },
})
export default class EquipTab extends Vue {
    // 项目id
    private get projectId(): string {
        return UserModule.projectId;
    }

    // 设备类型
    private get deviceType(): string {
        const length = this.deviceList.length;
        return length ? this.deviceList[length - 1] : "";
    }

    // 设备关键字
    private keyWord = "";
    // 设备类下拉绑定值
    private deviceList: any = [];
    // 设备筛选
    private deviceOptions: any[] = [];
    // 下拉框映射
    private optionProps: any = {
        value: "code",
        label: "name",
        children: "children",
    };
    // 表格数据加载loading
    private loading = false;
    // 表格数据
    private tableData: any[] = [];
    // 阶段信息
    private currentHeader = "运维阶段维护";
    // 表头阶段信息结合
    private headersStage: any = {};
    // 信息点集合（表头）
    private all: any = [];
    // 输入类型选项
    private codeToDataSource: any = {};
    // 分页
    private paginationList = {
        page: 1,
        size: 50,
        sizes: [10, 30, 50, 100, 150, 200],
        total: 0,
    };

    // created钩子
    created() {
        this.getDeviceOptions();
    }

    /**
     * 设备类数据
     */
    private async getDeviceOptions() {
        const res = await allDevice({});
        if (res.result === "success") {
            this.deviceOptions = res.content;
        }
    }

    /**
     * 获取设备数据（信息点和实例数据）
     */
    private getEquipData() {
        if (this.deviceType) {
            this.loading = true;
            let param = {
                category: this.deviceType,
            };
            let param2 = {
                filters: `classCode='${this.deviceType}'`,
                pageNumber: this.paginationList.page,
                pageSize: this.paginationList.size,
                orders: "createTime desc, id asc",
                projectId: this.projectId,
            };
            if (this.keyWord != "") {
                param2.filters += `;codeName contain '${this.keyWord}' or systemCategory contain '${this.keyWord}' or bimTypeId contain '${this.keyWord}' or localId contain '${this.keyWord}'`;
            }
            let promise = new Promise((resolve) => {
                dictInfo(param).then((res: any) => {
                    resolve(res);
                });
            });
            let promise2 = new Promise((resolve) => {
                queryEquip(param2).then((res: any) => {
                    resolve(res);
                });
            });
            Promise.all([promise, promise2]).then((res: any[]) => {
                this.loading = false;
                // 获取运维阶段名称
                this.currentHeader = res[0]?.dictStages.find((item: any) => {
                    return item.code === "moms";
                })?.name;
                this.headersStage = this.informationArrangement(res[0]); // 重组表头数据
                this.tableData = res[1]?.content ? res[1].content : []; // 主体数据
                this.paginationList.total = res[1]?.total ? res[1].total : 0;
            });
        } else {
            this.tableData = [];
        }
    }

    /**
     * 获取系统实例数据
     */
    private async getExampleData() {
        if (this.deviceType) {
            this.loading = true;
            let params = {
                filters: `classCode='${this.deviceType}'`,
                pageNumber: this.paginationList.page,
                pageSize: this.paginationList.size,
                orders: "createTime desc, id asc",
                projectId: this.projectId,
            };
            if (this.keyWord != "") {
                params.filters += `;codeName contain '${this.keyWord}' or systemCategory contain '${this.keyWord}' or bimTypeId contain '${this.keyWord}' or localId contain '${this.keyWord}'`;
            }
            const res = await queryEquip(params);
            if (res.result === "success") {
                this.tableData = res?.content ? res.content : []; // 主体数据
                this.paginationList.total = res?.total ? res.total : 0;
                this.loading = false;
            }
        } else {
            this.tableData = [];
        }
    }

    /**
     * 信息点重组
     */
    private informationArrangement(data: any): any {
        if (data?.basicInfos && data?.dictStages) {
            const base: any[] = [];
            data.dictStages.forEach((item: any) => {
                if (this.currentHeader === item.name) {
                    item?.infos.forEach((val: any) => {
                        base.push(val);
                    });
                }
            });
            // 信息点集合
            this.all = [...data.basicInfos, ...base];
            this.codeToDataSource = {};
            this.all.forEach((item: any) => {
                if (item.dataSource) {
                    try {
                        this.codeToDataSource[item.code] = {};
                        item.dataSource.forEach((dic: any) => {
                            this.codeToDataSource[item.code][dic.code] = dic.name;
                        });
                    } catch (e) {
                        console.log(e);
                    }
                }
            });
            return {
                basicInfos: {
                    name: "基础信息台账",
                    data: data.basicInfos,
                },
                dictStages: {
                    name: this.currentHeader,
                    data: base,
                },
            };
        } else {
            return {};
        }
    }

    /**
     * 切换设备类型
     */
    private handleChangeDevice() {
        this.getEquipData();
    }

    /**
     * 检索设备关键字
     */
    private searchValue(val: string) {
        this.keyWord = val;
        this.getExampleData();
    }

    /**
     * 切换页码
     */
    private handleCurrentChange(val: number) {
        this.paginationList.page = val;
        this.getExampleData();
    }

    /**
     * 切换每页显示数量
     */
    private handleSizeChange(val: number) {
        this.paginationList.size = val;
        this.getExampleData();
    }
}
</script>
<style lang="scss" scoped>
.tab-content {
    height: 100%;
    border: 1px solid #e1e7ea;
    border-top: none;
    padding-bottom: 12px;

    .search {
        padding: 12px;
        & > .item {
            margin-right: 12px;
        }
    }
}
// 数据暂未
.void {
    margin-top: 200px;
}
.align {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    flex-wrap: wrap;
}
</style>