<script setup>
import { computed, reactive, ref,onMounted } from "vue";
import SharePoster from '@/components/SharePoster.vue'
import { useRoute,useRouter } from "vue-router";
import { formatActivityTime } from "./utils";
import { ElMessage } from 'element-plus'

const router=useRouter()

const route = useRoute();

// 获取详情
import { apiActivityDetail } from "@/api/activity.js";
let noAuth=reactive({
    show:false,
    data:null
})
let info = ref(null);
let infoList = ref(null)
const getDetail = async () => {
    const res = await apiActivityDetail({
        activity_id: Number(route.query.id),
    });
    if (res.code === 200) {
        info.value = res.data;
        let arr = [
            {
                label: "大陆拨号",
                text: res.data.mainlandTel,
                color: "yellow",
                type: "tel",
            },
            {
                label: "香港拨入",
                text: res.data.hongKongTel,
                color: "yellow",
                type: "tel",
            },
            {
                label: "台湾拨入",
                text: res.data.taiwanTel,
                color: "yellow",
                type: "tel",
            },
            {
                label: "新加坡拨入",
                text: res.data.singaporeTel,
                color: "yellow",
                type: "tel",
            },
            {
                label: "美国拨入",
                text: res.data.americaTel,
                color: "yellow",
                type: "tel",
            },
            {
                label: "拨入密码",
                text: res.data.participationCode,
            },
        ];
        infoList.value = arr.filter((item) => {
            return item.text;
        });
        // 研究员线下沙龙
        if (res.data.firstActivityTypeId === 3) {
            if (res.data.linkParticipants) {
                infoList.value.push({ label: "网络参会", text: res.data.linkParticipants, color: "yellow", type: "copy" });
            }
        }
        handleShareMsg()
    }else if(res.code===403){//无权限
        noAuth.show=true
        noAuth.data=res.data
    }
};
getDetail();

// 处理分享数据
const handleShareMsg=()=>{
    //向小程序发送消息

    // let title=''
    //     if(this.info.firstActivityTypeId==1){
    //         title=this.info.reportName.split('】')[1]||this.info.activityName
    //         if(this.info.is_new_report==1){
    //             title=this.info.reportName
    //         }
    //     }else{
    //         title=this.info.activityName
    //     }
    let title=info.value.activityName
    // if(info.value.firstActivityTypeId==1){
    //     title=info.value.reportName.split('】')[1]||info.value.activityName
    //     if(info.value.is_new_report==1){
    //         title=info.value.reportName
    //     }
    // }else{
    //     title=info.value.activityName
    // }

    let shareImg=`${import.meta.env.VITE_APP_API_URL}/activity/getActivityShareImg?activity_id=${info.value.activityId}`//分享海报

    let postData = {
        path: "/pages-activity/detail",
        params:{
            id:info.value.activityId
        },
        title: title,
        shareImg:shareImg
    };
    wx.miniProgram.postMessage({ data: postData });
}

// 获取活动音频
import {apiActivityAudios} from '@/api/activity.js'
let audioList=ref([])
const getAudio=async ()=>{
    const res=await apiActivityAudios({activity_id: Number(route.query.id)})
    if(res.code===200){
        const arr=res.data||[]
        audioList.value=arr.map(_item=>{
            return {
                name:_item.voiceName,
                url:_item.voiceUrl,
                time:_item.voicePlaySeconds,
                activityId:_item.activityId,
                activity_voice_id:_item.activity_voice_id
            }
        })
    }
}
getAudio()

// 格式化音频时间
const formatAudioTime=(e)=>{
    let minus=parseInt(e/60)
    let sec=e%60
    return `${minus>9?minus:'0'+minus}分${sec>9?sec:'0'+sec}秒`
}

// 跳转报告详情
const goDetail=()=>{
    if(info.value.is_new_report){
        router.push({
            path:'/report/detail',
            query:{
                reportId:info.value.report_id
            }
        })
        return
    }
    let params=info.value.reportLink.split('?')[1]
    let research_report_id=params.split('=')[1]
    router.push({
        path:'/activity/reportdetail',
        query:{
            research_report_id:research_report_id
        }
    })
}


