<template>
    <view class="activity-detail" v-if="info">
        <view
            class="top-wrap"
            :style="'background-image:url(' + info.speakerBackgroundPic + ')'"
        >
            <view class="status status-before" v-if="info.activityState === 1"
                >未开始</view
            >
            <view class="status status-before" v-if="info.activityState === 2"
                >进行中</view
            >
            <view class="status status-before" v-if="info.activityState === 3"
                >已结束</view
            >
            <view class="title">{{ info.activityTypeName }}</view>
            <view class="name">主讲人：{{ info.speaker }}</view>
            <view class="time"
                >活动时间：{{
                    info.startTime | formatActivityTime(info.endTime)
                }}</view
            >
            <view class="flex city" v-if="info.city">
                <image src="./static/position.png" model="aspectFill"></image>
                <text>{{ info.city }}</text>
            </view>
        </view>
        <view class="intro-wrap">{{ info.reportName?info.reportName.split('】')[1]:info.activityName }}</view>
        

        <!-- 音频 -->
        <view class="audio-wrap" v-if="info.activityState === 3">
            <view
                class="audio-item"
                v-for="(item,index) in audioList"
                :key="item.voiceUrl"
                @click="handleClickAudioItem(item)"
            >
                <image
                    class="icon" 
                    src="../static/audio-doing-2.png"
                    mode="aspectFill"
                    v-if="item.voiceUrl==activeAudioUrl&&audioPlayStatus"
                />
                <image
                    class="icon" 
                    src="../static/audio-pause-3.png"
                    mode="aspectFill"
                    v-else
                />
                <view class="name" :style="{color:item.voiceUrl==activeAudioUrl?'#D5AD79':''}">{{ item.voiceName }}</view>
                <view class="time">{{ item.voicePlaySeconds|formatVoiceTime }}</view>
            </view>

            <view class="box" v-if="activeAudioUrl">
                <view class="flex top-slider">
                    <text>{{audioCurrentTime|formatVoiceTime}}</text>
                    <slider 
                        class="audio-slider" 
                        activeColor="#e3b377"
                        :max="activeAudioTime" 
                        :value="audioCurrentTime" 
                        @change="handleAudioSliderChange($event)"
                        block-size="20"
                    />
                    <text>{{activeAudioTime|formatVoiceTime}}</text>
                </view>
                <view class="flex btns">
                    <image 
                        class="before" 
                        :src="isFirstAudio?'../static/audio-before-grey.png':'../static/audio-before.png'" 
                        mode="aspectFit"
                        @click="handleAudioBtn('before')"
                    />
                    <image 
                        class="center" 
                        :src="audioPlayStatus?'../static/audio-doing.png':'../static/audio-pause-3.png'" 
                        mode="aspectFit"
                        @click="handleAudioBtn('center')"
                    />
                    <image 
                        class="next" 
                        :src="isLastAudio?'../static/audio-before-grey.png':'../static/audio-before.png'" 
                        mode="aspectFit"
                        @click="handleAudioBtn('next')"
                    />
                </view>
            </view>
        </view>

        <view class="info-wrap">
            <view
                class="flex item"
                v-for="item in infoList"
                :key="item.label"
                @click="handleClickInfoItem(item)"
            >
                <view class="label">{{ item.label }}：</view>
                <view :class="['content', item.color && 'yellow-color',item.type=='copy'&&'link']">
                  {{item.text}}
                </view>
                <view class="copy-btn" v-if="item.type == 'copy'" @click="handleCopyLink(item.text)">复制链接</view>
            </view>
        </view>

        <!-- 报告链接 -->
        <!-- <view class="info-wrap" v-if="info.reportLink">
            <view class="flex item" @click="handleOpenReport">
                <view class="label">相关报告：</view>
                <view class="yellow-color">查看报告链接</view>
            </view>
        </view> -->

        <view class="btn-wrap">
            <view 
                class="global-btn-yellow-change btn" 
                @click="handleOpenReport"
                v-if="info.reportLink"
            >查看相关报告</view>
            <block v-if="info.activityState === 1">
            <view
                :class="[info.registerState == 1?'global-btn-disable':'global-btn-yellow-change' ,'btn']"
                v-if="info.firstActivityTypeId === 3"
                @click="handleSetRegister"
                >{{
                    info.registerState == 0
                        ? "报名线下参会"
                        : "取消报名线下参会"
                }}({{ info.registeredNum>info.limitPeopleNum?info.limitPeopleNum:info.registeredNum }}/{{ info.limitPeopleNum }})</view
            >
            <view
                :class="[
                    info.hasRemind == 1
                        ? 'global-btn-disable'
                        : 'global-btn-yellow-change',
                    'btn',
                ]"
                @click="handleSetRemind"
                >{{ info.hasRemind == 1 ? "取消会议提醒" : "会议提醒" }}</view
            >
            <p class="tips">(会前15分钟推送微信消息提醒)</p>
            </block>
        </view>

        <!-- 弹窗 -->
        <van-popup :show="pupData.show" @close="pupData.show = false" :close-on-click-overlay="false">
            <view class="global-pup">
                <view class="content">
                    <rich-text :nodes="pupData.content"></rich-text>
                </view>
                <view class="flex bot" v-if="pupData.type == 'contact'">
                    <view @click="pupData.show = false" style="color: #a9afb8">取消</view>
                    <view @click="handleCallPhone(pupData.mobile)">拨号</view>
                </view>
                <view class="flex bot" v-else-if="pupData.type == 'apply'">
                    <view @click="pupData.show = false" style="color: #a9afb8">取消</view>
                    <view @click="handleApply">立即申请</view>
                </view>
                <view class="flex bot" v-else>
                    <view @click="pupData.show = false">知道了</view>
                </view>
            </view>
        </van-popup>

        <!-- 分享海报 -->
        <sharePoster 
            :style="{bottom:'250rpx'}" 
            :shareData="{
                type:'activity_detail',
                code_page:'pages-activity/detail',
                code_scene:code_scene,
                data:shareParams
            }"
        ></sharePoster>
    </view>
