<template>
    <div class="adm-system">
        <statistics :statistics-msg="statisticsMsg"/>
        <div class="hr"></div>
        <div class="operation">
            <el-cascader :options="list" ref="floorCascader" clearable v-model="systemType" :props="optionProps"
                         @change="changeSystemList"
                         class="adm-select"></el-cascader>

            <admSearch @SearchValue="SearchValue"/>
            <el-button class="adm-btn" type="default" @click="addDevice">添加系统</el-button>
        </div>

        <div class="content">
            <div v-loading="loading" class="table">
                <template v-if="systemType.length > 0">
                    <admMultiTable
                        @handleCurrentEdit="handleCurrentEdit"
                        :currentHeader="currentHeader"
                        :headersStage="headersStage"
                        :tableData="tableData"/>
                    <Pagination
                        :paginationList="paginationList"
                        @handleCurrentChange="handleCurrentChange"
                        v-if="tableData.length > 0"
                        @handleSizeChange="handleSizeChange"
                    />
                </template>
                <div v-else class="void align">
                    <svg-icon :height="String(123)" :width="String(120)" name="void"/>
                    <p class="void-title">暂无内容</p>
                    <p class="void-tips">可点击左上角选择系统类型</p>
                </div>
            </div>
        </div>
        <!--        添加/编辑 系统-->
        <el-dialog
            :title="systemMsg"
            :width="!isWidth ? '20%':''"
            :visible.sync="dialogVisible"
            @close="close">
            <template v-if="next">
                <div class="align" :style="{ 'height': isWidth ? '400px':'200px' }">
                    <span class="text">系统类别</span>
                    <el-cascader :options="list" clearable v-model="systemVal"
                                 :props="optionProps"
                                 class="adm-select"></el-cascader>
                </div>
                <el-button class="fr" type="primary" @click="handleNext">下一步</el-button>
            </template>

            <template v-else>
                <baseDataForm :objectHeaders="systemHeaders"
                              :currRowContent="currRowContent"
                              ref="baseDataForm"
                />
                <span slot="footer" class="dialog-footer">
                         <el-button type="primary" @click="handleDataForm">完成</el-button>
                         <el-button @click="dialogVisible = false">取消</el-button>
                    </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";
import { AdmMultiTable, AdmSearch, baseDataForm, Pagination, Statistics } from "../components/index";
import { createSystem, dictQuery, queryCountSystem, querySystem, updateSystem } from "@/api/datacenter";
import tools from "@/utils/maintain";
import { UserModule } from "@/store/modules/user";
import { allSystem, BeatchQueryParam } from "@/api/equipComponent";

@Component({
    name: "adm-system",
    components: { Statistics, AdmSearch, AdmMultiTable, Pagination, baseDataForm },
})
export default class extends Vue {
    optionProps = {
        value: 'code',
        label: 'name',
        children: 'children'
    }
    // 设置高度
    isWidth = false
    // loading
    loading = false;
    // 下拉数据
    list = [];
    // 信息点集合（表头）
    all = [];
    codeToDataSource: any = {};
    // 系统类值
    systemType = "";
    // 系统名称 label值
    systemLabel = "";
    systemVal = "";
    currentHeader = "运维阶段";
    tableData = [];
    // 表头阶段信息结合
    headersStage = {};
    // 当前行数据
    currRowContent = {}
    // 统计信息对象
    statisticsMsg = {
        title: "全部系统",
        total: 0,
    };
    // 分页
    paginationList = {
        page: 1,
        size: 50,
        sizes: [10, 30, 50, 100, 150, 200],
        total: 0,
    };
    // 下一步
    next = true;
    // 弹窗 title
    systemMsg = "添加系统";
    // 弹窗开关
    dialogVisible = false;
    // 搜索内容
    inputSearch = "";
    systemHeaders = {}

    // 项目id
    get projectId(): string {
        return UserModule.projectId;
    }

    created() {
        this.systemList();
        this.dataCount();
    }

    //查询统计数量
    dataCount() {
        queryCountSystem({}).then((res) => {
            this.statisticsMsg.total = res.count;
        });
    }