import { useStore } from "vuex";
const store=useStore()
const curAudiourl=computed(()=>{
    return store.state.audioData.list[store.state.audioData.index]&&store.state.audioData.list[store.state.audioData.index].url
})
const aduioIconDefault=new URL('../../assets/audio-pause-2.png', import.meta.url).href
const aduioIconPlay=new URL('../../assets/audio-doing.png', import.meta.url).href
const aduioIconPause=new URL('../../assets/audio-pause-3.png', import.meta.url).href
const handlePlayAudio=(index)=>{
    if(store.state.audioData.activityId==route.query.id){//同一个活动
        if(store.state.audioData.list.length>0&&store.state.audioData.index==index){
            if(store.state.audioData.paused){
                store.state.audioData.INS.play()
            }else{
                store.state.audioData.INS.pause()
            }
        }else{
            store.commit('addAudio',{list:audioList.value,activityId:route.query.id,index:index})
        }
    }else{
        store.commit('addAudio',{list:audioList.value,activityId:route.query.id,index:index})
    }
}

//返回
const goBack=()=>{
    if(window.history.state.back){
        console.log('返回上一页');
        router.go(-1)
    }else{
        console.log('返回首页');
        router.push({path:'/report/index'})
    }
}

// 申请
import {apiApplyPermission} from '@/api/user'
import {ElMessageBox} from 'element-plus'
const handleApply=()=>{
    if(noAuth.data.type=='apply'){
        if(noAuth.data.customer_info.has_apply){//已经申请过
            const htmlStr=`<p>您已提交过申请，请耐心等待</p>`
            ElMessageBox({
                title:`会议提醒`,
                message:htmlStr,
                center: true,
                dangerouslyUseHTMLString: true,
                confirmButtonText:'知道了',
                confirmButtonClass:'self-elmessage-confirm-btn'
            })
        }else{
            if(!noAuth.data.customer_info.status||noAuth.data.customer_info.status!='流失'||noAuth.data.customer_info.status!='关闭'){
                console.log('跳转申请页');
                router.push({
                    path:'/apply/permission',
                    query:{
                        source:2,
                        fromPage:'活动详情'
                    }
                })
            }else{//主动调一次申请权限接口 
                apiApplyPermission({
                    company_name:noAuth.data.customer_info.company_name,
                    real_name:noAuth.data.customer_info.name,
                    source:2,
                    from_page:'活动详情'
                }).then((res)=>{
                    if(res.code===200){
                        console.log('主动申请成功');
                        const htmlStr=`<p>申请已提交</p><p>请等待销售人员与您联系</p>`
                        ElMessageBox({
                            title:`会议提醒`,
                            message:htmlStr,
                            center: true,
                            dangerouslyUseHTMLString: true,
                            confirmButtonText:'知道了',
                            confirmButtonClass:'self-elmessage-confirm-btn'
                        })
                    }
                })
            }
        }
    }
}


// 会议提醒\报名会议
import {apiActivityAddRemind,apiActivityCancelRemind,apiActivityRegister,apiActivityCancelRegister} from '@/api/activity.js'
import {applyAuth} from './applyAuth'
// 添加/取消提醒
const handleRemind=()=>{
    if(info.value.hasRemind ==0){
        addRemind()
    }else{
        cancelRemind()
    }
}
// 添加提醒
const addRemind=async ()=>{
    const res=await apiActivityAddRemind({activity_id:Number(info.value.activityId)})
    if(res.code===200){
        info.value.hasRemind=1
        store.commit('updateActivityStatus',{activityId:info.value.activityId,type:'会议'})
    }
    applyAuth(res,'会议',2,'活动列表')
}
//取消提醒
const cancelRemind=async ()=>{
    const res=await apiActivityCancelRemind({activity_id:Number(info.value.activityId)})
    if(res.code===200){
        ElMessage('取消提醒成功')
        info.value.hasRemind=0
        store.commit('updateActivityStatus',{activityId:info.value.activityId,type:'会议'})
    }else if(res.code===403){
        ElMessage.warning(res.msg)
    }
}

