<template>
    <div class="container">
        <div class="title_top">
            <div class="title_name" @click="handleHome">
                {{ this.$dictLabel('node_title3') }}
            </div>
        </div>

        <leftNav selNavId="3" />


        <div class="matrix_box">
            <div class="model_box" id="webgl"></div>
            <div class="but_1" @click="handleMatrix"></div>
        </div>
        <div class="checklist_box">
            <div class="text_gradual title"> 清单 </div>
            <div class="head_but">
                <!-- <span></span> -->
                <div class="but_classify">
                    <div class="but" @click="handleAllDel">批量删除</div>
                    <div class="but" @click="handleAdd">添加数据</div>
                    <!-- <div class="but" @click="handletab(v, k)">批量删除</div> -->
                </div>
                <div class="but_classify">
                    <div :class="{but:true, sel_but: selTab == k}" v-for="(v,k) in tabList" @click="handletab(v,k)">{{ v
                        }}</div>
                </div>
            </div>
            <div class="table_box" v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.6)">
                <el-table :data="dataList" height="100%" stripe style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="70" align="center">
                    </el-table-column>
                    <el-table-column prop="destination" label="信宿" align="center">
                        <!-- <template slot-scope="{row}">
                            <el-input v-if="row.status != 1" v-model="row.destination" placeholder="请输入信宿" clearable />
                            <span v-else>{{ row.destination }}</span>
                        </template> -->
                    </el-table-column>
                    <el-table-column prop="type" label="信息类型" align="center">
                        <!-- <template slot-scope="{row}">
                            <el-input v-if="row.status != 1" v-model="row.stock_num" placeholder="请输入信息类型" clearable />
                            <span v-else>{{ row.type }}</span>
                        </template> -->
                    </el-table-column>
                    <el-table-column prop="source" label="信源" align="center">
                        <!-- <template slot-scope="{row}">
                            <el-input v-if="row.status != 1" v-model="row.stock_num" placeholder="请输入信源" clearable />
                            <span v-else>{{ row.source }}</span>
                        </template> -->
                    </el-table-column>
                    <!-- <el-table-column label="校核" align="center">
                        <template slot-scope="{ row }">
                            <span v-if="row.status == 1">已保存</span>
                            <el-button v-else class="but_3" size="small" @click="handleSave(row)">保存</el-button>
                        </template>
                    </el-table-column> -->
                    <el-table-column prop="sign" label="校核标识" align="center">

                    </el-table-column>
                    <el-table-column prop="format" label="格式标准" align="center">
                        <!-- <template slot-scope="{row}">
                            <el-input v-if="row.status != 1" v-model="row.stock_num" placeholder="请输入格式标准" clearable />
                            <span v-else>{{ row.format }}</span>
                        </template> -->
                    </el-table-column>
                </el-table>
            </div>
        </div>

        <el-dialog custom-class="cell_dia" title="添加数据" :visible.sync="dialogVisible">
            <el-form :model="form" ref="ruleForm" class="demo-ruleForm">
                <el-form-item label="信宿" prop="destination">
                    <el-input v-model="form.destination" placeholder="请输入信宿"></el-input>
                </el-form-item>
                <el-form-item label="信息类型" prop="type">
                    <el-input v-model="form.type" placeholder="请输入信息类型"></el-input>
                </el-form-item>
                <el-form-item label="信源" prop="source">
                    <el-input v-model="form.source" placeholder="请输入信源"></el-input>
                </el-form-item>
                <el-form-item label="校核标识" prop="sign">
                    <el-input v-model="form.sign" placeholder="请输入校核标识"></el-input>
                </el-form-item>
                <el-form-item label="格式标准" prop="format">
                    <el-input v-model="form.format" placeholder="请输入格式标准"></el-input>
                </el-form-item>
                <el-form-item label="信宿类型" prop="dataType">
                    <el-select v-model="form.dataType" placeholder="请选择信宿类型">
                        <el-option v-for="(v,k) in tabList" :key="v" :label="v" :value="v"></el-option>
                    </el-select>
                    <!-- <el-input v-model="form.dataType" placeholder="请输入数据类型"></el-input> -->
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <div class="but_save" @click="submitForm('ruleForm')"></div>
                <!-- <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button> -->
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { drawAxes } from "@/utils/three.js";
import { taskData, statistics, lastData, updateData, dataAdd, dataRemove } from "@/api/bigScreen/api.js";
import { connectWebsocket, closeWebsocket } from "@/utils/websocket.js";
export default {
    name: 'Matrix',
    props: {

    },
    components: {

    },
    data(){
        return {
            dialogVisible: false,  //  弹窗
            butLoading: false,
            loading: false,
            tabList: [
                this.$dictLabel('node_sub_title9'), 
                this.$dictLabel('node_sub_title10'), 
                this.$dictLabel('node_sub_title11'), 
                this.$dictLabel('node_sub_title12')],
            selTab: 0,
            queryParams: {
                pageNum: 1,
                pageSize: 1000,
                taskId: '',
                status: '',
                dataType: this.$dictLabel('node_sub_title9'),
            },
            dataList: [],
            saveList: [],  //  已保存的数据
            selectionList: [],  //  表格选中的数据
            taskId: '',  //  任务id
            demo1: null,
            sizeX: 0,
            sizeY: 0,
            sizeZ: 0,
            data: [], //  点位数据 列表
            destinationStats: [],  //  信宿
            sourceStats: [],  //  信源
            typeStats: [],  //  分类
            labels_left: [],   //  z 轴 名称
            labels_back: [],  //  x 轴 名称
            typeList: [],  //  y 轴 分类名称


            form:{},  //  表单数据

            // tableColumn: [],
        }
    },
    computed: {
        // 表格勾选
        ids() {
            let ids = [];
            this.selectionList.forEach(ele => {
                ids.push(ele.id);
            });
            return ids.join(",");
        }
    },
    created() {
        if (this.$route.query && this.$route.query.id) {
            this.taskId = this.$route.query.id
        }
        
        // this.getStatistics()

    },
    async mounted() {
        if (!this.taskId) {
            this.initHome()
        } else {
            this.init() 
            this.getList();
        }
        

    },
    beforeDestroy() {
        // closeWebsocket()
        if (this.demo1) {
            this.demo1.dispose()
        }
    },
    methods: {
        async init(){
            //  获取信宿、信源、信息类型数据统计  ==>>  获取 3d模型 三维大小
            let res = await statistics({ taskId: this.taskId })
            // debugger
            if (res.code == 0) {
                this.destinationStats = res.data.destinationStats   //  信宿
                this.typeStats = res.data.typeStats  //  分类   
                this.sourceStats = res.data.sourceStats   //   信源
            }
            
            let query = {
                pageNum: 1,
                pageSize: 1000,
                taskId: this.taskId,
                // status: '1',
            }
            let respone = await taskData(query)
            if (respone.code == 0) {
                this.saveList = respone.rows
            }

            this.sizeX = this.destinationStats.length   //  信宿
            this.sizeY = this.typeStats.length  //  分类   
            this.sizeZ = this.sourceStats.length  //   信源

            // console.log(this.typeList, 'this.typeList');

            this.labels_back = this.destinationStats.map(el => { return el.name })
            this.labels_left = this.sourceStats.map(el => { return el.name })
            this.typeList = this.typeStats.map(el => { return el.name })
            this.labels_left.unshift('')
            this.labels_back.unshift('')

            this.data = []
            this.typeList.forEach(el => {
                this.data.push({
                    name: el,
                    point: []
                })
            })
            
            this.data.forEach((el, index) => {
                this.saveList.forEach(el2 => {

                    if (el.name == el2.type) {
                        // console.log(this.labels_back);

                        let x = this.labels_back.indexOf(el2.destination)
                        let z = this.labels_left.indexOf(el2.source)
                        let y = this.typeList.indexOf(el2.type)

                        const yHeight = this.typeList.length * 10
                        let axisY = yHeight - y * 10

                        
                        let pointDetail = {
                            id: el2.id,
                            pointData: [x * 10, axisY, z * 10]
                        }
                        el.point.push(pointDetail)

                        const pointRoot = [x * 10, axisY, 0]
                        let falg = el.point.some(item => item.pointData[0] == pointRoot[0] && item.pointData[1] == pointRoot[1] && item.pointData[2] == pointRoot[2])
                        let pointRootDetail = {
                            id: el2.destination + el2.type,
                            pointData: pointRoot
                        }
                        
                        if (!falg) {
                            el.point.push(pointRootDetail)
                        }
                    }
                })
            })


            // const letterList = JSON.parse(JSON.stringify(this.letterList))
            const sceneBox = document.getElementById('webgl');

            const options = {
                gridSize: { x: this.sizeX * 10, y: this.sizeY * 10, z: this.sizeZ * 10 }, // 三维网格尺寸
                // gridSize: { x: 100, y: 100, z: 100 }, // 三维网格尺寸
                grid_uv_back: [this.sizeX, this.sizeY],  //  [z,y]
                grid_uv_left: [this.sizeZ, this.sizeY],  //  [x,y]
                show_water: true, // 是否显示水面
                water_height: 5, // 水面厚度
                data: this.data,
                labels_left: this.labels_left,  //  x
                labels_back: this.labels_back,  //  z
                labels_height: this.typeList,
            };

            //   scene, camera, renderer, dispose 
            this.demo1 = drawAxes(sceneBox, options, (falg, val) => {
                // console.log(falg, val, 'ppppppppppppppp');

            })
        },
        async initHome() {
            let res = await lastData()
            if (res.code == 0) {
                this.taskId = res.data.list[0].taskId
                this.init() 
                this.getList();
            }
        },
        //  获取数据列表
        async getList() {
            this.queryParams.taskId = this.taskId
            this.loading = true
            let res = await taskData(this.queryParams)
            if (res.code == 0) {
                this.dataList = res.rows
                this.total = res.total
                this.loading = false
            }
        },
        //  获取信宿、信源、信息类型数据统计  ==>>  获取 3d模型 三维大小
        async getStatistics() {
            let res = await statistics({taskId: 3})
            if (res.code == 0) {
                this.sizeZ = res.destinationStats.length   //  信宿
                this.sizeY = res.typeStats.length  //  分类   
                this.sizeX = res.sourceStats.length   //   信源
            }
        },
        
        //  添加数据
        handleAdd(){
            this.form = {}
            this.dialogVisible = true
        },
        //  保存
        submitForm(formName) {
            if (this.butLoading) return;
            this.butLoading = true
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    this.form.taskId = this.taskId
                    this.form.status =  '1'
                    let res = await dataAdd(this.form) 
                    if (res.code == 0) {
                        this.butLoading = false
                        this.getList()
                        // let respone = await taskData(query)
                        // if (respone.code == 0) {
                        //     this.saveList = respone.rows
                        // }
                        this.demo1.dispose()
                        this.init() 
                        this.dialogVisible = false
                        // this.demo1.addPoint(el.name, pointRoot, index);
                    }
                } else {
                    // console.log('error submit!!');
                    this.butLoading = false
                    return false;
                }
            });
        },

       
        //  表格勾选
        handleSelectionChange(val){
            this.selectionList = val;
        },
        //  批量 删除
        async handleAllDel() {
            if (this.ids.length == 0) {
                this.$modal.msgWarning("请选择数据！")
                return
            }
            let res = await dataRemove({ids: this.ids})
            if (res.code == 0) {
                this.$modal.msgSuccess("删除成功")
                this.getList()
                this.demo1.dispose()
                this.init()
                // this.demo1.addPoint(el.name, pointRoot, index);
            }
            // this.$modal.confirm('是否确认删除名称为"' + row.title + '"的数据项？').then(() => {
            //     return dataRemove({ ids: this.ids })
            // }).then(() => {
            //     this.getList()
            //     this.demo1.dispose()
            //     this.init()
            //     this.$modal.msgSuccess("删除成功")
            // }).catch(() => { })
        },
        //  批量保存
        async hansleAllSave(){
            if (this.selectionList.length == 0) {
                this.$modal.msg("请选择数据");
                return 
            }
            let flag = this.selectionList.some(el => el.status == 1)
            if (flag) {
                this.$modal.msg(`请全部选择状态为未保存的数据`);
                return
            }
            let formList = this.selectionList.map(el => {
                return {
                    ...el,
                    status: 1
                }
            })
            let res = await batchSave(formList)
            if (res.code == 0) {
                // this.data.forEach((el, index) => {
                //     this.selectionList.forEach(el2 => {
                //         if (el.name == el2.type) {
                //             let x = this.labels_back.indexOf(el2.destination)
                //             let z = this.labels_left.indexOf(el2.source)
                //             let y = this.typeList.indexOf(el2.type)
    
    
                //             // 动态添加单个点位
                //             const pointData = [x * 10, y * 10 + 10, z * 10]
                //             el.point.push(pointData)
                //             this.demo1.addPoint(el.name, pointData, index);
    
                //             let pointRoot = [x * 10, y * 10+10, 0]
                //             let falg = el.point.some(item => item[0] == pointRoot[0] && item[1] == pointRoot[1] && item[2] == pointRoot[2])
                //             // console.log(falg);

                //             if (!falg) {
                //                 el.point.push(pointRoot)
                //                 this.demo1.addPoint(el.name, pointRoot, index);
                //             }
                            
                //         }

                //     })
                // })
                this.getList()
                this.$modal.msgSuccess("操作成功");
            }
        },
        //  矩阵生成
        async handleMatrix(){
            if (this.butLoading) return;
            this.butLoading = true
            let query = {
                pageNum: 1,
                pageSize: 100,
                taskId: this.taskId,
                status: '',
                dataType: ''
            }
            let res = await taskData(query)
            if (res.code == 0) {
                this.butLoading = false
                const data = res.rows
                let dataList = []
                dataList = data.map((el)=> {
                    return {
                        id: el.id,
                        destination: el.destination,
                        destinationId: el.destinationId,
                        source: el.source,
                        sourceId: el.sourceId,
                        type: el.type,
                        typeId: el.typeId,
                    }
                })
                const sendDataObj = {
                    dataList: dataList,
                }
                // const dataObjJSON = JSON.stringify(dataObj) 
                this.toform(sendDataObj)
                // this.updateWebsoctData(sendDataObj)
                console.log(sendDataObj);
                

                this.$router.push('/homeIndex')
            }
        },
        toform(sendDataObj) {  //插件选中窗口回调
            const websocketUrl = 'ws://48.2.16.137:8666/TBDD/websocket'
            // const websocketUrl = 'ws://192.168.1.25:8000/api/ws'
            connectWebsocket(
                websocketUrl,
                sendDataObj, // 初始化数据
                (data) => {
                    console.log("前端websocket接受的数据", data);
                    const dataObj = JSON.parse(data)
                    this.updateWebsoctData(dataObj)
                },
                (event) => {
                    console.log("关闭的回调函数", event);
                    closeWebsocket()
                },
                (err) => {
                    console.log("失败的回调函数", err);
                    closeWebsocket()
                }
            );



            // // console.log('windowSelect callback: ', iWndIndex);
            // window.parent.postMessage({
            //     action: 'selWndId',
            //     msg: '子页面通知父页面',
            //     info: dataList
            // }, '\*')  
        },
        //  websocket 向后端 回传
        async updateWebsoctData(dataObj){
            let res = await updateData(dataObj)
        },
        //  分类 标签 选择s
        handletab(v,k){
            if (this.selTab == k) return;
            this.selTab = k
            this.queryParams.dataType = v
            this.getList();
        },
        handleHome(){
            this.$router.push('/home')
        }
    }
}
</script>

