<template>
    <div>
        <el-badge
            class="message-button"
            :value="unreadMessage.total"
            :max="10"
            :hidden="unreadMessage.total == 0"
        >
            <el-button type="text" @click="handleDialogShow">
                通知消息
            </el-button>
        </el-badge>

        <!-- 点击弹窗 -->
        <el-dialog
            title="通知消息"
            v-if="messagesDialog.visible"
            :visible.sync="messagesDialog.visible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="60%"
            append-to-body
            center
            top="8vh"
        >
            <div
                v-loading="loading"
                element-loading-text="拼命加载中......请稍等"
            >
                <el-card v-if="messageDetail.visible">
                    <div slot="header">
                        <span>{{ messageDetail.rowData.msgTitle }}</span>
                        <el-button
                            style="float: right; padding: 3px 0"
                            type="text"
                            @click="handleMessageDetailClose"
                            >返回上级</el-button
                        >
                    </div>
                    <div>
                        <wang-editor-ex-display
                            ref="refWangEditorExDisplay"
                            :contentText="messageDetail.msgContent"
                            :height="500"
                        ></wang-editor-ex-display>
                    </div>
                </el-card>
                <div v-else>
                    <el-table
                        :data="allMessage.resultList"
                        stripe
                        height="550"
                        style="width: 100%"
                    >
                        <el-table-column width="50">
                            <template slot-scope="scope">
                                <div v-if="!hasReadedMessage(scope.row)">
                                    <i class="tag-red"></i>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="标题内容"
                            width="280"
                            show-overflow-tooltip
                        >
                            <template slot-scope="scope">
                                <el-link
                                    :type="
                                        hasReadedMessage(scope.row)
                                            ? 'info'
                                            : 'primary'
                                    "
                                    @click="handleMessageDetail(scope.row)"
                                >
                                    {{ scope.row.msgTitle }}
                                </el-link>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="msgBrief"
                            label="简介内容"
                            show-overflow-tooltip
                        >
                        </el-table-column>
                        <el-table-column
                            prop="createTime"
                            label="创建时间"
                            width="180"
                            show-overflow-tooltip
                        >
                        </el-table-column>
                        <el-table-column
                            prop="msgType"
                            label="类型"
                            align="center"
                            width="180"
                            :formatter="fmtMsgType"
                        >
                        </el-table-column>
                    </el-table>
                    <br />
                    <div style="text-align: right">
                        <el-pagination
                            background
                            layout="total,sizes,prev,pager,next"
                            :current-page="
                                allMessage.resultPagination.currentPage
                            "
                            :page-sizes="allMessage.resultPagination.pageSizes"
                            :page-size="allMessage.resultPagination.pageSize"
                            :total="allMessage.resultPagination.total"
                            @size-change="handleResultSizeChange"
                            @current-change="handleResultCurrentChange"
                        >
                        </el-pagination>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 自动弹窗 -->
        <el-dialog
            v-if="autoDialog.visible"
            :visible.sync="autoDialog.visible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="60%"
            append-to-body
            center
            top="8vh"
        >
            <div
                v-loading="autoDialog.loading"
                element-loading-text="拼命加载中......请稍等"
            >
                <div style="text-align: center">
                    <h2>{{ autoDialog.detail.msgTitle }}</h2>
                </div>

                <wang-editor-ex-display
                    :contentText="autoDialog.detail.msgContent"
                    :height="500"
                ></wang-editor-ex-display>
                <el-divider></el-divider>
                <div style="text-align: center">
                    <el-checkbox
                        v-model="autoDialog.current.isShowTips"
                        style="margin-right: 50px"
                    >
                        下次不再提醒我
                    </el-checkbox>
                    <el-button type="primary" @click="handleNextMessage">
                        下一条
                        {{ autoDialog.readedNumber }}/{{
                            allUnreadMessageNumber
                        }}
                    </el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import USER_MANAGEMENT from "@/api/user-management";
import NOTIFICATION_MESSAGE from "@/api/notification-message";
import wangEditorExDisplay from "@/components/wangEditorEx/display";

import cache from "@/utils/cache";

// 发票明细页面无发票清单标签列表
const msgTypeOptions = [
    {
        value: 1,
        label: "系统全局公告消息",
    },
    {
        value: 2,
        label: "全局的企业消息",
    },
    {
        value: 3,
        label: "全局的服务商消息",
    },
    {
        value: 4,
        label: "企业个体消息",
    },
    {
        value: 5,
        label: "服务商个体消息",
    },
    {
        value: 6,
        label: "用户个人消息",
    },
    {
        value: 7,
        label: "服务商下企业消息",
    },
];

