<template>
    <view class="voice-play-page" v-if="isAuth">
        <!-- 由于目前板块较少 先去掉底部弹出筛选 改为平铺展示在tab上 -->
        <!-- <view class="top-filter-box">
            <image src="@/static/question/select.png" mode="aspectFill" @click="showFilter = true" />
            <text @click="showFilter = true">筛选</text>
        </view> -->
        <view class="top-filter-box">
            <van-tabs 
                id="tabs"
                :ellipsis="false" 
                :active="activeId" 
                color="#E3B377"
                line-width="18px"
                @change="onTabsChange"
            >
                <van-tab 
                    :title="item.SectionName" 
                    :name="item.SectionId" 
                    v-for="item in tabsList" 
                    :key="item.SectionId"
                ></van-tab>
            </van-tabs>
        </view>
          
        <view class="empty-box" v-if="list.length==0&&finished">
            <image
                :src="globalImgUrls.activityNoAuth"
                mode="widthFix"
            />
            <view>暂无数据</view>
        </view>
        <view class="list-wrap" :class="showAudioPop?showAudioBigPop?'list-bot3':'list-bot2':'list-bot1'" v-else>
            <view class="item" v-for="item in list" :key="item.BroadcastId" @click="handleGoDetail(item)">
                <view class="title">{{item.BroadcastName}}</view>
                <view class="time">发布时间：{{item.PublishTime|formatTime}}</view>
                <view class="flex audio-box" @click.stop="handlePlay(item)">
                    <image 
                        :src="item.BroadcastId==curVoiceId&&!curAudioPaused?require('@/static/voice/playing.png'):require('@/static/voice/pause.png')" 
                        mode="widthFix" 
                    />
                    <text>{{item.VoicePlaySeconds|formatVoiceTime}}</text>
                </view>
                <view class="opt-box">
                    <image style="width:34rpx;height:34rpx" src="@/static/voice/publish.png" mode="widthFix" @click.stop="handleSendMsgItem(item)" v-if="item.CouldSendMsg"/>
                    <image style="width:34rpx;height:34rpx" src="@/static/voice/del.png" mode="widthFix" v-if="item.IsAuthor" @click.stop="handleDelItem(item)" />
                    <sharePoster 
                        :showSlot="true"
                        :shareData="getItemShareData(item)"
                    >
                        <image style="width:32rpx;height:32rpx" src="@/static/voice/creat-poster-icon.png" mode="aspectFill" />
                    </sharePoster>
                    <button 
                        class="share-btn" 
                        open-type="share" 
                        :data-item="item"
                        @click.stop=""
                    >
                        <image class="share-img" src="@/static/share-icon.png" mode="aspectFill"/>
                    </button>
                </view>
            </view>
        </view>

        <navigator url="/pages-voice/addVoice" v-if="IsVoiceAdmin">
            <view :class="['add-btn',showAudioPop?showAudioBigPop?'add-btn-bot3':'add-btn-bot2':'add-btn-bot1']">新建语音</view>
        </navigator>

        <!-- 筛选弹窗 -->
        <van-popup 
            :show="showFilter" 
            position="bottom"  
            :close-on-click-overlay="true"
            @close="showFilter = false"
            round
        >
            <view class="fliter-wrap-list">
                <view class="flex top">
                    <text style="color:#000">全部筛选</text>
                    <text style="color:#E3B377" @click="showFilter=false">取消</text>
                </view>
                <van-tree-select
                    :items="options"
                    :main-active-index="mainActiveIndex"
                    :active-id="activeId"
                    @click-nav="onClickNav"
                    @click-item="onClickItem"
                    main-active-class="main-active-class"
                    content-active-class="content-active-class"
                />
            </view>
        </van-popup>

        <!-- 音频悬浮 -->
        <view v-if="showPage">
            <audioBox v-if="showAudioPop"/>
        </view>
        
        <!-- 跳转去提问悬浮按钮 -->
        <dragButton :existTabBar="true">
            <navigator url="/pages-question/hasQuestion">
                <view class="to-question-fixed-box">
                    <image src="@/static/toquestion-icon.png" mode="widthFix" />
                    <text>我要提问</text>
                </view>
            </navigator>
        </dragButton>
        

        <van-dialog id="van-dialog" />
    </view>
    <noAuth :info="noAuthData" v-else/>