</template>

<script>
// 活动详情
import {
    apiActivityDetail,
    apiActivityAudios,
    apiActivityAddRemind,
    apiActivityCancelRemind,
    apiActivityRegister,
    apiActivityCancelRegister
} from "@/api/activity";
import {apiGetSceneToParams} from '@/api/common'
import {baseApiUrl} from '@/utils/config.js'
import sharePoster from '../components/sharePoster/sharePoster.vue'
const moment=require('@/utils/moment-with-locales.min')
moment.locale('zh-cn');
export default {
    name: "ActivityDetail",
    components: {
        sharePoster
    },
    computed: {
      isFirstAudio(){
          if(this.audioList.length>0){
              return this.activeAudioUrl==this.audioList[0].voiceUrl
          }
      }, 
      isLastAudio(){
          if(this.audioList.length>0){
              return this.activeAudioUrl==this.audioList[this.audioList.length-1].voiceUrl
          }
      },
      shareParams(){ //生成海报数据
        if(this.info){
            let obj={
                activity_title:this.info.activityTypeName+'电话会',
                activity_speaker:this.info.speaker,
                activity_time:this.formatActivityTime(this.info.startTime,this.info.endTime),
                activity_avatar:this.info.speakerHeadPic
            }   
            return obj
        }
        
      },
      code_scene(){//生成海报的小程序页面参数
        return  JSON.stringify({id:this.id})
      }
    },
    data() {
        return {
            id: 0, //活动id
            infoList: [],
            info: null,
            audioList: [], //音频数据

            activeAudioUrl:'',//正在播放的背景音频地址
            activeAudioTime:0,//选择的音频数据时长
            audioCurrentTime:0,//音频正常播放的时间
            audioPlayStatus:false,//音频是否正在播放

            pupData: {
                show: false,
                content: "", //弹窗html字符串
                type: "",
                mobile: "",
            },

        };
    },
    onLoad(options) {
        if(options.scene){
            this.init(options.scene)
        }else{
            this.id = options.id;
            this.getDetail();
            this.getAudios()
        }
        
    },
    onUnload(){
        // 存一次
        const tag=this.audioList.some(item=>item.voiceUrl==this.globalBgMusic.src)
        if(tag){
            let obj={
                activityId:this.id,//活动id
                play:this.audioPlayStatus,//是否正在播放
                list:this.audioList,//音频列表数据
                show:false,//是否显示弹窗
                title:this.info.activityTypeName,//音频弹窗标题
                audioCurrentTime:this.audioCurrentTime,//音频播放实时时间
                audioTime:this.activeAudioTime,//当前音频时间
                audioCurrentUrl:this.activeAudioUrl,//当前音频地址
            }
            uni.setStorageSync('audioMsg', JSON.stringify(obj))
        }
    },
    onShareAppMessage() {
        let title=''
        if(this.info.firstActivityTypeId==1){
            title=this.info.reportName.split('】')[1]||this.info.activityName
        }else{
            title=this.info.activityName
        }
        const token=uni.getStorageSync('token')
        const timestamp=new Date().getTime()
        
        let imgUrl=baseApiUrl+`/activity/getActivityShareImg?activity_id=${this.id}&timestamp=${timestamp}`

        return {
            title: title,
            imageUrl:imgUrl
        }
    },
    methods: {
        async init(e){
            const res=await apiGetSceneToParams({scene_key:e})
            if(res.code==200){
                const obj=JSON.parse(res.data)
                this.id=obj.id 
                this.getDetail()
                this.getAudios()
            }
        },
        formatActivityTime(start,end){
            const week=moment(start).format('dddd');
            const day=moment(start).format('YYYY-MM-DD');
            const startTime=moment(start).format('HH:mm');
            const endTime=moment(end).format('HH:mm');
            return `${day} ${startTime}-${endTime} ${week}`
        },
        // 点击音频项
        handleClickAudioItem(item){
            // 点击同一个音频
            if(item.voiceUrl==this.activeAudioUrl){
                // if(this.audioPlayStatus){
                //     this.globalBgMusic.pause()
                // }else{
                //     this.globalBgMusic.play()
                // }
            }else{
                this.handlePlayAudio(item)
            }
        },

        // 播放音频
        handlePlayAudio(e){
            console.log(e);
            
            this.globalBgMusic.title=e.voiceName
            this.globalBgMusic.src=e.voiceUrl

            this.globalBgMusic.onCanplay(()=>{
                console.log('onCanplay');
                this.globalBgMusic.play()
                this.activeAudioUrl=e.voiceUrl
                this.activeAudioTime=e.voicePlaySeconds
            })
          
            this.handleAudioFun()
        },

        // 音频事件
        handleAudioFun(){
            this.globalBgMusic.onPlay(()=>{
                console.log('onplay');
                this.audioPlayStatus=true
            })
            this.globalBgMusic.onPause(()=>{
                console.log('onPause');
                this.audioPlayStatus=false
            })
            this.globalBgMusic.onStop(()=>{
                console.log('onStop');
               this.audioPlayStatus=false
               this.activeAudioUrl=''
               this.activeAudioTime=0
               this.audioCurrentTime=0
            })
            this.globalBgMusic.onEnded(()=>{
                console.log('onEnded');
                this.audioPlayStatus=false
                this.handleAudioBtn('next','auto')
            })
            this.globalBgMusic.onError((e)=>{
                console.log('onError',e);
                uni.showToast({
                    title:"音频播放错误",
                    icon:'none'
                })
            })
            this.globalBgMusic.onTimeUpdate(()=>{
                if(this.globalBgMusic.src==this.activeAudioUrl){
                    this.audioCurrentTime=parseInt(this.globalBgMusic.currentTime)
                }
            })
        },

        // 点击播放按钮
        handleAudioBtn(type,e){
            if(type==='center'){
                if(this.globalBgMusic.src){
                    if(this.audioPlayStatus){
                        this.globalBgMusic.pause()
                    }else{
                        this.globalBgMusic.play()
                    }
                }else{
                    this.handlePlayAudio(this.audioList[0])
                }
                
            }

            if(type==='before'){
                if(!this.isFirstAudio){
                    this.audioList.forEach((_item,index)=>{
                        if(_item.voiceUrl==this.activeAudioUrl){
                            this.handlePlayAudio(this.audioList[index-1])
                        }
                    })
                }
            }

            if(type==='next'){
                if(!this.isLastAudio){
                    this.audioList.forEach((_item,index)=>{
                        if(_item.voiceUrl==this.activeAudioUrl){
                            this.handlePlayAudio(this.audioList[index+1])
                        }
                    })
                }else{
                    // 自动播放最后一个结束
                    if(e==='auto'){
                        this.activeAudioUrl=''
                        this.audioPlayStatus=false
                        this.activeAudioTime=0
                        this.audioCurrentTime=0
                    }
                }
            }


        },

        //音频进度条拖动
        handleAudioSliderChange(e){
            const value=e.detail.value
            this.globalBgMusic.seek(value)
        },

        // 获取活动音频
        async getAudios() {
            const res = await apiActivityAudios({ activity_id: Number(this.id) });
            if (res.code === 200&&res.data) {
                this.audioList = res.data

                let obj=uni.getStorageSync('audioMsg')
                if(obj){
                    if(this.globalBgMusic.src&&JSON.parse(obj).activityId==this.id){
                        this.activeAudioUrl=JSON.parse(obj).audioCurrentUrl
                        this.activeAudioTime=Number(JSON.parse(obj).audioTime)
                        this.audioCurrentTime=parseInt(this.globalBgMusic.currentTime)
                        this.audioPlayStatus=JSON.parse(obj).play
                        this.handleAudioFun()
                    }
                }
            }
        },

        async getDetail() {
            const res = await apiActivityDetail({ activity_id: Number(this.id) });
            // 无权限
            if (res.code === 403) {
                // 如果是pc进入的 则不跳转 
                //防止无权限用户在pc点击分享的或者识别的二维码，没法正常跳转到pc页
                uni.getSystemInfo({
                    success:(e)=>{
                        if (e.windowWidth < 700){
                            uni.redirectTo({
                                url: "/pages-activity/noAuthority?data=" + JSON.stringify(res.data),
                            });
                        }
                    }
                })
                return;
            }
            if (res.code === 200) {
                this.info = 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,
                    },
                ];
                this.infoList = arr.filter((item) => {
                    return item.text;
                });
                // 研究员线下沙龙
                if (res.data.firstActivityTypeId === 3) {
                    // this.infoList.push({label: "活动地址",text: res.data.city + res.data.address})
                    if(res.data.linkParticipants){
                      this.infoList.push({label: "网络参会",text: res.data.linkParticipants,color: "yellow",type: "copy"})
                    }
                }
            }
        },

        // 点击信息项
        handleClickInfoItem(e) {
            if (e.type === "tel" && e.text) {
                uni.makePhoneCall({
                    phoneNumber: e.text,
                });
            }
        },

        // 跳转webview 打开报告
        handleOpenReport() {
            uni.navigateTo({
                url: "/pages-activity/reportDetail",
                success:(res)=>{
                    res.eventChannel.emit('webUrl', { url:  this.info.reportLink})
                }
            });
        },

        // 复制链接
        handleCopyLink(text){
          uni.setClipboardData({
              data: text,
              success: function () {
                  uni.showToast({
                    title:"复制成功,可在浏览器内打开",
                    icon:"none"
                  })
              },
              fail:function(){
                  uni.showToast({
                    title:"复制失败",
                    icon:"none"
                  })
              }
          });
        },

        // 设置会议提醒
        async handleSetRemind() {
            if (this.info.hasRemind == 1) {
                this.handleCancelRemind();
            } else {
                this.handleAddRemind();
            }
        },
        // 添加提醒
        async handleAddRemind() {
            const res = await apiActivityAddRemind({ activity_id: Number(this.info.activityId) });
            if (res.code === 200) {
                this.pupData.content = `<h4 style="text-align:center;margin-bottom:5px">设置成功</h4>
                                        <p>关注【弘则研究】公众号，接收会前15分钟微信提醒，并及时获取活动信息变更通知</p>`;
                this.pupData.show = true;
                this.handleUpateRemindStatus();
            } else if (res.code === 4001) {
                if (res.data.type == "time") {
                    this.pupData.content = `<p>会议开始前15分钟内无法设置会议提醒</p>`;
                    this.pupData.type = "time";
                }
                this.pupData.show = true;
            }
        },
        //取消提醒
        async handleCancelRemind() {
            const res = await apiActivityCancelRemind({ activity_id: Number(this.info.activityId) });
            if (res.code === 200) {
                uni.showToast({
                    title: "取消提醒成功",
                    icon: "none",
                });
                this.handleUpateRemindStatus();
            }else if(res.code===403){
                uni.showToast({
                    title:res.msg,
                    icon:"none"
                })
            }
        },
        // 更新列表提醒状态
        handleUpateRemindStatus() {
            if (this.info.hasRemind == 1) {
                this.info.hasRemind = 0
            } else {
                this.info.hasRemind = 1
            }
            uni.$emit('activityDetailSetRemind', { id: this.info.activityId })
        },

        // 设置报名
        handleSetRegister() {
            if (this.info.registerState == 1) {
                this.handleCancelRegister();
            } else {
                this.handleAddRegister();
            }
        },
        // 线下报名
        async handleAddRegister() {
            const res = await apiActivityRegister({ activity_id: Number(this.info.activityId) })
            if (res.code === 200) {
                this.pupData.content = `<h4 style="text-align:center;margin-bottom:5px">报名成功</h4>
                                        <p>关注【弘则研究】公众号，接收会前1小时微信提醒，并及时获取活动信息变更通知</p>`
                this.pupData.show = true
                this.handleUpdateRegister()
            } else if (res.code === 4001) {
                if (res.data.type == 'time') {
                    this.pupData.content = `<p>活动开始前15分钟内无法设置会议提醒</p>`
                    this.pupData.type = 'time'
                } else if (res.data.type == 'full') {
                    this.pupData.content = `<p>此活动报名人数已满，请留意下期活动</p>`
                    this.pupData.type = 'full'
                }
                this.pupData.show = true
            }
        },
        //取消线下报名
        async handleCancelRegister() {
            const res = await apiActivityCancelRegister({ activity_id: Number(this.info.activityId) })
            if (res.code === 200) {
                uni.showToast({
                    title: "取消报名成功",
                    icon: "none"
                })
                this.handleUpdateRegister()
            }else if(res.code===403){
                uni.showToast({
                    title:res.msg,
                    icon:"none"
                })
            }
        },
        //更新列表报名状态
        handleUpdateRegister() {
            if (this.info.registerState == 1) {
                this.info.registerState = 0
            } else {
                this.info.registerState = 1
            }
            this.getDetail()
            uni.$emit('activityDetailSetRegister', { id: this.info.activityId })
        }
    },
};
</script>

