<!--
 * @Author: zouwenying
 * @Date: 2020-10-26 10:32:32
 * @LastEditTime: 2021-04-30 14:34:19
 * @LastEditors: zwy
 * @Description: In User Settings Edit
 * @FilePath: \UMIS\src\components\others\Header.vue
-->
<template>
    <div class="header" :class="[collapse ? 'collapse' : 'expand']">
        <div class="el-fl-left"><v-tags></v-tags></div>
        <div class="header-right">
            <div class="header-user-con">
                <div>欢迎你,{{ cruUserInfo.username }}</div>
                <!-- 用户头像 -->
                <div class="user-avator" @click="editUserInfo">
                    <i class="iconfont" v-show="!cruUserInfo.photo" v-bottom-txt-tip data-txt="编辑用户信息">&#xe6e8;</i>
                    <div
                        class="imgs"
                        v-show="cruUserInfo.photo"
                        :style="'backgroundImage:' + 'url(' + envConfig.baseImgApi + cruUserInfo.photo + ');'"
                    ></div>
                </div>
                <div class="message">
                    <span class="main" @click="goMessage('unread')">
                        <img src="@/assets/img/btn_news.png" alt="" />
                        <span class="iconfont point" v-if="messageNumber"></span>
                    </span>
                    <div class="msg-content" v-if="messageList && messageList.length">
                        <p>消息通知</p>
                        <ul>
                            <li v-for="(items, index) in messageList" :key="index" @click="toUrl(items.typeId)" style="cursor: pointer">
                                <img :src="imgList[items.typeId - 1]" style="width: 30px; height: 30px" />
                                <div>
                                    <span class="cont">【{{ items.shortName }}】{{ items.messageContent }}</span>
                                    <span class="time">{{ items.dateCreate }}</span>
                                </div>
                            </li>
                        </ul>
                        <el-button type="text" class="more" @click="goMessage('more')">查看更多</el-button>
                    </div>
                    <div class="msg-content" v-else>
                        <p>消息通知</p>
                        <ul>
                            <li style="text-align: center; display: block; padding: 0 20px; line-height: 60px">暂无消息</li>
                        </ul>
                        <el-button type="text" class="more" disabled>查看更多</el-button>
                    </div>
                </div>
                <span class="border"></span>
                <div class="logout">
                    <el-tooltip placement="bottom" content="退出">
                        <img src="@/assets/img/btn_quit.png" class="tab_head-right" @click="logOut" />
                    </el-tooltip>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import userInfoVue from '../../views/system/users/userInfo.vue';
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';
import envConfig from '@/config';
import vTags from './Tags.vue';
export default {
    data() {
        return {
            name: '',
            envConfig: envConfig,
            imgList: [
                require('@/assets/img/icon_msg1.png'),
                require('@/assets/img/icon_msg2.png'),
                require('@/assets/img/icon_msg3.png'),
                require('@/assets/img/icon_msg4.png'),
                require('@/assets/img/icon_msg5.png'),
                require('@/assets/img/icon_msg6.png'),
                require('@/assets/img/icon_msg7.png'),
                require('@/assets/img/icon_msg8.png'),
                require('@/assets/img/icon_msg9.png')
            ]
        };
    },
    components: {
        vTags
    },
    computed: {
        cruUserInfo() {
            return this.$store.getters['getCruUserInfo'];
        },
        collapse() {
            return this.$store.getters['getCollapse'];
        },
        ...mapState(['messageNumber']),
        ...mapState(['messageList'])
    },
    methods: {
        toUrl(type) {
            let url, appId;
            if (type == 1 || type == 2) {
                url = this.envConfig.warnDetailUrl;
                appId = '1002';
            } else if (type == 4) {
                url = this.envConfig.taskManagementUrl;
                appId = '1003';
            } else if (type == 3 || type == 7) {
                url = this.envConfig.eventHiddenDangerUrl;
                appId = '1003';
            } else if (type == 9) {
                // url=this.envConfig.eventHiddenDangerUrl;
                appId = '1012';
                this.$router.push({
                    path: '/msg'
                });
                return;
            }
            this.$http
                .postForm('/sc-message/message/judgingTheMessageJumpPermission', {
                    url: url.split('/')[url.split('/').length - 1],
                    appId: appId
                })
                .then(({ status, data, msg }) => {
                    if (status == 0 && data == 0) {
                        window.open(url);
                    } else {
                        this.$message.error('您没有该系统权限');
                    }
                });
        },
        // 退出登录
        logOut() {
            var access_token = localStorage.getItem('SC_token');
            this.$http.postForm('/sc-user-auth/user/logout', { access_token: access_token }).then(({ status, data, msg }) => {
                if (0 === status) {
                    this.$message({
                        type: 'success',
                        message: '您已退出登录'
                    });
                    localStorage.removeItem('SC_token');
                    this.$store.commit('setloginInfo', '');
                    this.$store.dispatch('tags', []);
                    sessionStorage.removeItem('tabs');
                    location.href = this.envConfig.loginUrl;
                } else {
                    this.$message.error(msg);
                }
            });
        },
        getUserInfo(resolve) {
            this.$http.postForm('/user/findLoginUserById').then(({ status, data, msg }) => {
                if (status === 0) {
                    this.$store.commit('setcCruUserInfo', data);
                } else {
                    this.$message.error('获取用户信息失败');
                }
                resolve && resolve(true);
            });
        },
        editUserInfo() {
            new Promise((resolve) => {
                this.$store.dispatch('openModal', {
                    url: '/system/users/popups/edituser.vue',
                    width: '500px',
                    height: '500px',
                    props: {
                        data: JSON.parse(JSON.stringify(this.cruUserInfo)),
                        callback: resolve
                    },
                    title: '编辑用户信息'
                });
            }).then(() => {
                this.getUserInfo();
            });
        },
        goMessage(msg) {
            let messageStatus = 2; //全部
            if (msg == 'unread') {
                messageStatus = 0; //未读
            }
            this.$store.commit('setmessageStatus', messageStatus);
            this.$router.push({
                path: '/msg'
            });
        },
        //获取最新消息列表
        getMessageList() {
            this.$http.postForm('/sc-message/message/queryLastMessage', { num: '5' }).then(({ status, data, msg }) => {
                if (status === 0) {
                    this.$store.commit('setmessageList', data);
                }
            });
        },
        //查询未读消息数量
        getUnreadNumber() {
            this.$http.postForm('/sc-message/message/queryUnreadMessageStatic').then(({ status, data, msg }) => {
                if (status === 0) {
                    data.map((item, index) => {
                        if (item.cn) {
                            this.$store.commit('setmessageNumber', true);
                        }
                    });
                }
            });
        },
        //初始化websoket
        initWebSocket(id) {
            if ('WebSocket' in window) {
                var serviceIp = this.envConfig.websoketUrl;
                this.websocket = new WebSocket('ws://' + serviceIp + '/sc-message/webSocket/' + id);
            } else {
                console.log('当前浏览器 Not support websocket');
            }
            let that = this;
            this.interval = window.setInterval(function () {
                //每隔30秒钟发送一次心跳，避免websocket连接因超时而自动断开
                if (that.websocket != null) {
                    // that.websocket.send('HeartBeat');
                    // console.log('发送心跳包：HeartBeat');
                }
            }, 30000);
            //连接发生错误的回调方法
            this.websocket.onerror = function (ev) {
                console.log('WebSocket连接发生错误');
            };

            //连接成功建立的回调方法
            this.websocket.onopen = function (ev) {
                console.log('WebSocket连接成功');
                // this.send('addsocket');
            };

            //接收到消息的回调方法
            this.websocket.onmessage = function (event) {
                let msg = JSON.parse(event.data);
                let i = msg.typeId - 1;
                if (msg.userId) {
                    that.$notify({
                        dangerouslyUseHTMLString: true,
                        showClose: true,
                        customClass: 'notice_icon',
                        offset: 60,
                        duration: 3000,
                        message:
                            "<div class='notice'><img src=" +
                            that.imgList[i] +
                            " class='img'/><div class='notice-content'><span class='title'>新消息通知</span><span class='nowrap'>" +
                            '【' +
                            msg.type +
                            '】' +
                            msg.content +
                            '</span></div></div>'
                    });
                    that.getMessageList();
                    that.getUnreadNumber();
                }
            };

            //连接关闭的回调方法
            this.websocket.onclose = function (ev) {
                console.log('WebSocket连接关闭');
                this.websocket = null;
            };
        },
        send(message) {
            if (this.websocket && this.websocket != null) {
                // this.websocket.send(message);
                console.log('发送的消息：' + message);
            }
        },
        //关闭WebSocket连接
        closeWebSocket() {
            if (this.websocket != null) {
                this.websocket.close();
            }
            if (this.interval) {
                window.clearInterval(this.interval);
            }
        }
    },
    mounted() {
        let vm = this;
        window.onbeforeunload = function () {
            vm.closeWebSocket();
        };
    },
    destoryed() {
        this.closeWebSocket();
    },
    created() {
        new Promise((resolve) => {
            this.getUserInfo(resolve);
        }).then((_) => {
            let id = this.$store.state.cruUserInfo.id;
            this.initWebSocket(id);
            this.getMessageList();
            this.getUnreadNumber();
        });
    }
};
</script>
<style lang='scss' scoped>
.border {
    width: 1px;
    height: 10px;
    background: #ffffff;
    opacity: 0.3;
}
.header {
    height: 46px;
    font-size: 14px;
    color: #fff;
    background: #2c354a;
    display: flex;
    align-items: center;
    justify-content: space-between;
    &.expand::before {
        content: '';
        display: inline-block;
        width: 230px;
        height: 46px;
        background: #2c354a;
        position: absolute;
        left: 0;
    }
    &.collapse::before {
        content: '';
        display: inline-block;
        width: 95px;
        height: 46px;
        background: #2c354a;
        position: absolute;
        left: 0;
    }
}
.header-right {
    padding-right: 20px;
    color: rgba(255, 255, 255, 0.6);
    .name-txt {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #ffffff;
    }
}
.header-user-con {
    display: flex;
    height: 60px;
    align-items: center;
}
.logout {
    margin-left: 20px;
    img {
        width: 20px;
        height: 20px;
    }
}
.iconfont {
    font-size: 20px;
    color: rgba(255, 255, 255, 0.6);
    &:hover {
        color: rgba(255, 255, 255, 1);
    }
}
.user-avator {
    margin-left: 10px;
    margin-right: 20px;
    cursor: pointer;
}
.user-avator .imgs {
    background: no-repeat center top;
    background-size: cover;
    width: 20px;
    height: 20px;
}
.message {
    margin: 10px 20px 0px 0px;
    color: #000000;
    cursor: pointer;
    &:hover {
        .msg-content {
            display: block;
            background: #ffffff;
            box-shadow: 0px 5px 20px 0px rgba(144, 144, 144, 0.4);
            border-radius: 6px;
            z-index: 200;
        }
    }
    .main {
        height: 60px;
        line-height: 60px;
        position: relative;
        img {
            width: 20px;
            height: 20px;
        }
        .point {
            position: absolute;
            top: -4px;
            right: -1px;
            width: 4px;
            height: 4px;
            background: #fe7271;
            border-radius: 50%;
            display: block;
        }
    }

    .msg-content {
        position: absolute;
        width: 380px;
        background: #ffffff;
        z-index: 20;
        right: 20px;
        top: 40px;
        transition: all 0.3s;
        display: none;
        p {
            height: 40px;
            line-height: 40px;
            padding-left: 20px;
            color: #212226;
        }
        li {
            display: flex;
            align-items: center;
            height: 60px;
            padding-left: 20px;
            border-top: 1px solid #f6f6f6;
            font-size: 12px;
            cursor: auto;
            span {
                width: 300px;
                overflow: hidden; //超出的文本隐藏
                text-overflow: ellipsis; //溢出用省略号显示
                white-space: nowrap; //溢出不换行
                display: block;
                line-height: 20px;
                padding-left: 15px;
            }
            .cont {
                color: #424656;
                text-indent: -0.4em;
            }
            .time {
                color: #7d7f87;
            }
        }
        .more {
            width: 100%;
        }
    }
}
</style>
