<script setup>
import {ref,onMounted} from 'vue'
import {apiVoiceDetail,apiVoiceDel,apiVoicePlayRecord,apiVoiceSendMsg} from '@/api/voice'
import {apiGetWechatQRCode} from '@/api/common'
import {apiApplyPermission} from '@/api/user'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'
import SharePoster from '@/components/SharePoster.vue'

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

let voiceId=route.query.voiceId

// 获取详情
let noAuth=ref(null)
let info=ref(null)
const getDetail=async ()=>{
    const res=await apiVoiceDetail({broadcast_id:Number(voiceId)})
    if(res.code===200){
        info.value=res.data
        noAuth.value=null
        document.title=res.data.SectionName||'播报详情'
        store.commit('modifyBreadCrumb',res.data.SectionName||'播报详情')
        handelGetQRCodeImg()
        //向小程序发送消息
        let postData = {
            path: "/pages-voice/voiceDetail",
            params:{
                voiceId:info.BroadcastId
            },
            title: `${info.value.SectionName}:${info.value.BroadcastName}`,
            shareImg:info.value.ImgUrl
        };
        wx.miniProgram.postMessage({ data: postData });
        
    }else if(res.code===403){
        noAuth.value=res.data
        handleAutoApply()
        //向小程序发送消息
        let postData = {
            path: "/pages-voice/voiceDetail",
            params:{
                voiceId:voiceId
            },
            title: `播报详情`,
            shareImg:''
        };
        wx.miniProgram.postMessage({ data: postData });
    }
}
getDetail()

//获取音频对应的小程序二维码
const handelGetQRCodeImg=async ()=>{
    const res=await apiGetWechatQRCode({
        CodeScene:JSON.stringify({voiceId:info.value.BroadcastId}),
        CodePage:'pages-voice/voiceDetail'
    })
    if(res.code===200){
        info.value.QRCodeImg=res.data
    }
}

//无权限时申请
const handleAutoApply=()=>{
    if(noAuth.value.type=='contact'&&!noAuth.value.customer_info.has_apply){
        if(noAuth.value.customer_info.status=='冻结'||(noAuth.value.customer_info.status=='试用'&&noAuth.value.customer_info.is_suspend==1)){
            apiApplyPermission({
                company_name:noAuth.value.customer_info.company_name,
                real_name:noAuth.value.customer_info.name,
                source:8,
                from_page:'语音播报'
            }).then(res=>{
                if(res.code===200){
                    console.log('主动申请成功');
                }
            }) 
        }
    }
}
const handleApply=()=>{
    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(noAuth.value.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.value.customer_info.status || noAuth.value.customer_info.status != '流失'|| noAuth.value.customer_info.status != '关闭') {
            console.log('跳转申请页');
            router.push({
                path:'/apply/permission',
                query:{
                    source:8,
                    fromPage:'语音播报'
                }
            })
        }else{
            apiApplyPermission({
                company_name:noAuth.value.customer_info.company_name,
                real_name:noAuth.value.customer_info.name,
                source:8,
                from_page:'语音播报'
            }).then(res=>{
                onsole.log('主动申请成功');
                const htmlStr=`<p>申请已提交</p><p>请等待销售人员与您联系</p>`
                ElMessageBox({
                    title:`语音播报`,
                    message:htmlStr,
                    center: true,
                    dangerouslyUseHTMLString: true,
                    confirmButtonText:'知道了',
                    confirmButtonClass:'self-elmessage-confirm-btn'
                })
            })
        }
    }
}

//删除音频
const handleDel=(item)=>{
    ElMessageBox({
        title:`温馨提醒`,
        message:'确定要删除该语音播报吗？',
        center: true,
        dangerouslyUseHTMLString: true,
        confirmButtonText:'确定',
        confirmButtonClass:'self-elmessage-confirm-btn',
        showCancelButton:true,
        cancelButtonText:'取消',
        cancelButtonClass:'self-elmessage-cancel-btn'
    }).then(()=>{
        if(store.state.audioData.voiceId==item.BroadcastId){
            //删除的正在播放
            store.commit('closeAudio')
        }
        apiVoiceDel({broadcast_id:Number(item.BroadcastId)}).then(res=>{
            if(res.code===200){
                ElMessage.success('操作成功')
                if(window.history.state.back){
                    console.log('返回上一页');
                    router.go(-1)
                }else{
                    console.log('返回列表');
                    router.push({path:'/voice/list'})
                }
            }
        })
    }).catch(()=>{
            
    })
}

//发送模板消息
const handleSendMsg=async (item)=>{
    ElMessageBox({
        title:`温馨提醒`,
        message:'该操作将推送模板消息和客群，确认推送吗？',
        center: true,
        dangerouslyUseHTMLString: true,
        confirmButtonText:'确定',
        confirmButtonClass:'self-elmessage-confirm-btn',
        showCancelButton:true,
        cancelButtonText:'取消',
        cancelButtonClass:'self-elmessage-cancel-btn'
    }).then(()=>{
        apiVoiceSendMsg({broadcast_id:Number(item.BroadcastId)}).then(res=>{
            if(res.code===200){
                ElMessage.success('操作成功')
                info.value.CouldSendMsg=false
            }
        })
    }).catch(()=>{
            
    })
}

//处理音频时长显示
const formarVoiceTime=(e)=>{
    let m=parseInt(e/60)
    let s=parseInt(e%60)
    return `${m>9?m:'0'+m}:${s>9?s:'0'+s}`
}

