<template>
    <div class="ddkz-info">
        <div class="ddkz-info-selection">
            <el-form ref="form" :inline="true" :model="formInfo" class="demo-form-inline">
                <el-form-item>
                    <el-select v-model="formInfo.fromUser" placeholder="请选择公告来源" clearable @change="handleChangeFromUser">
                        <el-option v-for="item in optionsFrom" :key="item" :label="item" :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="formInfo.timeFrame" placeholder="请选择时间间隔" clearable @change="handleChangeTimeFrame">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <img class="goBack" :src="goBack" alt="" @click="goBackFn">
                </el-form-item>
            </el-form>
        </div>
        <div class="ddkz-info-content">
            <div class="info-content-left">
                <div class="everyDayNews" v-for="item in newsList">
                    <div class="everyDayTitle">
                        <div class="circle-light"></div>&emsp;
                        <span v-text="item.time"></span>&emsp;
                    </div>
                    <div class="everyDayNew">
                        <div class="everyTemplate">
                            <div v-for="(item1, index1) in item.news"
                                :class="['everyDayNewCard', 'cardType' + item1.teamInfo.id % 3]">
                                <div class="everyDayNewCardTitle" v-text="item1.title"></div>
                                <div class="everyDayNewCardContent">
                                    <div class="left-everyDayNew" :style="{ width: item1.attachment ? '50%' : '100%' }">
                                        <div class="everyDayNewCardInfo">
                                            <span v-text="item1.time"></span>&emsp;
                                        </div>
                                        <div class="everyDayNewCardInfo">
                                            来自于组：<span class="newsSource" v-text="item1.teamInfo.teamName"></span>；
                                            成员：<span class="newsSource" v-text="item1.from"></span>
                                        </div>
                                        <div class="everyDayNewCardText" v-text="item1.content"></div>
                                    </div>
                                    <div class="right-everyDayNew" v-if="item1.attachment">
                                        <template v-if="item1.type == 'PICTURE'">
                                            <el-image :src="item1.url" :preview-src-list="[item1.url]">
                                            </el-image>
                                        </template>
                                        <template v-else-if="item1.type == 'VIDEO'">
                                            <video :src="item1.url" controls loop>
                                            </video>
                                        </template>
                                        <template v-else-if="item1.type == 'EXCEL'">
                                            <el-image :src="excelImg" @click="showLiterature(item1.attachment)">
                                            </el-image>
                                        </template>
                                        <template v-else-if="item1.type == 'TEXT'">
                                            <el-image :src="textImg" @click="showLiterature(item1.attachment)">
                                            </el-image>
                                        </template>
                                        <template v-else-if="item1.type == 'WORD'">
                                            <el-image :src="wordImg" @click="showLiterature(item1.attachment)">
                                            </el-image>
                                        </template>
                                        <template v-else-if="item1.type == 'PDF'">
                                            <el-image :src="pdfImg" @click="showLiterature(item1.attachment)">
                                            </el-image>
                                        </template>
                                        <template v-else-if="item1.type == 'PPT'">
                                            <el-image :src="pptImg" @click="showLiterature(item1.attachment)">
                                            </el-image>
                                        </template>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <el-tooltip placement="left" class="myButtonList">
            <div class="myTools" slot="content">
                <div>
                    <el-button size="mini" type="info" @click="showPeopleList">人员列表</el-button>
                </div>
                <div>
                    <el-button size="mini" type="info" @click="showChatRoom"
                        v-if="currentChatRoomInfo.status.value == 'ONGOING'">聊天室</el-button>
                </div>
                <div>
                    <el-button size="mini" type="info" @click="sendNotice"
                        v-if="currentChatRoomInfo.status.value == 'ONGOING'">发送公告</el-button>
                    <el-button size="mini" type="info" @click="sendEmail">邮箱</el-button>
                </div>
            </div>
            <el-button size="mini">公告及邮箱</el-button>
        </el-tooltip>

        <NoticeDialog ref="myNotice" :stompClient="stompClient" :currentChatRoomInfo="currentChatRoomInfo"></NoticeDialog>
        <ChatRoomDialog ref="myChatRoom" :currentChatRoomInfo="currentChatRoomInfo" :stompClient="stompClient">
        </ChatRoomDialog>
        <ChatRoomMemberDialog ref="mychatRoomMemberDialog" :currentChatRoomInfo="currentChatRoomInfo"
            @openSendEmailPage="openSendEmailPage"></ChatRoomMemberDialog>
        <SendEmailDialog ref="myEmail" :fromUser="fromUser" :checkedUserList="checkedUserList"></SendEmailDialog>
    </div>
