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

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

let noAuth=ref(null)//无权限数据

// 获取板块列表
let options=ref([])
const getOptionsList=async ()=>{
    const res=await apiVoiceSectionList()
    if(res.code===200){
        const arr=res.data||[]
        arr.forEach(item => {
            const child=item.Children||[]
            child.forEach(_item=>{
                options.value.push({id:_item.SectionId,val:_item.SectionName})
            })
        });
        // 增加一个全部，一进来默认为全部
        options.value.unshift({id:0,val:'全部'})
        if(route.query.voiceId){
            listState.voiceId=route.query.voiceId
        }else{
            listState.section_id=options.value[0].id
        }
        getVoiceList()
    }
}
getOptionsList()

//点击板块
const handleChangeSection=(item)=>{
    if(item.id===listState.section_id){
        listState.section_id=0
    }else{
        listState.section_id=item.id
    }
    listState.page=1
    listState.list=[]
    listState.voiceId=0
    listState.finished=false
    getVoiceList()
}

//获取音频列表数据
let listState = reactive({
    loading:false,
    finished:false,
    page:1,
    pageSize:20,
    list:[],
    section_id:0,//选择的板块id
    voiceId:0,//分享进入的音频id
})
const getVoiceList=async ()=>{
    listState.loading=true
    const res=await apiVoiceList({
        page_index:Number(listState.page),
        page_size:listState.pageSize,
        broadcast_id:Number(listState.voiceId),
        section_id:Number(listState.section_id)
    })
    listState.loading=false
    if(listState.page===1){
        document.body.scrollTop=document.documentElement.scrollTop=0
    }
    if(res.code===200){
        let arr=res.data.List||[]
        listState.list=[...listState.list,...arr]
        if(arr.length===0||arr.length<listState.pageSize){
            listState.finished=true
        }
        noAuth.value=null
    }else if(res.code===403){
        noAuth.value=res.data
        handleAutoApply()
    }
}

// 加载下一页
const onLoad=()=>{
    listState.page++
    getVoiceList()
}

//无权限时申请
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 formarVoiceTime=(e)=>{
    let m=parseInt(e/60)
    let s=parseInt(e%60)
    return `${m>9?m:'0'+m}:${s>9?s:'0'+s}`
}

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

//删除音频
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('操作成功')
                listState.page=1
                listState.finished=false
                listState.list=[]
                getVoiceList()
            }
        })
    }).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('操作成功')
                item.CouldSendMsg=false
            }
        })
    }).catch(()=>{
            
    })
}

//播放音频
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('上报音频播放记录');
    }
}

//跳转详情
const goDetail=(item)=>{
    router.push({
        path:'/voice/detail',
        query:{
            voiceId:item.BroadcastId,     
        }
    })
}


onMounted(() => {
  //向小程序发送消息
  let postData = {
    path: "/pages/voice/voice",
    params:{},
    title: "语音播报",
    shareImg:''
  };
  wx.miniProgram.postMessage({ data: postData });
});
onActivated(()=>{
    //向小程序发送消息
    let postData = {
        path: "/pages/voice/voice",
        params:{},
        title: "语音播报",
        shareImg:''
    };
    wx.miniProgram.postMessage({ data: postData });
    if(noAuth.value){
        //无权限时每次进页面都刷新列表
        getVoiceList()
    }
})