// 报名/取消报名 线下参会
const handleRegister=()=>{
    if(info.value.registerState===0){
        addRegister()
    }else{
        cancelRegister()
    }
}
// 报名
const addRegister=async ()=>{
    const res=await apiActivityRegister({activity_id:Number(info.value.activityId)})
    if(res.code===200){
        info.value.registerState=1
        store.commit('updateActivityStatus',{activityId:info.value.activityId,type:'报名'})
        getDetail()
    }
    applyAuth(res,'活动',2,'活动列表')
}
//取消报名
const cancelRegister=async ()=>{
    const res=await apiActivityCancelRegister({activity_id:Number(info.value.activityId)})
    if(res.code===200){
        ElMessage('取消报名成功')
        info.value.registerState=0
        store.commit('updateActivityStatus',{activityId:info.value.activityId,type:'报名'})
        getDetail()
    }else if(res.code===403){
        ElMessage.warning(res.msg)
    }
}


const code_scene=computed(()=>{
    return JSON.stringify({id:route.query.id})
})

const posterParams=computed(()=>{
    if(info.value){
        let obj={
            activity_title:info.value.activityTypeName+'电话会',
            activity_speaker:info.value.speaker,
            activity_time:formatActivityTime(info.value.startTime,info.value.endTime),
            activity_avatar:info.value.speakerHeadPic
        }  
        return obj
    }
    
})


</script>

<template>
    <div class="activity-detail-page" v-if="info">
        <div class="top-box" :style="'background-image:url(' + info.speakerBackgroundPic + ')'">
            <span class="status-box status-before" v-if="info.activityState===1">未开始</span>
            <span class="status-box status-progress" v-if="info.activityState===2">进行中</span>
            <span class="status-box status-end" v-if="info.activityState===3">已结束</span>
            <h2 class="type-title">{{info.activityTypeName}}</h2>
            <div class="speaker">主讲人：{{ info.speaker }}</div>
            <div class="active-time"> 活动时间：{{ formatActivityTime(info.startTime, info.endTime) }}</div>
        </div>
        <div class="flex report-name">
            <span>{{ info.activityName }}</span>
            <!-- <span>{{ info.is_new_report==1?info.reportName:info.reportName?info.reportName.split('】')[1]:info.activityName }}</span> -->
            <div class="global-main-btn" v-if="info.reportLink" @click="goDetail">查看相关报告</div>
        </div>
        <!-- 音频模块 -->
        <div class="audio-wrap" v-if="audioList.length>0">
            <div 
                class="flex audio-item" 
                v-for="(item,index) in audioList" 
                :key="item.url"
            >
                <img @click="handlePlayAudio(index)" :src="curAudiourl==item.url?$store.state.audioData.paused?aduioIconPause:aduioIconPlay:aduioIconDefault" alt="">
                <div :class="['name',curAudiourl==item.url&&'name-active']">{{item.name}}</div>
                <!-- <span class="time">{{formatAudioTime(item.voicePlaySeconds)}}</span> -->
            </div>
        </div>
        <!-- 数据显示模块 -->
        <div class="info-wrap">
            <div
                class="flex item"
                v-for="item in infoList"
                :key="item.label"
            >
                <div class="label">{{ item.label }}：</div>
                <div
                    :class="[
                        'content',
                        item.color && 'yellow-color',
                        item.type == 'copy' && 'link',
                    ]"
                >
                    {{item.text}}
                </div>
            </div>
        </div>
        <!-- 按钮模块 -->
        <div class="btn-box" v-if="info.activityState === 1">
            <div 
                :class="[
                    'global-plain-btn btn',
                    info.registerState != 0?'grey-btn':''
                ]" 
                style="margin-bottom: 20px;"
                v-if="info.firstActivityTypeId === 3" 
                @click="handleRegister"
            >
                {{
                    info.registerState == 0
                    ? "报名线下参会"
                    : "取消报名线下参会"
                }}
                ({{ info.registeredNum>info.limitPeopleNum?info.limitPeopleNum:info.registeredNum }}/{{ info.limitPeopleNum }})
            </div>
            <div 
                :class="['global-plain-btn btn',info.hasRemind == 1&&'grey-btn']"
                @click="handleRemind"
            >{{info.hasRemind == 1 ? "取消会议提醒" : "会议提醒"}}</div>
            <p style="text-align:center;color:#999;font-size: 16px;">(会前15分钟推送微信消息提醒)</p>
        </div>
    </div>
    <!-- 无权限 -->
    <div class="no-auth-wrap" v-if="noAuth.show">
        <img :src="$store.state.globalImgUrls.activityNoAuth" alt="">
        <p style="font-size:16px;margin-bottom: 0;">您暂无权限参加此活动</p>
        <block v-if="noAuth.data.type=='contact'">
            <p style="font-size:16px;margin-top: 5px;margin-bottom: 62px;">若想参加，可以联系对口销售--{{noAuth.data.name}}：{{noAuth.data.mobile}}</p>
        </block>
        <block v-else>
            <p style="font-size:16px;margin-top: 5px;margin-bottom: 62px;">若想参加可以申请开通</p>
            <div class="global-main-btn btn" @click="handleApply" style="margin-bottom: 20px;">立即申请</div>
        </block>
        <div class="global-plain-btn btn" @click="goBack">返回</div>
    </div>

    <!-- 生成海报 -->
    <SharePoster 
        v-if="!noAuth.show" 
        :shareData="{
            type:'activity_detail',
            code_page:'pages-activity/detail',
            code_scene:code_scene,
            data:posterParams
        }"
    ></SharePoster>
