<template>
    <view class="my-voice-page">
        <view class="top-tab-warp">
           <text 
            :class="['item',status==opt.value?'item-active':'']" 
            v-for="opt in statusOpt" 
            :key="opt.value"
            @click="handleOptChange(opt)"
        >{{opt.lable}}（{{opt.count}}）</text>
        </view>

        <view class="empty-box" v-if="finished&&list.length==0">
            <image :src="globalImgUrls.activityNoAuth" mode="widthFix" />
            <view>暂无数据</view>
        </view>
        <view class="list-wrap" 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" v-if="item.PublishState==0">保存时间：{{item.ModifyTime|formatTime}}</view>
                <view class="time" v-else>发布时间：{{item.PublishTime|formatTime}}</view>
                <view class="argument" v-if="item.CentralArguments">
                    <view class="btn">核心观点</view>
                    <view class="van-multi-ellipsis--l2 argument_text">{{item.CentralArguments}}</view>
                </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="btns-box">
                    <button 
                        v-if="item.PublishState!=0"
                        class="btn" 
                        open-type="share" 
                        :data-item="item"
                        @click.stop=""
                    >
                        <image class="share-img" src="@/static/share-icon.png" mode="aspectFill"/>
                    </button>
                    <button class="btn" @click.stop="handleDelItem(item)">
                        <image class="del-img" src="@/static/voice/del.png" mode="widthFix" v-if="item.IsAuthor" />
                    </button>
                    <button class="btn" @click.stop="handleSendMsgItem(item)" v-if="item.CouldSendMsg&&item.PublishState!=0">
                        <image class="publish-img" src="@/static/voice/publish.png" mode="widthFix" />
                    </button>
                    <button class="btn" @click.stop="handlePublish(item)" v-if="item.PublishState==0">
                        <image class="publish-img" src="./static/publish.png" mode="widthFix" />
                    </button>
                </view>
            </view>
        </view>


        <!-- 音频悬浮 -->
        <view v-if="showPage">
        <audioBox v-if="showAudioPop"/>
        </view>
        
        <van-dialog id="van-dialog" />
    </view>
</template>

<script>
import {apiVoiceList,apiVoicePlayRecord,apiVoiceDel,apiVoiceSendMsg,apiVoicePublish,apiMyVoiceCount} from '@/api/voice'
import audioBox from '@/components/audioBox/audioBox.vue'
const dayjs=require('@/utils/dayjs.min')
export default {
    components:{
        audioBox
    },
    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 {
            page:1,
            pageSize:20,
            list:[],
            finished:false,
            status:0,//0-未发布 1-已发布 2-全部（我的语音播报列表）
            statusOpt:[
                {
                    lable:'未发布',
                    count:0,
                    value:0,
                    key:'Unpublished'
                },
                {
                    lable:'已发布',
                    count:0,
                    value:1,
                    key:'Published'
                },
                {
                    lable:'全部',
                    count:0,
                    value:2,
                    key:'All'
                }
            ],

            showPage:false,
        }
    },
    onLoad(){
        this.getCount()
        this.getList()
        this.addListenVoiceSuccess()
    },
    onShow(){
        this.showPage=true
    },
    onHide(){
        this.showPage=false
    },
    onUnload(){
		uni.$off('addVoiceSuccess')
	},
    onPullDownRefresh(){
        this.page=1
        this.list=[]
        this.finished=false
        this.getList()
        setTimeout(() => {
            uni.stopPullDownRefresh()
        }, 1500)
    },
    onReachBottom() {
        if(this.finished) return
        this.page++
        this.getList()
    },
    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
        }
    },
    methods: {  
        // 监听添加音频成功刷新列表
        addListenVoiceSuccess(){
            uni.$on('addVoiceSuccess',()=>{
                this.page=1
                this.list=[]
                this.finished=false
                this.getCount()
                this.getList()
            })
        },

        //获取列表数据
        async getList(){
            const res=await apiVoiceList({
                page_index:this.page,
                page_size:this.pageSize,
                author_id:Number(this.$store.state.user.userInfo.user_id),
                mine_status:this.status
            })
            if(res.code===200){
                let arr=res.data.List||[]
                this.list=[...this.list,...arr]
                if(arr.length===0){
                    this.finished=true
                }
            }
        },

        //获取数量
        async getCount(){
            const res=await apiMyVoiceCount({author_id:this.$store.state.user.userInfo.user_id})
            if(res.code===200){
                this.statusOpt.forEach(item => {
                    item.count=res.data[item.key]
                })
            }
        },

        //状态改变
        handleOptChange(item){
            this.status=item.value
            this.page=1
            this.list=[]
            this.finished=false
            this.getList()
        },

        //跳转详情
        handleGoDetail(item){
            if(item.PublishState==0){//未发布跳转编辑
                uni.navigateTo({
                    url: '/pages-voice/addVoice?voiceId='+item.BroadcastId,
                });
            }else{
                uni.navigateTo({
                    url: '/pages-voice/voiceDetail?voiceId='+item.BroadcastId,
                });
            }
            
        },
        
        //推送消息
        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.getList()
                        this.getCount()
                    }
                })
            }).catch(()=>{})
        },

        //未发布时点击立即发布并且推送
        handlePublish(item){
            this.$dialog.confirm({
                title:'',
                message: '该操作将发布并且推送模板消息和客群',
                confirmButtonText:'确认'
            }).then(async ()=>{
                const pubRes=await apiVoicePublish({
                    broadcast_id:Number(item.BroadcastId),
                    publish_type:1
                })
                if(pubRes.code===200){
                    const sendRes=await apiVoiceSendMsg({broadcast_id:item.BroadcastId})
                    if(sendRes.code===200){
                        uni.showToast({
                            title:'发布且推送成功',
                            icon:'success'
                        })
                        setTimeout(() => {
                            this.page=1
                            this.list=[]
                            this.finished=false
                            this.getList()
                            this.getCount()
                        }, 1000);
                    }else{
                        uni.showToast({
                            title:sendRes.msg,
                            icon:'none'
                        })
                    }
                }else{
                    uni.showToast({
                        title:pubRes.msg,
                        icon:'none'
                    })
                }
            }).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})
            }
        }
    },
}
</script>

