<script setup>
import {reactive,ref, watch,onUnmounted,onMounted,onUpdated,onActivated,computed} from 'vue'
import SelfList from '@/components/SelfList.vue'
import SharePoster from '@/components/SharePoster.vue'
import { useRouter } from "vue-router";
import {formatActivityTime} from './utils'

const router=useRouter()

import {apiActivityList} from '@/api/activity.js'
let listData=reactive({
    tabActive:'3',
    statusActive: '1',
    onlySeeAuth:false,
    loading:false,
    finished:false,
    page:1,
    list:[]
})
const tabChange=(e)=>{
    listData.tabActive=e
    listData.statusActive='1'
    refresh()
}
const statusChange=(e)=>{
    listData.statusActive=e
    refresh()
}
const authChange=(e)=>{
    listData.onlySeeAuth=e
    refresh()
}
const refresh=()=>{
    listData.page=1
    listData.finished=false
    listData.list=[]
    getList()
}
const getList=async ()=>{
    listData.loading=true
    const res=await apiActivityList({
        active_state: Number(listData.statusActive),
        activity_type: Number(listData.tabActive),
        has_permission:listData.onlySeeAuth?1:0,
        page: listData.page,
        limit: 20
    })
    listData.loading=false
    if(listData.page==1){
        document.body.scrollTop=document.documentElement.scrollTop=0
    }
    if(res.code===200){
        if(res.data){
            listData.list = [...listData.list, ...res.data]
            if(res.data.length<20){
                listData.finished=true
            }
        }else{
            listData.finished=true
        }
    }
}

// 获取个人信息判断是否默认选中只看有权限的
let hasInit=ref(false)
import {apiUserInfo} from '@/api/user.js'
const init=async ()=>{
    console.log('init');
    hasInit.value=false
    const res=await apiUserInfo()
    if(res.code===200){
        if(['正式','永续'].includes(res.data.status)){
            listData.onlySeeAuth=true
        }
        if(res.data.status=='试用'&&res.data.is_suspend==0){
            listData.onlySeeAuth=true
        }
        getList()
        hasInit.value=true
    }
    store.commit('modifyBreadCrumb','线下沙龙')
}
init()

// 触底加载
const onLoad=()=>{
    if(listData.finished||listData.loading) return
    listData.page++
    getList()
}

// 跳转详情
const goDetail=(id)=>{
    if(store.state.userInfo.is_bind===0){
        ElMessageBox({
            title:`温馨提示`,
            message:'为了优化您的用户体验，<br>请登录后查看更多信息！',
            dangerouslyUseHTMLString: true,
            center: true,
            confirmButtonText:'去登录',
            confirmButtonClass:'self-elmessage-confirm-btn',
            showCancelButton:true,
            cancelButtonText:'取消',
            cancelButtonClass:'self-elmessage-cancel-btn'
        }).then(res=>{
            wx.miniProgram.reLaunch({url:'/pages/login'})
        }).catch(()=>{})
        return
    }
    router.push({
        path:'/activity/detail',
        query:{
            id:id
        }
    })
}
import { ElMessage,ElMessageBox } from 'element-plus'
import {apiActivityAddRemind,apiActivityCancelRemind,apiActivityRegister,apiActivityCancelRegister} from '@/api/activity.js'
import {applyAuth} from './applyAuth'
// 添加/取消提醒
const handleRemind=(item)=>{
    if(store.state.userInfo.is_bind===0){
        ElMessageBox({
            title:`温馨提示`,
            message:'为了优化您的用户体验，<br>请登录后查看更多信息！',
            dangerouslyUseHTMLString: true,
            center: true,
            confirmButtonText:'去登录',
            confirmButtonClass:'self-elmessage-confirm-btn',
            showCancelButton:true,
            cancelButtonText:'取消',
            cancelButtonClass:'self-elmessage-cancel-btn'
        }).then(res=>{
            wx.miniProgram.reLaunch({url:'/pages/login'})
        }).catch(()=>{})
        return
    }
    if(item.hasRemind===0){
        addRemind(item)
    }else{
        cancelRemind(item)
    }
}
// 添加提醒
const addRemind=async (item)=>{
    const res=await apiActivityAddRemind({activity_id:Number(item.activityId)})
    if(res.code===200){
        item.hasRemind=1
    }
    applyAuth(res,'会议',2,'活动列表')
}
//取消提醒
const cancelRemind=async (item)=>{
    const res=await apiActivityCancelRemind({activity_id:Number(item.activityId)})
    if(res.code===200){
        ElMessage('取消提醒成功')
        item.hasRemind=0
    }else if(res.code===403){
        ElMessage.warning(res.msg)
    }
}

