<template>
    <div class="adm-device">
        <statistics :statistics-msg="statisticsMsg"/>
        <div class="operation">
            <el-cascader :options="list" clearable v-model="deviceType" :props="optionProps" @change="changeLinshi"
                         class="adm-select"></el-cascader>
            <admSearch @SearchValue="SearchValue"/>
            <el-button type="default" @click="addDevice" class="adm-btn">添加设备</el-button>
        </div>
        <div class="hr"></div>
        <div class="content">
            <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
                <el-tab-pane v-for="(item,index) in paneMsg" :key="index" :label="item" :name="index.toString()"/>
            </el-tabs>
            <div class="table" v-loading="loading">
<!--                <template v-if="deviceType">-->
                <template v-if="deviceType.length > 0">
                    <admMultiTable :currentHeader="currentHeader" :tableData="tableData" :headersStage="headersStage"/>
                    <Pagination v-if="tableData.length > 0" :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>
        <!--        添加/编辑 设备-->
        <el-dialog
            :title="deviceMsg"
            :visible.sync="dialogVisible"
            @close="close"
        >
            <template v-if="next">
                <div class="align" style="height: 400px">
                    <span class="text ">设备类别</span>
                    <el-cascader :options="list" clearable v-model="deviceVal" @change="changeLinshi"
                                 :props="optionProps"
                                 class="adm-select"></el-cascader>

                </div>
                <el-button type="primary" class="fr" @click="handleNext">下一步</el-button>
            </template>
            <template v-else-if="displayLocation && deviceVal">
                <el-button type="primary" class="fr ml-10">保存</el-button>
                <el-button type="default" class="fr ml-10">取消</el-button>
                <el-button type="default" class="fr ml-10">重置</el-button>
            </template>
            <template v-else>
                <dataForm :dataFormList="dataFormList"/>
                <el-button type="primary" class="fr ml-10">确定</el-button>
                <el-button type="default" class="fr" @click="handlePosition">维护位置</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { AdmMultiTable, AdmSearch, dataForm, Pagination, Statistics } from '../components/index'
import { allDevice, BeatchQueryParam, dictInfo } from "@/api/equipComponent";
import { queryCount, queryEquip } from "@/api/datacenter";
import { UserModule } from "@/store/modules/user";
import tools from "@/utils/maintain"


@Component({
    name: 'adm-device',
    components: { Statistics, AdmSearch, AdmMultiTable, Pagination, dataForm }
})
export default class extends Vue {
    optionProps = {
        value: 'code',
        label: 'name',
        children: 'children'
    }

    // loading
    loading = false
    // 统计信息对象
    private statisticsMsg = {
        title: '全部设备',
        total: 0

    }
    // 设备类值
    deviceType = ''
    // 弹窗设备类值
    deviceVal = ''
    // 维护位置
    displayLocation = false
    // 表头信息集合
    headerInformation = {}
    // 表头阶段信息结合
    headersStage = {}
    // 当前阶段表头信息点集合
    all = []
    // 搜索内容
    inputSearch = ''
    // 下拉数据
    list = []
    // 弹窗开关
    private dialogVisible = false
    // tabs数据
    private paneMsg = ['设计阶段维护', '施工阶段维护', '运维阶段维护']
    // 当前tabs值
    private activeName = ""
    // 分页
    private paginationList = {
        page: 1,
        size: 50,
        sizes: [10, 30, 50, 100, 150, 200],
        total: 0
    }
    // 下一步
    private next = true
    // 弹窗 title
    private deviceMsg = '添加设备'
    // 默认当前阶段
    private currentHeader = this.paneMsg[0]
    // 主体数据
    private tableData = []
    codeToDataSource = {}

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

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

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

// 设备类数据
    deviceList() {
        allDevice({}).then(res => {
            this.list = res.content
            console.log(res)
        })
    }