<style lang="scss" scoped>
.empty-box{
    text-align: center;
    font-size: 32rpx;
    color: #999;
    padding-top: 150rpx;
    image{
        width: 600rpx;
        margin-bottom: 57rpx;
    }
}
.top-tab-warp{
    padding: 34rpx;
    position: sticky;
    top: 0;
    left: 0;
    background: #ffffff;
    z-index: 99;
    .item{
        box-sizing: border-box;
        width: 200rpx;
        text-align: center;
        padding: 20rpx 10rpx;
        background: #F5F5F5;
        border-radius: 4rpx;
        margin-right: 30rpx;
        display: inline-block;
        &:last-child{
            margin-right: 0;
        }
    }
    .item-active{
        background: #FDF8F2;
        color: #E3B377;
    }
}
.list-wrap{
    padding: 0 34rpx 34rpx 34rpx;
    .item{
        border-bottom: 1px solid #CDCDCD;
        padding: 30rpx 0;
        position: relative;

        .btns-box{
            position: absolute;
            bottom: 34rpx;
            right: 0;
            
            .btn{
                float: right;
                margin-left: 60rpx;
                background-color: transparent;
                line-height: 1;
                padding: 0;
                overflow: visible;
                &::after{
                    border: none;
                }
                .publish-img{
                    width: 34rpx;
                    height: 34rpx;
                }
                .del-img{
                    width: 34rpx;
                    height: 34rpx;
                }
                .share-img{
                    width: 32.5rpx;
                    height: 32rpx;
                }
                .clock-img{
                    width: 32rpx;
                    height: 33.5rpx;
                }
            }
        }


        .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;
            }
        }
        .argument{
            margin-bottom: 30rpx;
            position: relative;
            .btn{
                background: linear-gradient(90deg, #201E1C 0%, #625A4E 100%);
                color: #F3A52F;
                font-size: 24rpx;
                width: 120rpx;
                line-height: 42rpx;
                border-radius: 20rpx;
                text-align: center;
                float: left;
                position: absolute;
                left: 0;
                top: 0;
            }
            .argument_text{
                color: #999999;
                text-indent: 5em;
            }
        }
    }
}
</style>