export default {
    name: "UserMessage",
    components: {
        "wang-editor-ex-display": wangEditorExDisplay,
    },
    data() {
        return {
            loading: false,
            // 未读消息
            unreadMessage: {
                total: 0,
                resultList: [],
            },
            // 未读公告
            unreadGlobalNotice: {
                total: 0,
                resultList: [],
            },
            allMessage: {
                resultList: [],
                resultPagination: {
                    currentPage: 1,
                    pageSizes: [10, 30, 50, 100],
                    pageSize: 10,
                    total: 0,
                },
            },
            resultList: [],
            resultPagination: {
                currentPage: 1,
                pageSizes: [10, 30, 50, 100],
                pageSize: 10,
                total: 0,
            },
            messagesDialog: {
                visible: false,
            },
            messageDetail: {
                visible: false,
                rowData: {}, // 选中消息
                msgContent: "", // 消息内容
            },
            autoDialog: {
                visible: false,
                loading: false,
                current: {
                    isUnreadMessage: false, // 是否读取未读消息列表，否则是在读取全局公告
                    msgId: "", // 消息 Id
                    index: "", // 消息列表索引
                    isShowTips: false, // 是否标记为已读使用
                },
                detail: { msgTitle: "", msgContent: "" }, // 消息详细
                readedNumber: 0, // 已读取消息个数
            },
        };
    },
    created() {
        // 未读消息查询
        this.getAllUnreadMessages();
    },
    computed: {
        isShowTips: function () {
            return this.autoDialog.current.isUnreadMessage === false;
        },
        allUnreadMessageNumber: function () {
            return this.unreadGlobalNotice.total + this.unreadMessage.total;
        },
    },
    methods: {
        fmtMsgType(row, column, cellValue) {
            let result = cellValue;
            for (const item of msgTypeOptions) {
                if (item.value === cellValue) {
                    result = item.label;
                    break;
                }
            }
            return result;
        },
        // 消息已读 true,否则 false
        hasReadedMessage(row) {
            return row && row.hasRead;
        },
        // 显示通知消息对话框
        handleDialogShow() {
            this.messageDetail.visible = false;
            this.messagesDialog.visible = true;

            // 读取所有消息
            this.callAllMessages(
                this.allMessage.resultPagination.currentPage,
                this.allMessage.resultPagination.pageSize
            );
        },
        // 获取全部未读消息信息,含公告
        getAllUnreadMessages() {
            let _this = this;
            _this.autoDialog.loading = true;
            USER_MANAGEMENT.findGlobalNotice({
                hasRead: false,
                pageNum: 1,
                pageSize: 100,
            })
                .then((val) => {
                    _this.unreadGlobalNotice.total = val.data.total;
                    _this.unreadGlobalNotice.resultList = val.data.records;

                    // _this.unreadGlobalNotice.total = 0;
                    // _this.unreadGlobalNotice.resultList = [];

                    USER_MANAGEMENT.getUserMessages({
                        hasRead: false,
                        pageNum: 1,
                        pageSize: 100,
                    })
                        .then((val2) => {
                            _this.unreadMessage.total = val2.data.total;
                            _this.unreadMessage.resultList = val2.data.records;

                            // 自动弹窗初始化
                            _this.autoDialogInit();
                        })
                        .catch((err2) => {
                            // _this.$message.error(err2);
                        })
                        .finally(() => {
                            _this.autoDialog.loading = false;
                        });
                })
                .catch((err) => {
                    // _this.$message.error(err);
                })
                .finally(() => {
                    _this.autoDialog.loading = false;
                });
        },
        // 获取未读消息信息
        callGetUnreadMessages() {
            let _this = this;
            // _this.loading = true;
            USER_MANAGEMENT.getUserMessages({
                hasRead: false,
                pageNum: 1,
                pageSize: 10,
            })
                .then((val) => {
                    _this.unreadMessage.total = val.data.total;
                    _this.unreadMessage.resultList = val.data.records;
                })
                .catch((err) => {
                    _this.$message.error(err);
                })
                .finally(() => {
                    // _this.loading = false;
                });
        },
        callAllMessages(pageNum, pageSize) {
            let _this = this;
            _this.loading = true;
            USER_MANAGEMENT.getUserMessages({
                pageNum: pageNum,
                pageSize: pageSize,
            })
                .then((val) => {
                    // _this.allMessage.resultPagination.total = val.data.total;
                    _this.allMessage.resultPagination.total = val.data.total;
                    _this.allMessage.resultPagination.pageSize = val.data.size;
                    _this.allMessage.resultPagination.currentPage =
                        val.data.current;
                    _this.allMessage.resultList = val.data.records;
                })
                .catch((err) => {
                    _this.$message.error(err);
                })
                .finally(() => {
                    _this.loading = false;
                });
        },
        handleMessageDetail(row) {
            if (row) {
                this.messageDetail.rowData = row;
                let _this = this;
                _this.loading = true;
                USER_MANAGEMENT.getUserMessageDetail(row.msgId)
                    .then((val) => {
                        _this.messageDetail.msgContent = val.data.msgContent;
                        _this.messageDetail.visible = true;
                    })
                    .catch((err) => {
                        _this.$message.error(err);
                    })
                    .finally(() => {
                        _this.loading = false;
                    });
            }
        },
        handleMessageDetailClose() {
            this.messageDetail.visible = false;

            let mobile = JSON.parse(cache.getSession("user")).account;
            NOTIFICATION_MESSAGE.setMessageReaded(
                mobile,
                this.messageDetail.rowData.msgId
            )

            this.callAllMessages(
                this.allMessage.resultPagination.currentPage,
                this.allMessage.resultPagination.pageSize
            );

            // 未读消息查询
            this.callGetUnreadMessages();
        },
        handleResultSizeChange(val) {
            this.callAllMessages(1, val);
        },
        handleResultCurrentChange(val) {
            this.callAllMessages(
                val,
                this.allMessage.resultPagination.pageSize
            );
        },
        // 自动弹框页面的消息详情读取
        autoDialogGetDetail(isUnreadMessage, msgId, index) {
            const _this = this;

            _this.autoDialog.current.isUnreadMessage = isUnreadMessage;
            _this.autoDialog.current.msgId = msgId;
            _this.autoDialog.current.index = index;
            _this.autoDialog.current.isShowTips = false;

            _this.autoDialog.readedNumber++;

            _this.autoDialog.loading = true;
            USER_MANAGEMENT.getUserMessageDetail(msgId)
                .then((val) => {
                    _this.autoDialog.detail.msgTitle = val.data.msgTitle;
                    _this.autoDialog.detail.msgContent = val.data.msgContent;
                })
                .catch((err) => {
                    _this.$message.error(err);
                    // 消息详情读取失败，关闭自动弹窗
                    _this.autoDialog.visible = false;
                })
                .finally(() => {
                    _this.autoDialog.loading = false;
                });
        },
        // 自动弹窗初始化，
        // 判断是否需要弹出
        autoDialogInit() {
            // 1. 判断未读公告
            // 2. 判断未读消息
            // 未开始消息显示
            // 判断全局消息
            if (
                this.unreadGlobalNotice.total > 0 &&
                this.unreadGlobalNotice.resultList
            ) {
                this.autoDialog.visible = true;

                let firstItem = this.unreadGlobalNotice.resultList[0];
                this.autoDialogGetDetail(false, firstItem.msgId, 0);
            } else if (
                this.unreadMessage.total > 0 &&
                this.unreadMessage.resultList
            ) {
                // 其它消息
                this.autoDialog.visible = true;

                let firstItem = this.unreadMessage.resultList[0];
                this.autoDialogGetDetail(true, firstItem.msgId, 0);
            } else {
                this.autoDialog.visible = false;
            }
        },
        handleNextMessage() {
            if (
                this.unreadGlobalNotice.resultList &&
                this.autoDialog.current.isUnreadMessage === false &&
                this.autoDialog.current.index + 1 ===
                    this.unreadGlobalNotice.resultList.length
            ) {
                this.autoDialog.current.isUnreadMessage = true;
                this.autoDialog.current.msgId = "";
                this.autoDialog.current.index = -1;
            }

            let currentIndexAdd1 = this.autoDialog.current.index + 1;
            if (this.autoDialog.current.isUnreadMessage === false) {
                if (
                    this.unreadGlobalNotice.resultList.length > currentIndexAdd1
                ) {
                    let item = this.unreadGlobalNotice.resultList[
                        currentIndexAdd1
                    ];

                    if (this.autoDialog.current.isShowTips) {
                        let mobile = JSON.parse(cache.getSession("user"))
                            .account;
                        NOTIFICATION_MESSAGE.setMessageReaded(
                            mobile,
                            this.autoDialog.current.msgId
                        );
                    }

                    this.autoDialogGetDetail(
                        false,
                        item.msgId,
                        currentIndexAdd1
                    );
                }
            } else {
                if (this.unreadMessage.resultList.length > currentIndexAdd1) {
                    let item = this.unreadMessage.resultList[currentIndexAdd1];

                    if (this.autoDialog.current.isShowTips) {
                        let mobile = JSON.parse(cache.getSession("user"))
                            .account;
                        NOTIFICATION_MESSAGE.setMessageReaded(
                            mobile,
                            this.autoDialog.current.msgId
                        );
                    }

                    this.autoDialogGetDetail(
                        true,
                        item.msgId,
                        currentIndexAdd1
                    );
                } else {
                    this.autoDialog.visible = false;
                }
            }
        },
    },
};
</script>

<style lang="stylus" scoped>
.message-button {
    margin-left: 10px;
    margin-right: 10px;
}

>>> .el-scrollbar__wrap {
    overflow-x: hidden;
}

.tag-red {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #409EFF;
    display: block;
}
</style>