<script setup>
import {
    apiGetNoticeList,
    apiReadAllNotice,
    apiReadOneNotice,
    apiDelOneNotice
} from '@/api/common'
import { ElMessage,ElMessageBox } from 'element-plus'
import { reactive,onMounted } from 'vue'
import moment from 'moment'
import 'moment/dist/locale/zh-cn'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
moment.locale('zh-cn')

const store=useStore()
const router=useRouter()

// 格式化消息时间
const formatTime=(e)=>{
    let dayStr=moment(e).format('HH:mm:ss')
    // 判断是否为今天
    if(moment(new Date()).isSame(e, 'day')){
        return dayStr
    }
    // 判断昨天
    if(moment(moment().subtract(1, 'day')).isSame(e,'day')){
        return `昨天 ${dayStr}`
    }
    // 前天
    if(moment(moment().subtract(2, 'day')).isSame(e,'day')){
        return `前天 ${dayStr}`
    }
    // 周内
    if(moment(new Date()).isSame(e, 'week')){
        return `${moment(e).format('ddd')} ${dayStr}`
    }
    //年内
    if(moment(new Date()).isSame(e, 'year')){
        return `${moment(e).format('MM月DD日')} ${dayStr}`
    }

    return `${moment(e).format('YYYY年MM月DD日')} ${dayStr}`
}

const listState=reactive({
    type:0,// 0-全部，1-留言回复通知，2-精选留言通知
    list:[],
    page:1,
    pageSize:20,
    loading:false,
    finished:false
})
// 获取消息列表
const getNoticeList=async ()=>{
    listState.loading=true
    const res=await apiGetNoticeList({
        type:Number(listState.type),
        page_size:listState.pageSize,
        current_index:listState.page 
    })
    listState.loading=false
    if(res.code===200){
        let arr=res.data.list||[]
        listState.list=[...listState.list,...arr]
        if(res.data.paging.is_end){
            listState.finished=true
        }
    }
}

//加载更多
const onLoad=()=>{
    if(listState.loading) return
    listState.page++
    getNoticeList()
}

// 消息类型切换
const handleTypeChange=(type)=>{
    listState.type=type 
    listState.list=[]
    listState.page=1
    listState.finished=false
    getNoticeList()
}

//删除消息
const handleDelNotice=(item,index)=>{
    const htmlStr=`<p>删除后无法恢复，<p><p>确定删除该条通知吗？</p>`
    ElMessageBox({
        title:`操作提醒`,
        message:htmlStr,
        center: true,
        dangerouslyUseHTMLString: true,
        confirmButtonText:'确定',
        confirmButtonClass:'self-elmessage-confirm-btn',
        showCancelButton:true,
        cancelButtonText:'取消',
        cancelButtonClass:'self-elmessage-cancel-btn'
    }).then(()=>{
        apiDelOneNotice({msg_id:Number(item.msg_id)}).then(res=>{
            if(res.code===200){
                ElMessage.success('删除成功')
                listState.list.splice(index,1)//删除数组中该数据
                // 如果该消息是未读状态则 重新获取一次个人信息
                if(item.is_read==0){
                    store.dispatch('getUserInfo')
                }
            }
        })
    }).catch(()=>{
        console.log('取消删除');
    })

    
}

//全部已读
const handleReadAll=async ()=>{
    const res=await apiReadAllNotice({type:Number(listState.type)})
    if(res.code===200){
        store.dispatch('getUserInfo')
        listState.list.forEach(item=>{
            item.is_read=1
        })
    }
}