    // todo 临时假数据函数
    private changeLinshi(val) {
        console.log(this.deviceType, this.deviceType[1])
        if (this.deviceType[1]) {
            this.loading = true
            let param = {
                category: this.deviceType[1]
            }
            let param2 = {
                filters: this.deviceType[1] ? `classCode='${ this.deviceType[1] }'` : undefined,
                pageNumber: this.paginationList.page,
                pageSize: this.paginationList.size,
                orders: "createTime desc, id asc",
                projectId: this.projectId
            }
            if (this.inputSearch != '') {
                param2.filters += `;codeName contain '${ this.inputSearch }' or systemCategory contain '${ this.inputSearch }' or bimTypeId contain '${ this.inputSearch }' or localId contain '${ this.inputSearch }'`
            }
            let promise = new Promise(resolve => {
                dictInfo(param).then(res => {
                    resolve(res)
                })
            })
            let promise2 = new Promise(resolve => {
                queryEquip(param2).then(res => {
                    resolve(res)
                })
            })
            Promise.all([promise, promise2]).then(res => {
                this.loading = false
                // 类型下信息点,默认设计阶段
                this.headerInformation = res[0] // 获取表头
                this.tableData = res[1].content // 主体数据
                this.headerStage()
                this.paginationList.total = res[1].total
            })
        } else {
            this.headerInformation = {}
        }
    }
    private handleFilter(val) {
        console.log(this.deviceType)
        if (this.deviceType) {
            this.loading = true
            let param = {
                category: this.deviceType
            }
            let param2 = {
                filters: this.deviceType ? `classCode='${ this.deviceType }'` : undefined,
                pageNumber: this.paginationList.page,
                pageSize: this.paginationList.size,
                orders: "createTime desc, id asc",
                projectId: this.projectId
            }
            if (this.inputSearch != '') {
                param2.filters += `;codeName contain '${ this.inputSearch }' or systemCategory contain '${ this.inputSearch }' or bimTypeId contain '${ this.inputSearch }' or localId contain '${ this.inputSearch }'`
            }
            let promise = new Promise(resolve => {
                dictInfo(param).then(res => {
                    resolve(res)
                })
            })
            let promise2 = new Promise(resolve => {
                queryEquip(param2).then(res => {
                    resolve(res)
                })
            })
            Promise.all([promise, promise2]).then(res => {
                this.loading = false
                // 类型下信息点,默认设计阶段
                this.headerInformation = res[0] // 获取表头
                this.tableData = res[1].content // 主体数据
                this.headerStage()
                this.paginationList.total = res[1].total
            })
        } else {
            this.headerInformation = {}
        }
    }

    headerStage() {
        let header = []
        if (Object.keys(this.headerInformation).length > 0) {
            this.headerInformation.dictStages.forEach(item => {
                if (this.currentHeader == item.name) {
                    item.infos && item.infos.forEach(val => header.push(val))
                    // item.infos && item.infos.forEach(val => {
                    //     val.name = val.unit ? `${ val.name }(${ val.unit })` : val.name
                    //     header.push(val)
                    // })
                }
            })
        }
        this.headersStage = {
            basicInfos: {
                name: '基础信息台账',
                data: this.headerInformation.basicInfos
            },
            dictStages: {
                name: this.currentHeader,
                data: header
            }
        }
        // 信息点集合
        this.all = [...this.headerInformation.basicInfos, ...header]
        this.codeToDataSource = {}
        this.all.forEach(item => {
            if (item.dataSource) {
                try {
                    this.codeToDataSource[item.code] = {}
                    item.dataSource.forEach(dic => {
                        this.codeToDataSource[item.code][dic.code] = dic.name;
                    })
                } catch (e) {
                    console.log(e);
                }
            }
        });
        this.getBatch(this.tableData)
    }

    // 查询动态数据
    getBatch(data) {
        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
                                        );
                                    }
                                });
                            }
                        }
                    })
                    return item
                })
            })
        }
    }

    // 维护阶段 tabs
    async handleClick(val: any) {
        this.currentHeader = val.label
        await this.headerStage()

    }


    //设备类筛选
    selectValue(val: string) {
        console.log(val, 3)

    }

    // 搜索
    SearchValue(val: string) {
        this.inputSearch = val
        // this.handleFilter(this.deviceType)
        this.changeLinshi(this.deviceType[1])
    }

    // 当前分页
    handleCurrentChange(val: number) {
        console.log(val)
        this.paginationList.page = val
        // this.handleFilter(this.deviceType)
        this.changeLinshi(this.deviceType[1])
    }

    handleSizeChange(val: number) {
        this.paginationList.size = val
        // this.handleFilter(this.deviceType)
        this.changeLinshi(this.deviceType[1])
    }

    // 添加设备
    addDevice() {
        this.dialogVisible = true
    }

    //下一步事件
    handleNext() {
        if (this.deviceVal) {
            this.next = false
        }
    }

    // 维护位置
    handlePosition() {
        this.displayLocation = true
    }

    // close
    close() {
        this.next = true
        this.displayLocation = false
    }
}
</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;
}

.adm-device {
    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-bottom: 16px;
    }

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

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

            .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>
.data-form {
    height: 430px;
}

.text {
    color: #000000;
    margin-bottom: 10px;

}

.el-tabs__header {
    margin: 0;
}

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

.fl {
    float: left;
}

.fr {
    float: right;
}

.el-dialog__body {
    overflow: hidden;
}

.ml-10 {
    margin-left: 10px;
}
</style>