// 报名/取消报名 线下参会
const handleRegister=(item)=>{
    if(store.state.userInfo.is_bind===0){
        ElMessageBox({
            title:`温馨提示`,
            message:'为了优化您的用户体验，<br>请登录后查看更多信息！',
            dangerouslyUseHTMLString: true,
            center: true,
            confirmButtonText:'去登录',
            confirmButtonClass:'self-elmessage-confirm-btn',
            showCancelButton:true,
            cancelButtonText:'取消',
            cancelButtonClass:'self-elmessage-cancel-btn'
        }).then(res=>{
            wx.miniProgram.reLaunch({url:'/pages/login'})
        }).catch(()=>{})
        return
    }
    if(item.registerState===0){
        addRegister(item)
    }else{
        cancelRegister(item)
    }
}
// 报名
const addRegister=async (item)=>{
    const res=await apiActivityRegister({activity_id:Number(item.activityId)})
    if(res.code===200){
        item.registerState=1
    }
    applyAuth(res,'活动',2,'活动列表')
}
//取消报名
const cancelRegister=async (item)=>{
    const res=await apiActivityCancelRegister({activity_id:Number(item.activityId)})
    if(res.code===200){
        ElMessage('取消报名成功')
        item.registerState=0
    }else if(res.code===403){
        ElMessage.warning(res.msg)
    }
}


// 获取音频
import { useStore } from "vuex";
const store = useStore();
import {apiActivityAudios} from '@/api/activity'
const handleGetAudio=async (item)=>{
    if(store.state.userInfo.is_bind===0){
        ElMessageBox({
            title:`温馨提示`,
            message:'为了优化您的用户体验，<br>请登录后查看更多信息！',
            dangerouslyUseHTMLString: true,
            center: true,
            confirmButtonText:'去登录',
            confirmButtonClass:'self-elmessage-confirm-btn',
            showCancelButton:true,
            cancelButtonText:'取消',
            cancelButtonClass:'self-elmessage-cancel-btn'
        }).then(res=>{
            wx.miniProgram.reLaunch({url:'/pages/login'})
        }).catch(()=>{})
        return
    }
    if(store.state.audioData.list.length>0&&store.state.audioData.activityId==item.activityId){
        if(store.state.audioData.paused){
            store.state.audioData.INS.play()
        }else{
            store.state.audioData.INS.pause()
        }
        return
    }
    if(!(item.firstActivityTypeId===1&&item.activityState===3&&item.hasPlayBack)) return
    const res=await apiActivityAudios({activity_id:Number(item.activityId)})
    if(res.code===200){
        const arr=res.data.map(_item=>{
            return {
                name:_item.voiceName,
                url:_item.voiceUrl,
                time:_item.voicePlaySeconds,
                activityId:_item.activityId,
                activity_voice_id:_item.activity_voice_id
            }
        })
        store.commit('addAudio',{
            list:arr,
            activityId:item.activityId,
            index:0
        })
    }else if(res.code===403){
        applyAuth(res,'会议',2,'活动列表')
    }
}


// 监听详情的会议提醒\报名状态是否变化
const subscribeUpdateActivitStatus=store.subscribe((mutation, state) => {
  if(mutation.type==='updateActivityStatus'){
        console.log('更新列表项状态',mutation);
        listData.list.forEach(item=>{
            if(item.activityId==mutation.payload.activityId){
                if(mutation.payload.type=='会议'){
                    if(item.hasRemind===0){
                        item.hasRemind=1
                    }else{
                        item.hasRemind=0
                    }
                }else{
                    if(item.registerState===0){
                        item.registerState=1
                    }else{
                        item.registerState=0
                    }
                }
            }
        })
  }
})