</template>

<script>
import goBack from '@/assets/img/xjs/4.png';
import { getRecordsByPaging, updateStatus } from '@/api/chat/chatRecords';
import { getTime_extent } from '@/util/http_util.js';
import NoticeDialog from '@/view/ddkz/components/noticeDialog.vue';
import ChatRoomDialog from "@/view/ddkz/components/chatRoomDialog.vue";
import chatRoomMemberDialog from "@/view/ddkz/components/chatRoomMemberDialog.vue";
import sendEmailDialog from "@/view/ddkz/components/sendEmailDialog.vue";
import textImg from '@/assets/img/ddkz/tool1.png';
import excelImg from '@/assets/img/ddkz/excel.png';
import wordImg from '@/assets/img/ddkz/word.png';
import pdfImg from '@/assets/img/ddkz/pdf.png';
import pptImg from '@/assets/img/ddkz/ppt.png';
import { MAIL_ADDRESS } from "@/constant/user";
import dayjs from "dayjs";
export default {
    data() {
        return {
            goBack: goBack,
            excelImg: excelImg,
            textImg: textImg,
            wordImg: wordImg,
            pdfImg: pdfImg,
            pptImg: pptImg,
            formInfo: {
                timeFrame: 5,
                fromUser: null
            },
            options: [{ label: '5分钟', value: 5 }, { label: '10分钟', value: 10 }, { label: '30分钟', value: 30 }, { label: '60分钟', value: 60 }, { label: '1天', value: 1440 }],
            optionsFrom: [],
            currentChatRoomInfo: { status: {}, teamInfo: {} },
            newsList: [],
            publicNoticeList: [],
            stompClient: { connected: false },
            // peopleList: [],
            notifications: [],
            fromUser: '',
            checkedUserList: []
            // status:false
        }
    },
    components: {
        NoticeDialog: NoticeDialog,
        ChatRoomDialog: ChatRoomDialog,
        ChatRoomMemberDialog: chatRoomMemberDialog,
        SendEmailDialog: sendEmailDialog
    },
    methods: {
        goBackFn() {
            this.$router.push({ name: '导调控制模块' });
        },
        subscribe(item) {
            if (item.status.value != "ONGOING") {//未开始的聊天室禁止订阅
                return;
            }
            //取消大群聊的订阅和导演部的订阅
            for (const sub in this.stompClient.subscriptions) {
                if (sub.startsWith("multicastMeeting") || sub.startsWith("multicastApproveNotice")) {
                    this.stompClient.unsubscribe(sub);
                }
            }
            //取消导演部审批
            //订阅大群主题，订阅功能中设置ID：
            this.stompClient.subscribe(item.address, res => {
                // this.getRecordsByPagingFn(item);
                let body = JSON.parse(res.body);
                console.log(body)
                this.publicNoticeList.push({
                    attachment: body.attachment,
                    content: body.content,
                    destId: res.headers.chatRoomId,
                    fromUserId: res.headers.fromUserId,
                    messageForm: body.messageForm,
                    remark: body.remark,
                    teamId: body.teamInfo.id,
                    teamInfo: body.teamInfo,
                    title: body.title,
                    createTime: body.createTime
                });
                this.publicNoticeList = this.publicNoticeList.sort(this.compare);
                this.dataOrderByParams(5, null);
                this.optionsFrom = [];
                this.publicNoticeList.forEach(item => {
                    if (this.optionsFrom.indexOf(item.fromUserId) == -1) {
                        this.optionsFrom.push(item.fromUserId);
                    }
                });
                this.$nextTick(() => {
                    this.$refs.myNotice.handleClose();
                })
            }, { id: "multicastMeeting" + item.id + new Date().getTime() });


            //判断次用户是否为导演部成员
            if (item.approvalPendingAddress) {
                //订阅导演部成员，订阅功能中设置ID：
                this.stompClient.subscribe(item.approvalPendingAddress, res => {
                    this.openApprove(JSON.parse(res.body));
                }, { id: "multicastApproveNotice" + item.id + new Date().getTime() });
            }
        },
        //分页查询群聊天记录
        getRecordsByPagingFn(item) {
            getRecordsByPaging(item.id, 1, 100, '2023-01-01 00:00:00', getTime_extent(0).pre_rq_end).then(res1 => {
                this.publicNoticeList = res1.records;
                this.dataOrderByParams(5, null);
                this.optionsFrom = [];
                this.publicNoticeList.forEach(item => {
                    if (this.optionsFrom.indexOf(item.fromUserId) == -1) {
                        this.optionsFrom.push(item.fromUserId);
                    }
                });
            });
        },
        dataOrderByParams(timeFrame, user) {
            let newsArr = [];
            let tmpArr = this.publicNoticeList;
            if (user) {
                tmpArr = this.publicNoticeList.filter(item => { return item.fromUserId == user });
            }
            tmpArr.forEach(item => {
                let fileUrl = item.attachment ? 'api/rest/file/viewPicture/CHAT?objectName=' + item.attachment : null;
                newsArr.push({ time: item.createTime, title: item.title, content: item.content, from: item.fromUserId, teamInfo: item.teamInfo, url: fileUrl, type: item.messageForm, attachment: item.attachment });
            });
            // this.newsList = this.splitIntoHours(tmpArr[tmpArr.length - 1].createTime, tmpArr[0].createTime, newsArr, timeFrame);
            this.newsList = this.groupByTime(newsArr, timeFrame);
            // console.log(this.newsList);
        },
        sendNotice() {
            this.$nextTick(() => {
                this.$refs.myNotice.showDialog();
            })
        },
        showChatRoom() {
            this.$nextTick(() => {
                this.$refs.myChatRoom.showDialog();
            })
        },
        showPeopleList() {
            this.$nextTick(() => {
                this.$refs.mychatRoomMemberDialog.showDialog();
            })
        },
        openSendEmailPage(data) {
            this.checkedUserList = data;
            this.$nextTick(() => {
                this.$refs.myEmail.showDialog();
            })
        },
        sendEmail() {
            window.open(MAIL_ADDRESS);
        },
        showLiterature(url) {
            window.open("api/rest/file/download/CHAT/" + url);
        },
        openApprove(item) {
            const h = this.$createElement;
            const agreeButton = h('el-button', {
                props: {
                    type: 'success',
                    size: "mini"
                },
                on: {
                    //为按钮绑定点击事件
                    click: () => {
                        this.approvalNotice(item.id, 'PASS')
                    }
                },
                style: {
                    border: "none",
                    textAlign: "center",
                    // width:"20%",
                    margin: "5% 0 0 0 ",
                }
            }, '同意');
            const rejectButton = h('el-button', {
                props: {
                    type: 'danger',
                    size: "mini"
                },
                on: {
                    //为按钮绑定点击事件
                    click: () => {
                        this.approvalNotice(item.id, 'REFUSE')
                    }
                },
                style: {
                    border: "none",
                    textAlign: "center",
                    margin: "5% 0 0 20px ",
                }
            }, '驳回');

            const contentDiv = h('div', {}, `内容：${item.content}`);
            const fileDiv = h('div', {}, `附件名称：${item.remark == '' ? '暂无' : item.remark}`);
            const divTemplate = h('div', { style: { textAlign: 'center' } }, [agreeButton, rejectButton])
            let myNotify = this.$notify({
                title: item.title,
                dangerouslyUseHTMLString: true,
                duration: 0,
                message: h('div', {
                    style: {}
                },
                    [contentDiv, fileDiv, divTemplate]
                )
            });
            this.notifications[item.id] = myNotify
        },
        approvalNotice(id, state) {
            updateStatus(id, state).then(res => {
                this.$message.success(res);
                this.notifications[id].close();
                delete this.notifications[id];
            }).catch(error => {
                this.$message.error(error);
            })
        },
        groupByTime(data, timeFrame) {
            let tmp = [], timeInterval = 0, startTime = null, endTime = null;
            data.forEach(item => {
                let obj = { time: '', news: [] };
                let timeStamp = Date.parse(item.time);
                timeInterval = timeStamp % (timeFrame * 60 * 1000);
                startTime = dayjs((timeStamp - timeInterval)).format('YYYY-MM-DD HH:mm:ss');
                endTime = dayjs((timeStamp + (timeFrame * 60 * 1000 - timeInterval))).format('YYYY-MM-DD HH:mm:ss');
                if (tmp.some(newsArrChild => { return newsArrChild.time == (startTime + ' ~ ' + endTime) })) {
                    tmp.forEach(item1 => {
                        if (item1.time == (startTime + ' ~ ' + endTime)) {
                            item1.news.push(item);
                        }
                    })
                } else {
                    obj.time = startTime + ' ~ ' + endTime;
                    obj.news.push(item);
                    tmp.push(obj);
                }
            });
            return tmp;
        },
        splitIntoHours(startTime, endTime, data, timeFrame) {
            let start = new Date(startTime); // 将开始时间转换为日期对象
            let end = new Date(endTime); // 将结束时间转换为日期对象
            let hoursArray = []; // 创建空数组存放每小时的时间点
            while (start < end) {
                let tmp = [];
                data.forEach(item => {
                    if (Date.parse(item.time) >= start.getTime() && Date.parse(item.time) < start.getTime() + (timeFrame * 60 * 1000)) {
                        tmp.push(item);
                    }
                })
                hoursArray.unshift(tmp); // 添加当前时间到数组中
                start.setMinutes(start.getMinutes() + timeFrame); // 设置下一次循环的起始时间（+5分钟）
            }
            let returnData = hoursArray.filter(item => item.length > 0);
            return returnData;
        },

        handleChangeFromUser(val) {
            // debugger
            this.formInfo.timeFrame = 5;
            this.dataOrderByParams(5, val ? val : null);
        },
        handleChangeTimeFrame(val) {
            this.dataOrderByParams(val ? val : 5, this.formInfo.fromUser);
        },
        compare(obj1, obj2) {
            var val1 = obj1.createTime;
            var val2 = obj2.createTime;
            if (val1 > val2) {
                return -1;
            } else if (val1 < val2) {
                return 1;
            } else {
                return 0;
            }
        }
    },
    computed: {
        userInfo() {
            if (this.$store.getters.userInfo) {
                return this.$store.getters.userInfo;
            } else {
                return { account: "" };
            }
        }
    },
    activated() {
        this.currentChatRoomInfo = this.$route.params.data;
        this.stompClient = this.$route.params.client;
        // this.status = this.stompClient.connected;
        this.subscribe(this.currentChatRoomInfo);
        //获取当前组成员
        // this.getCurrentTeamPeople(this.currentChatRoomInfo);
        //获取当前公告列表
        this.getRecordsByPagingFn(this.currentChatRoomInfo);
        this.fromUser = this.userInfo.email;
        this.formInfo.timeFrame = 5;
    }
}
</script>