//播放音频
const handlePlay=(item)=>{
    if(store.state.audioData.voiceId==item.BroadcastId){
        if(store.state.audioData.paused){
            store.state.audioData.INS.play()
        }else{
            store.state.audioData.INS.pause()
        }
        return
    }
    store.commit('addAudio',{
        list:[{name:item.BroadcastName,url:item.VoiceUrl,time:item.VoicePlaySeconds}],
        voiceId:item.BroadcastId,
        index:0
    })
    // handleVoiceRecord(item)
}

//上报音频播放记录
const handleVoiceRecord=async (item)=>{
    const res=await apiVoicePlayRecord({
        broadcast_id:item.BroadcastId
    })
    if(res.code===200){
        console.log('上报音频播放记录');
    }
}

</script>

<template>
    <div class="voice-no-auth" v-if="noAuth">
        <img :src="$store.state.globalImgUrls.activityNoAuth" alt="">
        <p style="font-size:16px;margin-bottom: 0;">您暂无权限查看语音播报</p>
        <template v-if="noAuth.type=='contact'">
            <p style="font-size:16px;margin-top: 5px;margin-bottom: 62px;">若想查看，可以联系对口销售--{{noAuth.name}}：<span style="color:#F3A52F">{{noAuth.mobile}}</span></p>
        </template>
        <template 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>
        </template>
    </div>
    <div class="voice-detail-page" v-if="!noAuth&&info">
        <h2 class="title">{{info.BroadcastName}}</h2>
        <p class="publish-time">发布时间：{{moment(info.PublishTime).format('YYYY-MM-DD HH:mm:ss')}}</p>
        <div class="flex bot-box">
            <div class="flex audio-box" @click.stop="handlePlay(info)">
                <div :class="['icon',($store.state.audioData.voiceId==info.BroadcastId)&&!$store.state.audioData.paused?'active':'']"></div>
                <div>{{formarVoiceTime(info.VoicePlaySeconds)}}</div>
            </div>
            <div class="flex btns-box">
                <img 
                    class="btn publish-btn" 
                    v-if="info.CouldSendMsg"
                    src="@/assets/voice/publish.png" 
                    alt=""
                    @click.stop="handleSendMsg(info)"
                />
                <img 
                    class="btn del-btn" 
                    v-if="info.IsAuthor" 
                    src="@/assets/voice/del.png" 
                    alt=""
                    @click.stop="handleDel(info)"
                />
                <SharePoster
                    :isSlot="true"
                    :shareData="{
                        type:'voice_detail',
                        code_page:'pages-voice/voiceDetail',
                        code_scene:JSON.stringify({voiceId:info.BroadcastId}),
                        data:{
                            title:info.BroadcastName,
                            img:info.ImgUrl
                        }
                    }"
                >
                    <img class="btn poster-btn" src="@/assets/voice/creat-poster-icon.png" alt="">
                </SharePoster>
                <el-popover
                    :width="200"
                    trigger="hover"
                >
                    <template #reference>
                        <div class="btn icon-wechat"></div>
                    </template>
                    <template #default>
                        <img style="width:100%" :src="info.QRCodeImg" alt="">
                    </template>
                </el-popover>
            </div>
        </div>
        <div class="img-box">
            <el-image
                style="width: 100%; height: auto"
                :src="item"
                :preview-src-list="info.Imgs"
                :initial-index="index"
                fit="contain"
                v-for="item,index in info.Imgs" 
                :key="item"
            />
        </div>

        <!-- 跳转去提问 -->
        <div class="to-question-box-fixed" @click="$router.push({path:'/question/list',query:{isAutoQuestion:true}})">
            <img src="@/assets/toquestion-icon.png" alt="">
            <span>我要提问</span>
        </div>

    </div>
</template>

<style lang="scss" scoped>
.icon-wechat{
    cursor: pointer;
    width: 24px;
    height: 24px;
    background-image: url('@/assets/icon-wechat.png');
    background-size: cover;
    margin-left: 30px;
    &:hover{
        background-image: url('@/assets/icon-wechat2.png');
    }
}
.voice-no-auth{
    text-align: center;
    img{
        width: 400px;
    }
    .btn{
        width: 218px;
        margin-left: auto;
        margin-right: auto;
    }
}
.voice-detail-page{
    border-left: 1px solid #F2F2F2;
    border-right: 1px solid #F2F2F2;
    padding: 30px;
    .title{
        font-size: 16px;
        margin: 0 0 10px 0;
    }
    .publish-time{
        margin: 0;
        font-size: 14px;
        color: #666;
    }
    .audio-box{
        width: 193px;
        height: 38px;
        background: #F4E1C9;
        border-radius: 28px;
        color: #E3B377;
        font-size: 14px;
        align-items: center;
        padding-left: 20px;
        cursor: pointer;
        .icon{
            width: 16px;
            height: 19px;
            background-image: url('@/assets/voice/pause.png');
            background-size: cover;
            margin-right: 10px;
        }
        .active{
            background-image: url('@/assets/voice/playing.png');
        }
    }
    .bot-box{
        justify-content: space-between;
        align-items: baseline;
        margin-top: 20px;
        .btn{
            margin-left: 30px;
        }
        .del-btn{
            width: 23px;
            height: 23px;
            cursor: pointer;
        }
        .publish-btn{
            width: 23px;
            height: 23px;
            cursor: pointer;
        }
        .poster-btn{
            width: 23px;
            height: 23px;
            cursor: pointer;
        }
    }
    .img-box{
        margin-top: 30px;
        img{
            width: 100%;
            object-fit: contain;
            margin-bottom: 30px;
        }
    }
}
</style>