    systemList() {
        allSystem({}).then((res) => {
            this.list = res.content;
        });
    }

    // 动态信息点
    getBatch(data: any) {
        let param = {
            groupCode: "WD",
            appId: "datacenter",
            projectId: this.projectId,
            data: [],
        };
        this.all.forEach((head) => {
            if (head.category != "STATIC") {
                data.forEach((item) => {
                    let cur = tools.dataForKey(item, head.path);
                    if (cur) {
                        param.data.push({
                            objectId: item.id,
                            infoCode: head.code,
                        });
                    }
                });
            }
        });
        if (param.data.length > 0) {
            BeatchQueryParam(param).then((res) => {
                this.tableData = data.map((item) => {
                    res.data.map((child) => {
                        if (item.id == child.objectId) {
                            if (!!child.data || child.data == 0) {
                                this.all.map((head) => {
                                    if (head.code == child.infoCode) {
                                        let contentVal = child.data;
                                        if (this.codeToDataSource[child.infoCode]) {
                                            contentVal = this.codeToDataSource[child.infoCode][child.data];
                                        }
                                        tools.setDataForKey(item, head.path, contentVal);
                                    }
                                });
                            } else {
                                this.all.map((head) => {
                                    if (head.code == child.infoCode) {
                                        tools.setDataForKey(item, head.path, child.error ? child.value
                                            ? "表号功能号格式错误"
                                            : "表号功能号不存在"
                                            : "暂未采集到实时数据");
                                    }
                                });
                            }
                        }
                    });
                    return item;
                });
            });
        }
    }

    // 搜索
    SearchValue(val: string) {
        this.inputSearch = val;
        this.changeSystemList()
    }

    // 当前分页
    handleCurrentChange(val: number) {
        this.paginationList.page = val;
        this.changeSystemList()
    }

    handleSizeChange(val: number) {
        this.paginationList.size = val;
        this.changeSystemList()
    }

    // 添加设备
    addDevice() {
        this.systemMsg = '添加系统'
        this.currRowContent = {}
        this.dialogVisible = true;
    }

    //下一步事件
    async handleNext() {
        if (this.systemVal[1]) {
            this.next = false
            this.isWidth = true
            let param = {
                type: this.systemVal[1],
                orders: "sort asc, name desc",
            };

            await dictQuery(param).then((res: any) => {
                const { basicInfos, dictStages } = this.informationArrangement(res.content);
                // 添加系统分类
                dictStages.map((item: any) => {
                    item = { ...item, classification: this.systemLabel };
                    return item;
                });
                this.systemHeaders = {
                    basicInfos: {
                        name: "基础信息台账",
                        data: basicInfos,
                    },
                    dictStages: {
                        name: "运维阶段",
                        data: dictStages,
                    },
                };
            })
        } else {
            console.log(5)
        }
    }

    // close
    close() {
        if (this.systemType) {
            this.systemVal = this.systemType
        } else {
            this.systemVal = ''
        }
        this.next = true;
        this.isWidth = false
    }

    // 编辑当前行
    handleCurrentEdit(val: any) {
        this.next = false
        this.systemMsg = '编辑系统'
        this.currRowContent = val
        this.systemHeaders = this.headersStage;
        this.dialogVisible = true
    }