onUnmounted(()=>{
    // 取消监听 活动报名状态
    subscribeUpdateActivitStatus()
})

const aduioIconPlay=new URL('../../assets/audio-doing-white.png', import.meta.url).href
const aduioIconPaused=new URL('../../assets/audio-pause-white.png', import.meta.url).href
const aduioIconDefault=new URL('../../assets/audio-pause.png', import.meta.url).href

onMounted(() => {
  //向小程序发送消息
  let postData = {
    path: "/pages/activity/activity",
    params:{},
    title: "弘则FICC线下沙龙",
    shareImg:'https://hzstatic.hzinsights.com/static/icon/hzyb/activitylist_share.jpg'
  };
  wx.miniProgram.postMessage({ data: postData });
  store.commit('modifyBreadCrumb','线下沙龙')
});

onActivated(()=>{//解决从详情返回到列表 分享时还是详情问题
    //向小程序发送消息
    let postData = {
        path: "/pages/activity/activity",
        params:{},
        title: "弘则FICC线下沙龙",
        shareImg:'https://hzstatic.hzinsights.com/static/icon/hzyb/activitylist_share.jpg'
    };
    wx.miniProgram.postMessage({ data: postData });
    setTimeout(() => {
        store.commit('modifyBreadCrumb','线下沙龙')
    }, 300);
})


const posterParams=computed(()=>{
    let obj={
        list_title:listData.tabActive === '1'?'线上会议':'线下沙龙',
        status_1:'',
        avatar_1:'',
        title_1:'',
        speaker_1:'',
        time_1:'',
        status_2:'',
        avatar_2:'',
        title_2:'',
        speaker_2:'',
        time_2:'',
    }
    if(listData.list[0]){
        obj.status_1=listData.list[0].activityState==1?'未开始':listData.list[0].activityState==2?'进行中':'已结束'
        obj.avatar_1=listData.list[0].speakerHeadPic
        obj.title_1=listData.list[0].activityTypeName
        obj.speaker_1=listData.list[0].speaker
        obj.time_1=formatActivityTime(listData.list[0].startTime,listData.list[0].endTime)
    }
    if(listData.list[1]){
        obj.status_2=listData.list[1].activityState==1?'未开始':listData.list[1].activityState==2?'进行中':'已结束'
        obj.avatar_2=listData.list[1].speakerHeadPic
        obj.title_2=listData.list[1].activityTypeName
        obj.speaker_2=listData.list[1].speaker
        obj.time_2=formatActivityTime(listData.list[1].startTime,listData.list[1].endTime)
    }

    return obj
})

</script>