</template>

<style lang="scss" scoped>
.activity-detail-page {
    .top-box{
        height: 186px;
        background-size: cover;
        background-repeat: no-repeat;
        background-position: center center;
        border-radius: 4px;
        padding-top: 20px;
        padding-left: 20px;
        color: #fff;
        position: relative;
        .type-title{
            font-size: 24px;
            margin: 0;
        }
        .speaker{
            margin-top: 19px;
            font-size: 14px;
        }
        .active-time{
            margin-top: 24px;
            font-size: 14px;
        }
        .status-box{
            position: absolute;
            top: 0;
            right: 0;
            font-size: 14px;
            background: #F2F2F2;
            border-radius: 0px 0px 0px 4px;
            padding: 4px 14px;
        }
        .status-before{
            color: #F3A52F;
            background: #FFFBF5;
        }
        .status-progress{
            color: #2A65F5;
            background: #F2F6FF;
        }
        .status-end{
            color: #333;
        }
    }
    .report-name{
        padding-top: 40px;
        padding-bottom: 30px;
        border-bottom: 1px solid #F2F2F2;
        span{
            font-size: 18px;
            font-weight: bold;
            flex: 1;
            &::before{
                content: '';
                display: inline-block;
                width: 6px;
                height: 24px;
                background: #F3A52F;
                position: relative;
                top: 6px;
                margin-right: 10px;
            }
        }
        .global-main-btn{
            flex-shrink: 0;
            margin-left: 30px;
            width: 218px;
        }
    }

    .audio-wrap{
        padding-top: 30px;
        padding-bottom: 30px;
        border-bottom: 1px solid #F2F2F2;
        .audio-item{
            align-items: center;
            margin-bottom: 20px;
            &:last-child{
                margin-bottom: 0;
            }
            img{
                width: 17px;
                height: 17px;
                flex-shrink: 0;
                cursor: pointer;
            }
            .name{
                flex: 1;
                margin: 0 10px;
                font-size: 16px;
            }
            .name-active{
                color: #F3A52F;
            }
            .time{
                color: #B6B6B6;
            }
        }
    }

    .info-wrap {
        padding-top: 30px;
        .item {
            margin-bottom: 20px;
            font-size: 16px;
            .label {
                flex-shrink: 0;
            }
            .yellow-color {
                color: #F3A52F;
            }
        }
    }

    .btn-box{
        .btn{
            width: 218px;
            margin-left: auto;
            margin-right: auto;
        }
        .grey-btn{
            background-color: #F6F6F6;
            color: #333;
            border: none;
        }
    }
}
.no-auth-wrap{
        text-align: center;
        img{
            width: 400px;
        }
        .btn{
            width: 218px;
            margin-left: auto;
            margin-right: auto;
        }
    }
</style>