</template>

<script>
import {apiVoiceList,apiVoiceSectionList,apiVoicePlayRecord,apiVoiceDel,apiVoiceSendMsg} from '@/api/voice'
import {apiGetSceneToParams} from '@/api/common'
import noAuth from './components/noAuth.vue'
import audioBox from '@/components/audioBox/audioBox.vue'
import dragButton from '@/components/dragButton/dragButton.vue'
import sharePoster from '@/components/sharePoster/sharePoster.vue'
const dayjs=require('@/utils/dayjs.min')
export default {
    components:{
        noAuth,
        audioBox,
        dragButton,
        sharePoster
    },
    filters:{
        formatTime(e){
            return dayjs(e).format('YYYY-MM-DD HH:mm:ss')
        },
        formatVoiceTime(e){
            let m=parseInt(e/60)
            let s=parseInt(e%60)
            return `${m>9?m:'0'+m}:${s>9?s:'0'+s}`
        }
    },
    computed:{
        showAudioPop(){//是否显示音频弹窗
            return this.$store.state.audio.show
        },
        showAudioBigPop(){
            return this.$store.state.audio.showBig
        },
        curVoiceId(){//当前正在播放的音频id
            return this.$store.state.audio.voiceId
        },
        curAudioPaused(){//当前音频是否暂停状态
            return this.$store.state.audio.paused
        },
    },
    data() {
        return {
            list:[],
            page:1,
            pageSize:20,
            finished:false,
            voiceId:0,//分享时进入的音频id

            IsVoiceAdmin:false,//是否是语音管理员

            isAuth:true,
            noAuthData:null,

            showFilter:false,
            options:[],
            mainActiveIndex:0,
            activeId:0,//选择的板块id
            tabsList:[],//顶部滑动筛选数据

            showPage:false,
        }
    },
    onLoad(options){
        this.init(options)
        this.addListenVoiceSuccess()
    },
    onShow(){
        //无权限时刷新列表
        if(!this.isAuth){
            this.getOptionsList()
        }else{
            this.$nextTick(()=>{
                this.selectComponent('#tabs').resize();// 解决初始渲染 vant tab 底部条
            })
        }
        
        this.showPage=true
    },
    onHide(){
        this.showPage=false
    },
    onUnload(){
		uni.$off('addVoiceSuccess')
	},
    onShareAppMessage({from,target}) {
        console.log(from,target);
        let path='/pages/voice/voice'
        let title='语音播报'
        let imageUrl=''
        if(from=='button'){
            title=`${target.dataset.item.SectionName}:${target.dataset.item.BroadcastName}`
            path=`/pages-voice/voiceDetail?voiceId=${target.dataset.item.BroadcastId}`
            imageUrl=target.dataset.item.ImgUrl
        }
        return {
            title:title,
            path:path,
            imageUrl:imageUrl
        }
    },
    onPullDownRefresh(){
        this.voiceId=0
        this.page=1
        this.list=[]
        this.finished=false
        this.getOptionsList()
        setTimeout(() => {
            uni.stopPullDownRefresh()
        }, 1500)
    },
    onReachBottom() {
        if(this.finished) return
        this.page++
        this.getVoiceList()
    },

    methods: {
        handleGoDetail(item){
            uni.navigateTo({
                url: '/pages-voice/voiceDetail?voiceId='+item.BroadcastId,
            });
        },

        // 监听添加音频成功刷新列表
        addListenVoiceSuccess(){
            uni.$on('addVoiceSuccess',()=>{
                this.voiceId=0
                this.page=1
                this.list=[]
                this.finished=false
                this.getVoiceList()
                this.getOptionsList()
            })
        },

        async init(options){
            if(options.scene){
                const res=await apiGetSceneToParams({scene_key:options.scene})
                if(res.code===200){
                    const obj=JSON.parse(res.data)
                    this.voiceId=obj.voiceId
                }
            }else{
                this.voiceId=options.voiceId||0
            }
            this.getOptionsList()
        },

        // 获取音频列表
        async getVoiceList(){
            const res=await apiVoiceList({
                page_index:this.page,
                page_size:this.pageSize,
                broadcast_id:Number(this.voiceId),
                section_id:Number(this.activeId)
            })
            if(res.code===200){
                this.IsVoiceAdmin=res.data.IsVoiceAdmin
                let arr=res.data.List||[]
                this.list=[...this.list,...arr]
                if(arr.length===0){
                    this.finished=true
                }

                // 如果有voiceId 则说明是分享进入的 如果没有数据则提示
                if(this.voiceId!=0&&arr.length===0){
                    uni.showToast({
                        title:'该语音播报不存在',
                        icon:'none'
                    })
                    setTimeout(() => {
                        this.voiceId=0
                        this.page=1
                        this.list=[]
                        this.finished=false
                        this.getVoiceList()
                        this.getOptionsList()
                    }, 1500);
                }
                this.isAuth=true
            }else if(res.code===403){
                //无权限用户
                this.isAuth=false
                this.noAuthData=res.data
            }
        },

        //获取筛选数据
        async getOptionsList(){
            const res=await apiVoiceSectionList()
            if(res.code!==200) return
            const arr=res.data||[]
            let temarr=[]
            this.options=arr.map(item=>{
                let obj={
                    text:'',
                    children:[]
                }
                obj.text=item.VarietyName
                obj.children=item.Children.map(_item=>{
                    temarr.push(_item)
                    return {
                        text:_item.SectionName,
                        id:_item.SectionId
                    }
                })
                return obj
            })
            this.tabsList=temarr||[]
            this.activeId=temarr[0].SectionId
            this.$nextTick(()=>{
                this.selectComponent('#tabs')?.resize();// 解决初始渲染 vant tab 底部条
            })
            this.getVoiceList()
        },

        // 顶部tab切换
        onTabsChange(e){
            this.activeId=e.detail.name
            this.voiceId=0
            this.page=1
            this.list=[]
            this.finished=false
            this.getVoiceList()
        },

        onClickNav({detail}){
            console.log(detail);
            this.mainActiveIndex=detail.index
        },

        onClickItem({detail}){
            console.log(detail);
            if(this.activeId==detail.id){
                this.activeId=0
            }else{
                this.activeId=detail.id
            }
            this.voiceId=0
            this.page=1
            this.list=[]
            this.finished=false
            this.getVoiceList()
            this.showFilter=false
        },

        //推送消息
        handleSendMsgItem(item){
            this.$dialog.confirm({
                title:'',
                message: '该操作将推送模板消息和客群，确认推送吗？',
                confirmButtonText:'确认'
            }).then(()=>{
                apiVoiceSendMsg({broadcast_id:item.BroadcastId}).then(res=>{
                    if(res.code===200){
                        uni.showToast({
                            title:"推送成功",
                            icon:'success'
                        })
                        item.CouldSendMsg=false
                    }
                })
            }).catch(()=>{})
        },
        
        //删除音频
        handleDelItem(item){
            this.$dialog.confirm({
                title:'',
                message: '确定要删除该语音播报吗？',
                confirmButtonText:'确定'
            }).then(()=>{
                if(this.curVoiceId==item.BroadcastId&&!this.curAudioPaused){
                    //删除的音频正好在播放则暂停
                    this.globalBgMusic.stop()
                }
                
                apiVoiceDel({broadcast_id:Number(item.BroadcastId)}).then(res=>{
                    if(res.code===200){
                        uni.showToast({
                            title:'操作成功',
                            icon:'none'
                        })
                        this.page=1
                        this.list=[]
                        this.finished=false
                        this.getVoiceList()
                    }
                })
            }).catch(()=>{})
        },

        //点击音频 播放或者暂停
        handlePlay(item){
            if(this.$store.state.audio.voiceId==item.BroadcastId){
                if(this.globalBgMusic.paused){
                    this.globalBgMusic.play()
                }else{
                    this.globalBgMusic.pause()
                }
            }else{
                const list=[{url:item.VoiceUrl,time:item.VoicePlaySeconds,title:item.BroadcastName,}]
                this.$store.commit('audio/addAudio',{
                    list:list,
                    voiceId:item.BroadcastId
                })
                this.handleVoicePlayRecord(item)
            }
        },

        //上报音频播放记录
        async handleVoicePlayRecord(item){
            const res=await apiVoicePlayRecord({
                broadcast_id:item.BroadcastId
            })
            if(res.code===200){
                console.log('上报音频播放记录');
                this.$store.commit('audio/addAudioRecordId',{recordId:res.data,source:2})
            }
        },

        //语音详情生成海报参数
        getItemShareData(item){
            return {
                type:'voice_detail',
                code_page:'pages-voice/voiceDetail',
                code_scene:JSON.stringify({voiceId:item.BroadcastId}),
                data:{
                    title:item.BroadcastName,
                    img:item.ImgUrl
                }
            }
        }
    },
}
</script>