<style lang="scss">
.activity-detail {
    background: #fff;
}
.top-wrap {
    width: 100%;
    height: 370rpx;
    // background: linear-gradient(
    //     312deg,
    //     rgba(0, 0, 0, 0.8) 0%,
    //     rgba(43, 43, 43, 0.8) 100%
    // );
	background-color: #666666;
    color: $global-text-color-white;
    padding-top: 144rpx;
    padding-left: 40rpx;
    padding-right: 40rpx;
    background-size: cover;
    background-repeat: no-repeat;
    position: relative;
    .status {
        position: absolute;
        top: 0;
        left: 0;
        width: 116rpx;
        line-height: 44rpx;
        border-radius: 0px 0px 16rpx 0px;
        color: $global-text-color-white;
        text-align: center;
        font-size: $global-font-size-sm;
    }
    .status-before {
        background-color: #e3b377;
    }
    .status-progress {
        background-color: #3385ff;
    }
    .status-end {
        background-color: #a2a2a2;
    }
    .title {
        font-size: 19px;
        font-weight: bold;
    }
    .name {
        margin-top: 15rpx;
        margin-bottom: 40rpx;
    }
    .time {
        opacity: 0.8;
        font-size: $global-font-size-sm;
    }
    .city {
        font-size: $global-font-size-sm;
        align-items: center;
        position: absolute;
        right: 40rpx;
        bottom: 59rpx;
        image {
            width: 32rpx;
            height: 32rpx;
        }
    }
}
.intro-wrap {
    background-color: #fff;
    box-shadow: 0px 3px 12px rgba(196, 196, 196, 0.16);
    font-size: $global-font-size-lg;
    font-weight: bold;
    padding: 28rpx 34rpx;
}
.info-wrap {
    padding: 30rpx 34rpx;
    .item {
        margin-bottom: 30rpx;
        .label {
            flex-shrink: 0;
        }
        .copy-btn {
            background-color: #e3b377;
            color: #fff;
            padding: 4rpx 8rpx;
            font-size: 12px;
            margin-left: 4rpx;
        }
        .link{
            width: 300rpx;
            white-space:nowrap;
            overflow:hidden;
            text-overflow:ellipsis;
        }
    }
    .yellow-color {
        color: $global-text-color-main;
    }
}