<template>
    <div class="activity-list-page">
        <div class="top-nav-wrap">
            <!-- <div class="nav-first">
                <span :class="listData.tabActive==1&&'active'" @click="tabChange('1')">报告及线上会议</span>
                <span :class="listData.tabActive==3&&'active'" @click="tabChange('3')">线下沙龙</span>
            </div> -->
            <div class="status-box">
                <span :class="listData.statusActive==1&&'active'" @click="statusChange('1')">本周预告</span>
                <span :class="listData.statusActive==2&&'active'" @click="statusChange('2')">进行中</span>
                <span :class="listData.statusActive==3&&'active'" @click="statusChange('3')">已结束</span>
                <el-checkbox v-model="listData.onlySeeAuth" size="large" @change="authChange">只看有权限</el-checkbox>
            </div>
        </div>
        <SelfList 
            class="list-wrap" 
            :finished="listData.finished" 
            :isEmpty="listData.list.length===0&&listData.finished"
            :loading="listData.loading"
            :count="listData.list.length"
            @listOnload="onLoad"
        >
            <li class="flex item" v-for="item in listData.list" :key="item.activityId" @click="goDetail(item.activityId)">
                <el-image
                    style="width: 74px; height: 104px;border-radius: 4px;flex-shrink: 0;"
                    :src="item.speakerHeadPic"
                    fit="cover"
                ></el-image>
                <div class="flex content">
                    <div v-if="item.firstActivityTypeId===3&&item.city" class="city-box">{{item.city}}</div>
                    <div>
                        <h2 class="title">
                            <span>{{item.activityTypeName}}</span>
                            <span class="status-box status-before" v-if="item.activityState===1">未开始</span>
                            <span class="status-box status-progress" v-if="item.activityState===2">进行中</span>
                            <span class="status-box status-end" v-if="item.activityState===3">已结束</span>
                        </h2>
                        <p class="speaker">主讲：{{item.speaker}}</p>
                    </div>
                    <div class="flex bot">
                        <span class="time">{{formatActivityTime(item.startTime,item.endTime)}}</span>
                        <div>
                            <template v-if="item.activityState===1">
                                <span 
                                    style="width:138px"
                                    :class="['btn',item.registerState&&'active']"
                                    v-if="item.firstActivityTypeId===3"
                                    @click.stop="handleRegister(item)"
                                >{{item.registerState?'取消线下报名':'报名线下参会'}}</span>
                                <span :class="['btn',item.hasRemind&&'active']" @click.stop="handleRemind(item)">{{item.hasRemind?'取消提醒':'会议提醒'}}</span>
                            </template>
                            <!-- 音频播放 -->
                            <div 
                                :class="['btn-audio',$store.state.audioData.activityId==item.activityId&&'btn-audio-active']" 
                                v-if="item.firstActivityTypeId===1&&item.activityState===3&&item.hasPlayBack"
                                @click.stop="handleGetAudio(item)"
                            >
                                <span 
                                    :class="['icon-audio',$store.state.audioData.activityId==item.activityId?$store.state.audioData.paused?'icon-audio-paused':'icon-audio-play':'icon-audio-default']" 

                                    :src="$store.state.audioData.activityId==item.activityId?$store.state.audioData.paused?aduioIconPaused:aduioIconPlay:aduioIconDefault" 
                                ></span>
                                <span style="vertical-align: middle;line-height: 1">{{
                                    $store.state.audioData.activityId==item.activityId?$store.state.audioData.paused?'已暂停':'播放中':'回放'
                                }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </li>
        </SelfList>
    </div>

    <!-- 生成海报 -->
    <SharePoster  
        :shareData="{
            type:'activity_list',
            code_page:'pages/activity/activity',
            code_scene:'',
            data:posterParams
        }"
    ></SharePoster>
</template>

