<template>
    <view class="con-body">
        <view class="con-bg">
            <!-- 头部 -->
            <customHeader ref="customHeaderRef" :title="!searchShow?'消息':'搜索'" 
                :leftFlag="!searchShow?false:true" 
                :rightFlag="true"  
                @back="handleBack" :searchType="searchShow?1:undefined"
            >
                <template #right  v-if="!searchShow">
                    <view class="head-right" @click="handleRead">
                        <img :src="'static/images/icon-clean@2x.png'" />清除未读
                    </view>
                </template>
            </customHeader>
            
            <!-- 高度来避免头部遮挡 -->
            <view class="top-height"></view>
          
            <!-- 搜索处理 -->
            <customSearch v-if="searchShow"   
                :searchKeywords="searchText" 
                :searchType="searchTypeObj" 
                :checkTypeObj="notictTypeCheck"
                :searchTypeList="noticeTypeList" 
                @confirm="handleSearchConfirm"
            ></customSearch>
            <view class="search" v-else  @click="handleSearchFocus">
                <view class="search-bg">
                    <view class="search-left">{{ notictTypeCheck.name?notictTypeCheck.name:'全部' }}</view>
                    <view class="search-right">
                        <uni-icons type="search" size="20" color="#ffffff"></uni-icons>
                        <input class="uni-input" v-model="searchText" placeholder="搜索" placeholder-class="search-color" />
                    </view>
                </view>
            </view>

            <!-- 消息列表 -->
            <mescroll-uni  v-if="!searchShow" ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback"
                :up="upOption" :down="downOption" :fixed="false" class="scroll-h" :class="{'loading-scroll':cssFlag}">
                <view class="white-bg" v-if="list.length>0" :class="{'bg-height':list.length<5}">
                    <view class="notice-list" v-for="(item, index) in list" :key="index" @click="handleJump(item)">
                        <img :src="'static/images/notice/'+item.imgSrc"  class="img-w" />
                        <!-- <image :src="item.imgSrc" mode="aspectFit" class="img-w"></image> -->
                        <view class="notice-item">
                            <view :class="{ 'notice-title': true, bold: item.isRead }">{{ item.subject }}</view>
                            <view class="notice-date">{{ formatDateStr(item.createTime) }}</view>
                            <view class="dot" v-if="item.isRead"></view>
                        </view>
                    </view>
                </view>
            </mescroll-uni>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted,computed } from 'vue'
import { onLoad,onHide } from '@dcloudio/uni-app';
import customHeader from '@/components/customHeader.vue'
import customSearch from '@/components/customSearch.vue'
import MescrollUni from 'mescroll-uni/mescroll-uni.vue';
import { getNavBarPaddingTop } from '@/utils/system.js'
import { noticeList } from '@/api/notice.js'
import { formatTimestamp } from '@/utils/datetime.js'

onLoad(async(opt) => {
    uni.setStorageSync('page_cache',true);
})

// 获取导航栏高度用于内容区域padding
const navBarPaddingTop = ref(0);
onMounted(() => {
    navBarPaddingTop.value = getNavBarPaddingTop() * 2;
})

// 搜索处理
let searchShow = ref(false);
let searchText = ref(undefined);
let searchTypeObj = ref({typeId:3,typeName:'消息类型'});
let noticeTypeList=ref([
    {id:1,name:'日程消息一二'}, 
    {id:2,name:'提醒消息'}, 
    {id:3,name:'通知消息'},
    {id:4,name:'待办消息'}, 
    {id:5,name:'服务消息'}
]);
let notictTypeCheck = ref({});//选中类型

onHide(()=>{
    searchShow.value=false;
})

// 搜索返回操作
const handleBack=()=>{
    searchShow.value=false;
}
// 获取input 焦点跳转
const handleSearchFocus=()=>{
    searchShow.value = true;
}

// 搜索完返回处理
const handleSearchConfirm = (param1,param2)=>{
    // console.log(param1,param2)
    notictTypeCheck.value=param1.value;
    searchText.value=param2.value;;
    searchShow.value=false;
}

const formatDateStr = (times) => {
    return formatTimestamp(times)
}

// 清除未读
const handleRead = () => {
    list.value.forEach(item => {
        item.isRead = false;
    })
}

// 随机图片数组
const images = [
  'icon-TiXing@2x.png',
  'icon-RiCheng@2x.png',
  'icon-DaiBan@2x.png',
  'icon-TongZhi@2x.png',
  'icon-TiXing@2x.png'
]