<style lang="scss">
.ddkz-info {
    width: 100%;
    height: 100%;

    .ddkz-info-selection {
        // display: none;
        width: 100%;
        height: 40px;
        text-align: right;

        .el-input {
            float: left;
            width: 200px;
            margin-right: 30px;

            .el-input__inner {
                background: none;
                color: #ffff;
                border: 1px solid #3a5f94c9 !important;
            }
        }

        .goBack {
            width: 40px;
            height: 40px;
            margin-right: 35px;
            cursor: pointer;
        }

        .searchButton {
            width: 80px;
            height: 30px;
            line-height: 30px;
            margin-top: 4px;
            margin-right: 30px;
            font-size: 14px;
            text-align: center;
            background-size: 100% 100%;
            background-repeat: no-repeat;
            border: 1px solid #3a5f94c9 !important;
            border-radius: 5px;
            cursor: pointer;
        }
    }

    .ddkz-info-content {
        width: 100%;
        height: calc(93% - 60px);
        margin-top: 20px;

        .info-content-left {
            width: calc(100% - 20px);
            height: 100%;
            float: left;
            padding-left: 35px;
            box-sizing: border-box;
            background-image: url(@/assets/img/ddkz/bg3.png);
            background-size: cover;
            overflow-y: auto;

            .everyDayNews {
                width: 100%;
                height: 230px;
                margin-bottom: 50px;
                padding: 6px 0px;
                box-sizing: border-box;


                .everyDayTitle {
                    width: 100%;
                    height: 30px;
                    color: white;
                    font-size: 20px;
                    font-weight: 600;
                    cursor: pointer;

                    .circle-light {
                        width: 15px;
                        height: 15px;
                        float: left;
                        margin-top: 7.5px;
                        border-radius: 50%;
                        background: white;
                        box-shadow: 0px 0px 20px 6px white;
                    }
                }

                .everyDayNew {
                    width: 100%;
                    height: 220px;
                    padding: 0px 10px;
                    box-sizing: border-box;
                    overflow-x: auto;
                    overflow-y: hidden;

                    .everyTemplate {
                        width: 98%;
                        height: 100%;
                        padding-bottom: 10px;
                        box-sizing: border-box;
                        overflow-x: auto;
                        overflow-y: hidden;
                        display: -webkit-box;
                    }

                    .everyDayNewCard {
                        width: calc(33% - 28px);
                        height: calc(100% - 20px);
                        float: left;
                        margin-top: 20px;
                        margin-left: 25px;
                        padding: 15px 30px;
                        box-sizing: border-box;
                        background-image: url(@/assets/img/ddkz/new3.png);
                        background-size: 100% 100%;

                        .everyDayNewCardTitle {
                            width: 100%;
                            height: 30px;
                            font-size: 18px;
                            font-weight: 600;
                            border-bottom: 1px solid #7b7b7bdd;
                        }

                        .everyDayNewCardContent {
                            width: 100%;
                            height: 110px;
                            margin-top: 10px;
                            display: flex;

                            .left-everyDayNew {
                                width: 50%;
                                height: 100%;

                                .everyDayNewCardInfo {
                                    width: 100%;
                                    height: 20px;
                                    margin-top: 10px;
                                    font-size: 12px;
                                    font-weight: 600;
                                    color: white;

                                    .newsSource {
                                        // color: red;
                                        color: white;
                                    }
                                }

                                .everyDayNewCardText {
                                    width: 100%;
                                    // height: calc(100% - 58px);
                                    margin-top: 5px;
                                    font-size: 12px;
                                    font-weight: 600;
                                    color: white;
                                    display: -webkit-box;
                                    -webkit-box-orient: vertical;
                                    -webkit-line-clamp: 5;
                                    /* 控制显示的行数 */
                                    overflow: hidden;
                                    word-break: break-all
                                }
                            }

                            .right-everyDayNew {
                                width: 50%;
                                height: 100%;
                                text-align: center;

                                img {
                                    width: 100%;
                                    height: 100%;
                                }

                                video {
                                    width: 100%;
                                    height: 100%;
                                }
                            }
                        }




                    }

                    .cardType0 {
                        background-image: url(@/assets/img/ddkz/new3.png);
                        background-size: 100% 100%;
                    }

                    .cardType1 {
                        background-image: url(@/assets/img/ddkz/new1.png);
                        background-size: 100% 100%;
                    }

                    .cardType2 {
                        background-image: url(@/assets/img/ddkz/new2.png);
                        background-size: 100% 100%;
                    }
                }
            }

        }
    }

    .myButtonList {
        position: absolute;
        right: -10px;
        bottom: 30px;
    }
}
</style>