</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-list-page" v-else>
        <div class="top-nav-list-box">
            <span 
                v-for="item in options" :key="item.id" 
                :class="['multi-ellipsis item',item.id==listState.section_id&&'active']"
                @click="handleChangeSection(item)"
            >{{item.val}}</span>
        </div>
        <SelfList 
            :finished="listState.finished" 
            :isEmpty="listState.list.length===0&&listState.finished"
            :loading="listState.loading"
            :count="listState.list.length"
            @listOnload="onLoad"
        >
            <div class="list-wrap">
                <div class="item" v-for="item in listState.list" :key="item.BroadcastId">
                    <h2 class="title" @click="goDetail(item)">{{item.BroadcastName}}</h2>
                    <div class="time">发布时间：{{moment(item.PublishTime).format('YYYY-MM-DD HH:mm:ss')}}</div>
                    <div class="flex audio-box" @click.stop="handlePlay(item)">
                        <div :class="['audio-icon',($store.state.audioData.voiceId==item.BroadcastId)&&!$store.state.audioData.paused?'active':'']"></div>
                        <div class="audio-pic">
                            <img src="@/assets/audio-waveform1.png">
                            <img src="@/assets/audio-waveform2.png">
                        </div>
                        <div class="audio-time">{{formarVoiceTime(item.VoicePlaySeconds)}}</div>
                    </div>
                    <div class="flex opts-box">
                        <img 
                            class="opt publish-btn" 
                            v-if="item.CouldSendMsg"
                            src="@/assets/voice/publish.png" 
                            alt=""
                            @click.stop="handleSendMsg(item)"
                        />
                        <img 
                            class="opt del-btn" 
                            v-if="item.IsAuthor" 
                            src="@/assets/voice/del.png" 
                            alt=""
                            @click.stop="handleDel(item)"
                        />
                        <SharePoster
                            :isSlot="true"
                            :shareData="{
                                type:'voice_detail',
                                code_page:'pages-voice/voiceDetail',
                                code_scene:JSON.stringify({voiceId:item.BroadcastId}),
                                data:{
                                    title:item.BroadcastName,
                                    img:item.ImgUrl
                                }
                            }"
                        >
                            <img class="opt poster-btn" src="@/assets/voice/creat-poster-icon.png" alt="">
                        </SharePoster>
                        <el-popover
                            :width="200"
                            trigger="hover"
                            @show="handelGetQRCodeImg(item)"
                        >
                            <template #reference>
                                <div class="opt icon-wechat"></div>
                            </template>
                            <template #default>
                                <img style="width:100%" :src="item.QRCodeImg" alt="">
                            </template>
                        </el-popover>
                    </div>
                    
                </div>
            </div>
        </SelfList>

        <!-- 跳转去提问 -->
        <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;
    &:hover{
        background-image: url('@/assets/icon-wechat2.png');
    }
}
.voice-list-page{
    .list-wrap{
        .item{
            padding: 20px;
            // border-left: 1px solid #F2F2F2;
            border-top: 1px solid #F2F2F2;
            // border-right: 1px solid #F2F2F2;
            position: relative;
            &:last-child{
                border-bottom: 1px solid #F2F2F2;
            }
            .title{
                font-size: 16px;
                margin: 0 0 10px 0;
                cursor: pointer;
            }
            .time{
                color: #666;
                font-size: 14px;
            }
            .audio-box{
                // width: 193px;
                // height: 38px;
                // background: #F4E1C9;
                // border-radius: 28px;
                // color: #E3B377;
                // font-size: 14px;
                // align-items: center;
                // margin-top: 20px;
                // 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');
                // }
                width: 443px;
                height: 46px;
                background-color: #F3A52F;
                border: 1px solid #F3A52F;
                border-radius: 23px;
                display: flex;
                margin-top: 20px;
                align-items: center;
                padding: 0 54px 0 27px;
                cursor: pointer;
                .audio-icon{
                    // cursor: pointer;
                    width: 16px;
                    height: 19.5px;
                    background-size: cover;
                    background-image: url('@/assets/recordplay.png');
                    &.active{
                        background-image: url('@/assets/recordpause.png');
                    }
                }
                .audio-pic{
                margin: 0 27px 0 27px;
                }
                .audio-time{
                font-size: 16px;
                font-weight: 400;
                color: #FFFFFF;
                }
            }
            .opts-box{
                position: absolute;
                bottom: 30px;
                right: 20px;
                .opt{
                    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;
                }
            }
            
        }
    }

    .top-nav-list-box{
        position: sticky;
        top: 60px;
        padding: 30px 0 12px;
        width: 100%;
        z-index: 10;
        margin-top: -20px;
        background-color: #fff;
        // border: 1px solid #F2F2F2;
        .item{
            min-width: 140px;
            display: inline-block;
            max-width: 100%;
            height: 40px;
            background: #F6F6F6;
            // border-radius: 4px;
            line-height: 40px;
            padding: 0 16px;
            font-size: 16px;
            margin-right: 30px;
            margin-bottom: 10px;
            cursor: pointer;
            text-align: center;
            border-radius: 20px;
            box-sizing: border-box;
            border: 1px solid transparent;
        }
        .active{
            color: #F3A52F;
            background: #FFFBF5;
            border: 1px solid #F3A52F;
        }
        @media screen and (max-width: 1100px){
            .item{
                min-width: 90px;
                height: 30px;
                line-height: 28px;
                margin-right: 15px;
                font-size: 14px;
                padding: 0 12px;
            }
        }
    }

}
.voice-no-auth{
    text-align: center;
    img{
        width: 400px;
    }
    .btn{
        width: 218px;
        margin-left: auto;
        margin-right: auto;
    }
}
</style>