<style lang="scss">
.top-filter-box{
    .van-tab{
        font-size: 28rpx;
        color: #777;
    }
    .van-tab--active{
        font-weight: bold;
        font-size: 32rpx;
        color: #333333;
    }
}
.voice-play-page{
    
    .fliter-wrap-list{
        background-color: #fff;
        padding-top: 53rpx;
        padding-bottom: 100rpx;
        .top{
            font-size: 32rpx;
            justify-content: space-between;
            margin-bottom: 40rpx;
            padding: 0 34rpx;
        }
        .van-sidebar{
            flex-shrink: 0;
        }
        .van-tree-select__content{
            overflow-x: hidden;
        }
        .main-active-class{
            border-color: #E3B377;
        }
        .content-active-class{
            color: #E3B377;
        }
    }
}
</style>

<style lang="scss" scoped>
.voice-play-page{
    .top-filter-box{
        
		background-color: white;
        box-shadow: 0px 4rpx 4rpx 0px rgba(198,198,198,0.2500);
		position: sticky;
		top: 0;
		left: 0;
		z-index: 99;
        // image{
        //     width: 34rpx;
        //     height: 34rpx;
        // }
        // color: #E3B377;
        // font-size: 28rpx;
    }
}
.empty-box{
    text-align: center;
    font-size: 32rpx;
    color: #999;
    padding-top: 150rpx;
    image{
        width: 80vw;
        margin-bottom: 57rpx;
    }
}
.list-wrap{
    padding: 0 34rpx 34rpx 34rpx;
    .item{
        border-bottom: 1px solid #CDCDCD;
        padding: 30rpx 0;
        position: relative;
        .opt-box{
            position: relative;
            float: right;
            bottom: 40rpx;
            display: flex;
            image{
                margin-left: 40rpx;
            }
            .share-btn{
                background-color: transparent;
                width: 36rpx;
                height: 36rpx;
                line-height: 1;
                padding: 0;
                margin-left: 40rpx;
                &::after{
                    border: none;
                }
                .share-img{
                    width: 32.5rpx;
                    height: 32rpx;
                    margin-left: 0;
                }
            }
            
        }


        .title{
            font-size: 32rpx;
        }
        .time{
            font-size: 28rpx;
            color: #666;
            margin-top: 20rpx;
            margin-bottom: 30rpx;
        }
        .audio-box{
            width: 185rpx;
            height: 56rpx;
            align-items: center;
            justify-content: center;
            border-radius: 28rpx;
            background-color: #F4E1C9;
            color: #E3B377;
            image{
                width: 23rpx;
                height: 28rpx;
                margin-right: 20rpx;
            }
        }
    }
}
.list-bot1{
	padding-bottom: 200rpx;
}
.list-bot2{
	padding-bottom: 340rpx;
}
.list-bot3{
	padding-bottom: 440rpx;
}
.add-btn{
    position: fixed;
    width: 514rpx;
    height: 80rpx;
    text-align: center;
    line-height: 80rpx;
    color: #E3B377;
    font-size: 32rpx;
    left: 50%;
    bottom: calc(150rpx + constant(safe-area-inset-bottom));
    bottom: calc(150rpx + env(safe-area-inset-bottom));
    transform: translateX(-50%);
    background: #333333;
    box-shadow: 0px 4rpx 20rpx rgba(160, 126, 84, 0.25);
    border-radius: 40rpx;
}
.add-btn-bot1{
    bottom: calc(120rpx + constant(safe-area-inset-bottom));
    bottom: calc(120rpx + env(safe-area-inset-bottom));
}
.add-btn-bot2{
    bottom: calc(260rpx + constant(safe-area-inset-bottom));
    bottom: calc(260rpx + env(safe-area-inset-bottom));
}
.add-btn-bot3{
    bottom: calc(355rpx + constant(safe-area-inset-bottom));
    bottom: calc(355rpx + env(safe-area-inset-bottom));
}

</style>