//跳转详情
const handleGoDetail=async (item)=>{
    // 如果没读则调用已读
    if(item.is_read==0){
        const res=await apiReadOneNotice({msg_id:Number(item.msg_id)})
        if(res.code===200){
            console.log('已读成功');
            store.dispatch('getUserInfo')
            item.is_read=1
        }
    }
    // 跳转
    if(item.old_report_chapter_id!=0){//活动的章节报告详情
        router.push({
            path:'/activity/chapterdetail',
            query:{
                research_report_type_id:item.old_report_chapter_id,
                research_report_id:item.old_report_id
            }
        })
        return
    }

    if(item.old_report_id!=0){//活动的普通报告详情
        router.push({
            path:'/activity/reportdetail',
            query:{
                research_report_id:item.old_report_id
            }
        })
        return
    }

    if(item.report_chapter_id!=0){
        router.push({
            path:'/report/chapterdetail',
            query:{
                chapterId:item.report_chapter_id
            }
        })
        return 
    }

    if(item.report_id!=0){
        router.push({
            path:'/report/detail',
            query:{
                reportId:item.report_id
            }
        })
        return 
    }
    
}

onMounted(() => {
    getNoticeList()
})

</script>

<template>
    <div class="notice-wrap">
        <div class="top-nav">
            <span :class="listState.type==0&&'active'" @click="handleTypeChange(0)">全部消息</span>
            <span :class="listState.type==1&&'active'" @click="handleTypeChange(1)">回复</span>
            <!-- <span :class="listState.type==2&&'active'" @click="handleTypeChange(2)">精选</span> -->
            <div style="float:right;color:#F3A52F;font-size:14px;cursor: pointer;" @click="handleReadAll">全部已读</div>
        </div>
        <div class="empty-box" v-if="listState.finished&&listState.list.length==0">
            <img :src="$store.state.globalImgUrls.chartEmpty" alt="">
            <p>暂时没有新的消息哦<br>快去留言试试吧～</p>
        </div>
        <ul 
            v-else
            class="notice-list" 
            v-infinite-scroll="onLoad"
            :infinite-scroll-disabled="listState.finished"
        >
            <li class="flex notice-item" v-for="(item,index) in listState.list" :key="item.msg_id">
                <el-image :src="item.img" :class="['avatar',item.is_read==0&&'avatar-dot']" fit="cover"></el-image>
                <div class="notice-con" @click="handleGoDetail(item)">
                    <p class="multi-ellipsis" style="color:#666;margin:0;font-size:16px">{{item.content_first}}</p>
                    <p class="multi-ellipsis" style="color:#333;margin:0;font-size:18px">{{item.content_second}}</p>
                    <div style="color:#666;font-size:16px">{{formatTime(item.create_time)}}</div>
                    <span class="del-btn" @click.stop="handleDelNotice(item,index)">删除该通知</span>
                </div>
            </li>
        </ul>
    </div>
</template>

<style lang="scss" scoped>
.notice-wrap{
    .top-nav{
        margin-bottom: 20px;
        span{
            font-size: 18px;
            display: inline-block;
            margin-right: 50px;
            cursor: pointer;
            padding-bottom: 5px;
        }
        .active{
            color: #F3A52F;
            border-bottom: 2px solid #F3A52F;
        }
    }
    .notice-list{
        height: 400px;
        overflow-y: auto;
        &::-webkit-scrollbar{
            display: none;
        }
        .notice-item{
            padding: 10px;
            .avatar{
                flex-shrink: 0;
                margin-right: 12px;
                width: 37px;
                height: 37px;
                position: relative;
            }
            .avatar-dot::after{
                content: '';
                display: block;
                width: 11.5px;
                height: 11.5px;
                background-color: #D62020;
                border-radius: 50%;
                position: absolute;
                top: 0;
                right: 0;
            }
            .notice-con{
                flex: 1;
                position: relative;
                overflow: hidden;
                .del-btn{
                    color: #F3A52F;
                    position: absolute;
                    right: 0;
                    bottom: 0;
                    cursor: pointer;
                    display: none;
                    &::before{
                        content: '';
                        display: inline-block;
                        width: 14px;
                        height: 14px;
                        background-image: url('@/assets/icon-del.png');
                        background-size: cover;
                        position: relative;
                        top: 2px;
                        margin-right: 7px;
                    }
                }
            }
            &:hover{
                background-color: #FFFBF5;
            }
            &:hover .del-btn{
                display: block;
            }
        }
    }
    .empty-box{
        text-align: center;
        color: #999;
        img{
            width: 50%;
        }
    }
}
</style>