.audio-wrap {
    padding: 0 34rpx;
    .audio-item {
        padding: 36rpx 0;
        border-bottom: 1px solid #E8DED2;
        position: relative;
        .icon {
            position: absolute;
            top: 50rpx;
            right: 6rpx;
            width: 40rpx;
            height: 40rpx;
        }
        .name {
            margin-bottom: 10rpx;
        }
        .time {
            font-size: $global-font-size-mini;
        }
        .audio-slider{
            margin: 20rpx 0 20rpx 20rpx; 
        }
    }
    .box{
        min-height: 100rpx;
        margin-top: 60rpx;
        margin-bottom: 70rpx;
        padding: 30rpx 20rpx;
        background: #FFFFFF;
        border: 1px solid rgba(240, 234, 226, 0.3);
        box-shadow: 0px 3px 12px rgba(154, 154, 154, 0.16);
        border-radius: 16px;
        .top-slider{
            align-items: center;
            text{
                width: 110rpx;
                font-size: 12px;
                text-align: center;
                flex-shrink: 0;
            }
            .audio-slider{
                flex: 1;
                margin: 0 20rpx;
            }
        }
        .btns{
            justify-content: space-between;
            width: 50%;
            align-items: center;
            margin-left: auto;
            margin-right: auto;
            margin-top: 25rpx;
            image{
                width: 58rpx;
                height: 58rpx;
            }
            .next{
                transform: rotate(180deg);
            }
        }
    }
}

.btn-wrap {
    .btn {
        width: 380rpx;
        line-height: 70rpx;
        margin-left: auto;
        margin-right: auto;
        margin-top: 40rpx;
    }
    .tips {
        font-size: $global-font-size-sm;
        color: $global-text-color-999;
        text-align: center;
    }
}
</style>