<style lang="scss" scoped>
.container{
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 20px;
    padding-left: 60px;
    .matrix_box{
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        .model_box{
            // width: 600px;
            width: 700px;
            height: 663px;
            // background-color: #0857ac;
        }
        .but_1{
            margin-top: 20px;
            width: 180px;
            height: 59px;
            background-image: url('~@/assets/bigScreen/task/but_matrix.png');
            background-repeat: no-repeat;
            background-position: -40px -40px;
            background-size: 260px 140px;
            cursor: pointer;
        }
    }
    .checklist_box{
        margin-left: 30px;
        padding: 60px 50px;
        // width: 964px;
        width: 1000px;
        // height: 834px;
        height: 88%;
        // background-color: red;
        background-image: url('~@/assets/bigScreen/task/img_bg_1.png');
        background-repeat: no-repeat;
        // background-position: -18px -38px;
        // background-size: 1000px 111%;
        background-size: 100% 100%;
        .title{
            text-align: center;
            font-weight: bold;
            font-size: 20px;
        }
        .head_but{
            margin-top: 25px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .but_2{
                color: #FFFFFF;
                font-size: 18px;
                cursor: pointer;
                margin-right: 15px;
            }
            .but_classify{
                display: flex;
                align-items: center;
                .but{
                    width: 140px;
                    height: 44px;
                    background-image: url('~@/assets/bigScreen/task/tab_bg_1.png');
                    background-repeat: no-repeat;
                    background-size: 100% 100%;
                    color: #FFFFFF;
                    font-size: 18px;
                    text-align: center;
                    line-height: 44px;
                    cursor: pointer;
                }
                .sel_but{
                    background-image: url('~@/assets/bigScreen/task/tab_bg_2.png');
                }
                .but+.but{
                    margin-left: 10px;
                }
            }
        }

        .table_box{
            margin-top: 15px;
            width: 100%;
            // height: 600px;
            height: calc(100% - 105px);
            ::v-deep .el-table{
                font-size: 16px;
                background-color: transparent;
                .el-table__header-wrapper tr{
                    height: 60px;
                    background-color: #003e7f;
                    th{
                        height: 60px;
                        font-size: 16px;
                        background-color: transparent;
                        border: none;
                        color: #FFFFFF90;
                    }
                }
                .el-table__body-wrapper{
                    tr {
                        height: 60px;
                        background-color: #091c43;
                        td{
                            height: 60px;
                            background-color: transparent;
                            border: none;
                            color: #FFFFFF;
                        }
                    }
                    .el-table__row--striped{
                        background-color: #0b2c58;
                    }
                }
                .el-checkbox{
                    .el-checkbox__inner{
                        width: 16px;
                        height: 16px;
                        background-color: transparent;
                        border-color: #FFFFFF40;
                    }
                    .el-checkbox__input.is-checked .el-checkbox__inner{
                        border-color: #FFFFFF40;
                    }
                    .el-checkbox__inner::after{
                        left: 5px;
                    }
                }
                .but_3{
                    background-color: #76d3ff;
                    border: 1px solid #76d3ff;
                    color: #000000;
                    font-size: 14px;
                }
            }
            .el-table::before{
                width: 0;
                height: 0;
            }
        }
    }
    ::v-deep .cell_dia{
        margin-top: 15vh !important;
        width: 500px;
        height: fit-content;
        // width: 713px;
        // height: 628px;
        background-color: #03173D;
        border: 1px solid #017D2D;
        // background-image: url('~@/assets/bigScreen/task/img_bg_4.png');
        // background-repeat: no-repeat;
        // background-size: 713px 628px;
        .el-dialog__title{
            color: #fff;
        }
        .el-form-item {
            // display: flex;

            .el-form-item__label {
                // padding: 0;
                width: 88px !important; 
                font-size: 16px;
                font-weight: 500;
                letter-spacing: 0.1em;
                color: #c0c5d0;
            }
            .el-form-item__content{
                margin-left: 88px !important;
            }
            .el-select{
                width: 100%;
            }
            .el-input__inner {
                font-size: 16px;
                background-color: #13335c;
                border-color: #13335c;
                color: #FFFFFF;
            }
        }
        .dialog-footer{
            display: flex;
            justify-content: center;
        }
        .but_save{
            display: inline-block;
            width: 180px;
            height: 59px;
            background-repeat: no-repeat;
            background-position: -40px -40px;
            background-size: 260px 140px;
            cursor: pointer;
            background-image: url('~@/assets/bigScreen/task/but_sub_2.png');
        }
    }
}
</style>
<style lang="scss">
.el-select-dropdown{
    border-color: #13335c;
}
.el-popper[x-placement^=bottom] .popper__arrow::after{
    border-color: #13335c;
}
.el-select-dropdown__wrap{
    background-color: #13335c;
    .el-select-dropdown__item{
        background-color: #13335c;
        color: #fff;
    }
    .el-select-dropdown__item:hover{
        background-color: #03173D;
    }
}
</style>