<style lang="scss" scoped>
 .activity-list-page{
    // height: 100%;
    // overflow-y: auto;
    .top-nav-wrap{
        width: 100%;
        padding-top: 30px;
        padding-bottom: 20px;
        background-color: #fff;
        position: fixed;
        top: 60px;
        z-index: 99;
        .nav-first{
            margin-bottom: 20px;
            span{
                display: inline-block;
                width: 140px;
                height: 40px;
                background-color: #F6F6F6;
                border-radius: 20px;
                text-align: center;
                line-height: 40px;
                margin-right: 20px;
                cursor: pointer;
                font-size: 16px;
                box-sizing: border-box;
                border: 1px solid transparent;
                &:hover{
                    background: #FFFBF5;
                    box-shadow: 0px 6px 7px 1px #FFF7EB;
                    border-radius: 20px 20px 20px 20px;
                    border: 1px solid #F3A52F;
                    color: #F3A52F;
                }
            }
            .active{
                background: #FFFBF5;
                box-shadow: 0px 6px 7px 1px #FFF7EB;
                border-radius: 20px 20px 20px 20px;
                border: 1px solid #F3A52F;
                color: #F3A52F;
            }
            :deep(.el-checkbox.el-checkbox--large .el-checkbox__label){
                color: #F3A52F;
            }
            :deep(.el-checkbox__input.is-checked .el-checkbox__inner){
                background-color: #F3A52F;
                border-color: #F3A52F;
            }
            :deep(.el-checkbox__inner){
                border-color: #F3A52F;
            }
        }
        .status-box{
            span{
                color: #999999;
                font-size: 16px;
                padding: 3px 0;
                margin-right: 37px;
                cursor: pointer;
                &:hover{
                    color: #F3A52F;
                }
            }
            .active{
                color: #F3A52F;
                position: relative;
                // &::after{
                //     content:'';
                //     display: block;
                //     width: 40px;
                //     height: 4px;
                //     border-radius: 2px;
                //     background: #F3A52F;
                //     position: absolute;
                //     left: 50%;
                //     transform: translateX(-50%);
                //     bottom: -5px;
                // }
            }
        }
    }
    .empty-list{
        margin-top: 100px;
    }
    .list-wrap{
        border-radius: 4px;
        margin-top: 100px;
        .item{
            border-bottom: 1px solid #F2F2F2;
            padding: 16px 0;
            .content{
                margin-left: 20px;
                flex:1;
                flex-direction: column;
                justify-content: space-between;
                position: relative;
                .title{
                    font-size: 20px;
                    margin-top: 0;
                    margin-bottom: 14px;
                    margin-right: 60px;
                    .status-box{
                        width: 69px;
                        height: 28px;
                        line-height: 28px;
                        display: inline-block;
                        text-align: center;
                        font-size: 14px;
                        font-weight: 600;
                        border-radius: 4px;
                        margin-left: 20px;
                    }
                    .status-before{
                        background-color: #FFFBF5;
                        color: #F3A52F;
                    }
                    .status-progress{
                        background-color: #F2F6FF;
                        color: #688EEC;
                    }
                    .status-end{
                        background-color: #F2F2F2;
                        color: #333;
                    }
                }
                .speaker{
                    margin: 0;
                    font-size: 16px;
                }
                .city-box{
                    color: #F3A52F;
                    font-size: 14px;
                    position: absolute;
                    top: 0;
                    right: 0;
                    &::before{
                        content: '';
                        display: inline-block;
                        width: 15px;
                        height: 15px;
                        background-image: url('@/assets/location.png');
                        background-size: cover;
                        margin-right: 5px;
                        position: relative;
                        top: 3px;
                    }
                }
                .bot{
                    justify-content: space-between;
                    align-items: flex-end;
                    .time{
                        font-size: 14px;
                        color: #999;
                    }
                    .btn{
                        min-width: 100px;
                        height: 28px;
                        background-color: #fff;
                        border-radius: 14px;
                        display: inline-block;
                        margin-left: 20px;
                        text-align: center;
                        line-height: 28px;
                        cursor: pointer;
                        color: #F3A52F;
                        border: 1px solid #F3A52F;
                        &:hover{
                            background-color: #F3A52F;
                            color: #fff;
                        }
                    }
                    .active{
                        background: #F6F6F6;
                        color: #666666;
                        border: none;
                    }
                    .btn-audio{
                        width: 100px;
                        height: 28px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        cursor: pointer;
                        color: #F3A52F;
                        border: 1px solid #F3A52F;
                        background-color: #fff;
                        border-radius: 14px;
                        &:hover{
                            background-color: #F3A52F;
                            color: #fff;
                            .icon-audio-default{
                                background-image:url('@/assets/audio-pause-white.png');
                            }

                        }
                    }
                    .btn-audio-active{
                        background: #F3A52F;
                        color: #fff;
                        border: none;
                    }
                    .icon-audio{
                        width: 17px;
                        height: 17px;
                        vertical-align: middle;
                        margin-right: 6px;
                        background-size:cover;
                        background-repeat:no-repeat;
                    }
                    .icon-audio-paused{
                        background-image:url('@/assets/audio-pause-white.png');
                    }
                    .icon-audio-play{
                        background-image:url('@/assets/audio-doing-white.png');
                    }
                    .icon-audio-default{
                        background-image:url('@/assets/audio-pause.png');
                    }
                }
            }
        }
    }
}
</style>