    //信息点重组
    informationArrangement(arr: []): any {
        let basicInfos = [{ path: "classification", name: "系统分类" }],
            dictStages: any[] = [];
        this.all = arr;
        arr.forEach((item: any) => {
            let i = ["localName", "localId"];
            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);
                }
            }
            if (i.includes(item.path)) {
                basicInfos.push(item);
            } else {
                dictStages.push(item);
            }
        });
        return {
            basicInfos,
            dictStages
        }
    }

    changeSystemList() {
        if (this.systemType[1]) {
            let systemLabel = this.$refs["floorCascader"].getCheckedNodes()[0].pathLabels;
            this.systemLabel = systemLabel[1];
            this.loading = true;
            let param = {
                type: this.systemType[1],
                orders: "sort asc, name desc",
            };
            let param2 = {
                filters: this.systemType[1] ? `classCode='${ this.systemType[1] }'` : undefined,
                pageNumber: this.paginationList.page,
                pageSize: this.paginationList.size,
                orders: "createTime desc, id asc",
                projectId: this.projectId,
            };
            if (this.inputSearch != "") {
                param2.filters = `localName contain '${ this.inputSearch }' or localId contain '${ this.inputSearch }'`;
            }
            let promise = new Promise((resolve) => {
                dictQuery(param).then((res) => {
                    resolve(res);
                });
            });
            let promise2 = new Promise((resolve) => {
                querySystem(param2).then((res) => {
                    resolve(res);
                });
            });
            Promise.all([promise, promise2]).then((res) => {
                let tableData = [];
                this.loading = false;
                // 类型下信息点,重组数据
                let { basicInfos, dictStages } = this.informationArrangement(res[0].content)
                this.headersStage = {
                    basicInfos: {
                        name: "基础信息台账",
                        data: basicInfos,
                    },
                    dictStages: {
                        name: "运维阶段",
                        data: dictStages,
                    },
                };
                this.paginationList.total = res[1].total;
                tableData = res[1].content; // 主体数据
                // 添加系统分类
                this.tableData = tableData.map((item) => {
                    item = { ...item, classification: this.systemLabel };
                    return item;
                });
                this.getBatch(this.tableData);
            });
        } else {
            console.log("void");
        }
    }

    // 添加/编辑 事件处理
    async handleDataForm() {
        this.$refs.baseDataForm.submitForm(this.handleDataFormSave)

    }

    handleDataFormSave() {
        let from = tools.formatData(this.$refs.baseDataForm.form)
        //编辑
        if (Object.keys(this.currRowContent).length > 0) {
            let param = {
                content: [from]
            }
            updateSystem(param).then(res => {
                res.result == 'success' && this.$message.success('更新成功')
                this.dialogVisible = false
                setTimeout(() => this.changeSystemList())
            })
        } else {
            //添加
            from = {
                ...from,
                classCode: this.systemVal[1]
            }
            let param = {
                content: [from]
            }
            createSystem(param).then(res => {
                res.result == 'success' && this.$message.success('添加成功')
                this.dialogVisible = false
                this.changeSystemList()
            })
        }
    }

    @Watch("systemType", { immediate: true, deep: true })
    handleDeviceMsg() {
        this.systemVal = this.systemType
    }
}
</script>

<style lang="scss" scoped>
$margin: 12px;
$border: 1px solid #e1e7ea;
.align {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    flex-wrap: wrap;

    .text {
        margin-right: 150px;
        margin-bottom: 10px;
    }
}

.adm-system {
    background: #fff;
    padding: 12px;
    height: 100%;

    .operation {
        margin: 12px 0;

        .adm-select {
            margin-right: $margin;
        }

        .adm-btn {
            float: right;
        }
    }

    .hr {
        background: #e1e7ea;
        color: #e1e7ea;
        width: 100%;
        height: 1px;
        margin: 15px 0;
    }

    .content {
        position: relative;
        height: calc(100% - 142px);

        .table {
            //border-left: $border;
            //border-right: $border;
            //border-bottom: $border;
            height: calc(100% - 41px);
            padding: 12px;

            .void {
                margin-top: 200px;
            }

            .void-title {
                color: #333333;
                line-height: 21px;
                font-size: 16px;
            }

            .void-tips {
                color: #9ca1a9;
                line-height: 22px;
                font-size: 14px;
            }
        }

        .adm-multi-table {
        }
    }

    .adm-pagination {
        right: 10px;
        position: absolute;
        bottom: 10px;
    }
}
</style>
<style lang="scss">
.adm-system {

    .el-dialog {
        .el-dialog__body {
            padding: 20px;
            max-height: 550px !important;
            min-height: 100px;
            overflow-y: auto;
            overflow-x: hidden;
        }
    }

    .el-select, .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 100%;
    }

    .el-dialog__header {
        border-bottom: 1px solid #D8D8D8;
    }

    .fr {
        float: right;
    }
}
</style>