// 查询通知列表
let list = ref([]);
const mescrollRef = ref(null);
const upOption = ref({
    page: { num: 0, size: 10 },
    noMoreSize: 5,
    empty: { 
        tip: '~ 空空如也 ~',
        icon: "../../static/images/mescroll-empty.png"
    },
    textLoading: '加载中...',
    textNoMore: '已经到底了'
});

const downOption = ref({
    auto: false,
    textInOffset: '下拉刷新',
    textOutOffset: '释放更新',
    textLoading: '刷新中...'
});

let cssFlag=ref(false);//控制样式
const mescrollInit = (mescroll) => {
    cssFlag.value = true;
    mescrollRef.value = mescroll;
};

// 下拉刷新
const downCallback = async (mescroll) => {
    try {
        console.log("下拉刷新")
        const res = await getNoticeList(1, upOption.value.page.size);
        cssFlag.value = false;
        list.value = res.list;
        // mescroll.resetUpScroll();
    } catch (error) {
        mescroll.endErr();
    } finally {
        setTimeout(async ()=>{
            mescroll.endSuccess();
        },500);
    }
}
// 上拉加载更多
const upCallback = async (mescroll) => {
    try {
        console.log("上拉加载更多")
        let res = await getNoticeList(mescroll.num, mescroll.size);
        if (mescroll.num === 1) {
            list.value = res.list;
        } else {
            list.value.push(...res.list);
        }
        mescroll.endBySize(res.list.length, res.total);
    } catch (error) {
        mescroll.endErr();
    }
}

// 获取数据列表
const getNoticeList = (pageIndex, pageSize) => {
    return new Promise(async (resolve) => {
        let param = {
            pageIndex,
            pageSize,
            searchValue:searchText.value?searchText.value:undefined,
            type:notictTypeCheck.value.id
        }
        
        let res = await noticeList(param);
        let list = res.list || [];
        list.forEach(item=>{
            const randomIndex = Math.floor(Math.random() * images.length)
            item.imgSrc =  images[randomIndex];
        })
        resolve({
            list,
            total: res.recordCount || 0
        });
    });

}

// 跳转webview
const handleJump = (item)=>{
    uni.navigateTo({
        // url: '/pages/h5-webview/h5-webview?url=' + item.mobileLink+"&title="+item.subject
        url:'/pages/notice/noticeDetail?title='+item.subject+'&time='+item.createTime+'&appName='+item.appName
    });
}
</script>

<style scoped>
.all-body{
    position: absolute;
    /* #ifdef APP-PLUS */
    top:150rpx;
    height: calc(100vh - 75px);
    /* #endif */
    /* #ifndef APP-PLUS */
    top:120rpx;
    height: calc(100vh - 64px);
    /* #endif */
    overflow: hidden;
}


:deep(.mescroll-downwarp .downwarp-progress){
    border-color:#fff !important;
}

:deep(.mescroll-downwarp .downwarp-tip){
    color:#fff;
}


.white-bg {
    width: 750rpx;
    padding: 40rpx 0 20rpx;
    margin-bottom:0;
    border-radius: 8px 8px 0 0;
}
.white-bg.bg-height{
    /* #ifdef APP-PLUS */
    height: calc(100vh - 145px);
    /* #endif */
    /* #ifndef APP-PLUS */
    height: calc(100vh - 175px);
    /* #endif */
}
.scroll-h{
    /* #ifdef APP-PLUS */
    height: calc(100vh - 150px);
    /* #endif */
    /* #ifndef APP-PLUS */
    height: calc(100vh - 160px);
    /* #endif */
}

.white-bg .notice-list {
    display: flex;
    padding: 0 30rpx 0 40rpx;
    margin-bottom: 30rpx;
}

.white-bg .notice-list .img-w{
    width: 80rpx;
    height: 80rpx;
    margin-right: 30rpx;
}

.white-bg .notice-list .notice-item {
    border-bottom: 1px solid #E7E7E7;
    width: 570rpx;
    padding-bottom: 30rpx;
    position: relative;
}

.white-bg .notice-list:last-child .notice-item {
    border-bottom: none;
    padding-bottom: 0;
}

.white-bg .notice-list .notice-title {
    font-size: 32rpx;
    width: 530rpx;
    white-space: nowrap;
    /* 禁止换行 */
    overflow: hidden;
    /* 隐藏溢出内容 */
    text-overflow: ellipsis;
    /* 显示省略号 */
}

.white-bg .notice-list .notice-title.bold {
    font-weight: bold;
}

.white-bg .notice-list .notice-date {
    color: #BFBFBF;
    font-size: 28rpx;
    margin-top: 10rpx;
}

.white-bg .notice-list .notice-item .dot {
    position: absolute;
    right: 0;
    top: 14rpx;
}
</style>