<template>
    <view class="chapeter-list-page">
        <view class="chapter-list-wrap" v-if="info" @click.self="closeAttention">
            <view class="top-box" :style="'background-image:url(' + info.report_info.banner_url + ')'">
                <view class="title">{{info.report_info.classify_name_first}}</view>
                <view class="sub-title">{{info.report_info.title}}</view>
                <view class="flex top-bot">
                    <view class="flex time-box">
                        <view class="day">{{formatChapterTime(info.report_info.publish_time,'day')}}</view>
                        <view>
                            <view>{{formatChapterTime(info.report_info.publish_time,'week')}}</view>
                            <view>{{formatChapterTime(info.report_info.publish_time,'year-month')}}</view>
                        </view>
                    </view>
						  
						  <template v-if="!info.report_info.video_url">
							  <view class="flex audio-play-box" @click="handlePlayWeekAudio(null)" v-if="info.report_info.classify_name_first=='周报'&&info.auth_ok">
									<image class="icon" :src="curAudioReportId==reportId&&!curAudioPaused?'./static/audio-s.png':'./static/audio.png'" mode="aspectFill"/>
									<text>{{curAudioReportId==reportId&&!curAudioPaused?'暂停':'播放'}}</text>
							  </view>
						  </template>
                </view>
                <view :class="[info.report_info.classify_name_first=='晨报'?'stage-num-day':'stage-num-week']">第{{info.report_info.stage}}期</view>
               
					<template v-if="!info.report_info.video_url">
						 <!-- 音频播放设置 -->
						 <view class="audio-play-set-box" v-if="info.report_info.classify_name_first=='周报'&&info.auth_ok">
							  <image class="btn" @click="handleGoSetAudioList" src="./static/set.png" mode="aspectFill"/>
							  <view class="attention-box" v-if="showChapterListAttention">
									点击<span style="color:#E3B377">设置</span>，打开<span style="color:#E3B377">播放列表</span>，进行<span style="color:#E3B377">关注品种配置</span>
									<image class="close-icon" src="./static/close2.png" @click.stop="closeAttention" />
							  </view>
						 </view>
					</template>
            </view>
            <view class="list-box">
                <view class="flex item" v-for="item in chapterList" :key="item.report_chapter_id" @click="goChapterDetail(item)">
                    <view class="img-box">
                        <image class="img" :src="item.report_chapter_type_thumb" mode="aspectFill" />
                    </view>
                    <view class="con">
                        <view class="title">
                            {{item.report_chapter_type_name}} 
                            <text class="tag" :style="{backgroundColor:getTagColor(tag)}" v-for="tag in item.trend.split(',')" :key="tag">{{tag}}</text>
                        </view>
                        <view class="van-multi-ellipsis--l2 sub-title">{{item.title}}</view>
                        <view class="update-time">更新至：{{formatChapterTime(item.publish_time,'year-month-day')}}</view>
                        <view 
                            class="audio-icon-box" 
                            v-if="!info.report_info.video_url&&info.report_info.classify_name_first=='周报'&&item.is_close==0"
                            @click.stop="handlePlayWeekAudio(item)"
                        >
                            <image 
                                class="icon" 
                                :src="curAudioReportId==reportId&&!curAudioPaused&&curAudioUrl==item.video_url?'./static/a-play.png':'./static/a-pause.png'" 
                                mode="aspectFill"
                            />
                        </view> 
                    </view>
                </view>
            </view>
            <!-- 无权限 -->
            <view class="no-auth-box" v-if="!info.auth_ok">
                <image class="img" src="https://hzstatic.hzinsights.com/static/icon/hzyb/activity_no_auth.png" mode="widthFix" />
                <view class="apply-box" v-if="info.permission_check.type=='apply'">
                    <view>您暂无权限查看报告，若想查看请申请开通</view>
                    <view class="global-btn-yellow-change btn" @click="handleGoApply">立即申请</view>
                </view>
                <view class="apply-box" v-else>
                    <view>您暂无权限查看报告 </view>
                    <view>若想查看请联系对口销售：{{info.permission_check.name}}</view>
                    <view class="global-btn-yellow-change btn" @click="handleCall">立即联系</view>
                </view>
            </view>
        </view>
        <!-- 申请提示弹窗 -->
        <van-popup :show="pupData.show" @close="pupData.show=false" :close-on-click-overlay="false">
            <view class="global-pup">
                <view class="content">
                    <view v-html="pupData.content"></view>
                </view>
                <view class="flex bot">
                    <view @click="pupData.show=false">知道了</view>
                </view>
            </view>
        </van-popup>

        <!-- 音频弹窗 -->
        <audioBox v-if="showAudioPop"></audioBox>

    </view>
</template>

<script>
import {apiReportDetail,apiRddpShareImg} from '@/api/report'
import {apiApplyPermission} from '@/api/user'
import audioBox from './components/audioBox.vue'
const dayjs=require('@/utils/dayjs.min')
dayjs.locale('zh-cn') 
export default {
    computed:{
        showAudioPop(){//是否显示音频弹窗
            return this.$store.state.report.audioData.show 
        },
        curAudioReportId(){//当前播放的音频所属报告
            return this.$store.state.report.audioData.reportId
        },
        curAudioPaused(){//当前音频是否暂停状态
            return this.$store.state.report.audioData.paused
        },
        curAudioUrl(){
            return this.$store.state.report.audioData.list[this.$store.state.report.audioData.index]?.video_url
        }
    },
    components: {
        audioBox
    },
    data() {
        return {
            reportId:0,
            chapterList:[],
            info:null,
            pupData:{
				show:false,
				content:'',//弹窗html字符串
			},
            shareData:null,
            showChapterListAttention:false,
        }
    },
    onLoad(opt){
        this.reportId=opt.reportId
        this.getDetail()
    },
    onShareAppMessage() {
        return {
            title:this.shareData.title,
            path:`/pages-report/chapterList?reportId=${this.reportId}`,
            imageUrl:this.shareData.shareImg||''
        }
    },
    onUnload(){
		uni.$off('chapterAudioSet')
	},
    methods: {
        handleCall(){
            uni.makePhoneCall({
                phoneNumber: this.info.permission_check.mobile,
                success: (result) => {},
                fail: (error) => {}
            })
        },
        // 关闭提示
        closeAttention(){
            if(this.info.report_info.classify_name_first=='晨报'||!this.info.auth_ok) return
            uni.setStorageSync('showChapterListAttention','true')
            this.showChapterListAttention=false
        }, 

        // 跳转设置播放清单
        handleGoSetAudioList(){
            this.addEventListenerAudioSet()
            uni.navigateTo({
                url:`/pages-report/audioPlayListSet?reportId=${this.reportId}`,
            })
        },

        // 监听播放清单的设置
        addEventListenerAudioSet(){
            uni.$on('chapterAudioSet',e=>{
                this.getDetail()
            })
        },

        // 点击播放音频
        handlePlayWeekAudio(e){
            const storeAudioData=this.$store.state.report.audioData
            // 如果点击的是总的播放按钮
            if(!e&&storeAudioData.reportId==this.reportId){
                if(this.globalBgMusic.paused){
                    this.globalBgMusic.play()
                    this.$store.commit('showPopAudio')
                }else{
                    this.globalBgMusic.pause()
                }
                return
            }
            const arr=[]
            this.chapterList.forEach(item=>{
                if(item.is_close==0){
                    arr.push({
                        video_url:item.video_url,
                        video_play_seconds:item.video_play_seconds,
                        video_name:item.video_name,
                        video_img:'https://hzstatic.hzinsights.com/static/yb_wx/report_list_zhou.png'
                    })
                }
            })
            let index=0
            if(e){
                arr.forEach((_item,idx)=>{
                    if(_item.video_url==e.video_url) index=idx
                })
            }

            if(storeAudioData.reportId==this.reportId&&storeAudioData.index==index){
                if(this.globalBgMusic.paused){
                    this.globalBgMusic.play()
                    this.$store.commit('showPopAudio')
                }else{
                    this.globalBgMusic.pause()
                }
            }else{
                this.$store.commit('removeAudio')
                this.$nextTick(()=>{
                    this.$store.commit('addAudio', {list:arr,reportId:this.reportId,index:index})
                })
                
            }
        },

        //获取报告详情
        async getDetail(){
            const res=await apiReportDetail({report_id:Number(this.reportId)})
            if(res.code===200){
                this.info=res.data
                this.chapterList=res.data.report_chapter_list
                uni.setNavigationBarTitle({
                    title: res.data.report_info.classify_name_first,
                    success: (result) => {},
                    fail: () => {},
                    complete: () => {}
                });

                if(!res.data.auth_ok){
                    // 获取详情如果为联系销售根据判断条件是否主动申请一次
                    if(this.info.permission_check.type=='contact'&&!this.info.permission_check.customer_info.has_apply){
                        if(this.info.permission_check.customer_info.status=='冻结'||(this.info.permission_check.customer_info.status=='试用'&&this.info.permission_check.customer_info.is_suspend==1)){
                            apiApplyPermission({
                                company_name:this.info.permission_check.customer_info.company_name,
                                real_name:this.info.permission_check.customer_info.name,
                                source:4,
                                from_page:'报告详情'
                            }).then(res=>{
                                if(res.code===200){
                                    console.log('主动申请成功');
                                }
                            }) 
                        }
                    }
                }
                
                this.getShareData()
            
                // 周报判断是否要显示提示
                if(res.data.report_info.classify_name_first=='周报'){
                    const showAtt=uni.getStorageSync('showChapterListAttention')||""
                    if(showAtt){
                        this.showChapterListAttention=false
                    }else{
                        this.showChapterListAttention=true
                    }
                }
                
            }
        },

        // 跳转章节详情
        goChapterDetail(item){
            uni.navigateTo({
                url:`/pages-report/chapterDetail?chapterId=${item.report_chapter_id}&fromPage=reportdetail`
            })
        },

        // 设置分享的数据
        async getShareData(){
            //处理分享标题
            let shareTitle=''
            let shareImg=''
            let imgText=''//分享图上需要显示的内容
                
            const shareTime=dayjs(this.info.report_info.publish_time).format('MMDD')
            if(this.info.report_info.abstract){
                shareTitle=this.info.report_info.abstract
                imgText=`<div style="font-size:78px">第${this.info.report_info.stage}期 | ${this.info.report_info.title}（${shareTime}）</div>`
            }else{
                shareTitle=this.info.report_info.title
                imgText=`<div style="font-size:78px">${dayjs(this.info.report_info.publish_time).format('YYYY/MM/DD')}</div><div style="font-size:78px">第${this.info.report_info.stage}期 | ${this.info.report_info.classify_name_second}</div>`
                if(['晨报','周报'].includes(this.info.report_info.classify_name_first)){
                    imgText=`<div style="font-size:78px">${dayjs(this.info.report_info.publish_time).format('YYYY/MM/DD')}</div><div style="font-size:78px">第${this.info.report_info.stage}期 | ${this.info.report_info.classify_name_first} </div>`
                }
            }
            const rddpImgRes=await apiRddpShareImg({
                pars:JSON.stringify({
                    title:imgText,
                    time_format:dayjs(this.info.report_info.publish_time).format('YYYY/MM/DD'),
                    background_img:this.info.report_info.share_bg_img
                }),
                report_id:Number(this.reportId)
            })
            if(rddpImgRes.code===200){
                shareImg=rddpImgRes.data
            }
            this.shareData={
                title:shareTitle,
                reportId:this.reportId,
                shareImg:shareImg
            }
        },

        //点击申请
        async handleGoApply(){
            if(this.userInfo.is_bind===0){
                Dialog.confirm({
                    title:'温馨提示',
                    message:'为了优化您的用户体验，\n 请登录后查看更多信息！',
                    confirmButtonText:'去登录',
                    confirmButtonColor:'#E6B77D',
                    cancelButtonColor:'#666'
                }).then(res=>{
                    uni.reLaunch({url:'/pages/login'})
                })
                return
            }
            if(this.info.permission_check.type=='apply'){
                if(this.info.permission_check.customer_info.has_apply){// 已经申请过
                    this.pupData.show=true
					this.pupData.content=`<p>您已提交过申请，请耐心等待</p>`
                }else{
                    if(!this.info.permission_check.customer_info.status||this.info.permission_check.customer_info.status!='流失'||this.info.permission_check.customer_info.status!='关闭'){
                        uni.redirectTo({
                            url:"/pages-applyPermission/applyPermission?source=4&from_page=报告详情"
                        })
                    }else{//主动调一次申请权限接口 
                        const res=await apiApplyPermission({
                            company_name:this.info.permission_check.customer_info.company_name,
                            real_name:this.info.permission_check.customer_info.name,
                            source:4,
                            from_page:'报告详情'
                        })
                        if(res.code===200){
                            this.pupData.show=true
					        this.pupData.content=`<p>申请已提交</p><p>请等待销售人员与您联系</p>`
                            this.getDetail()
                        }
                    }
                }
                
            }
        },

        // 格式化章节列表时间
        formatChapterTime(time,type){
            if(type==='day'){
                return dayjs(time).format('DD')
            }
            if(type==='week'){
                return dayjs(time).format('dddd')
            }
            if(type==='year-month'){
                return dayjs(time).format('YYYY-MM')
            }
            if(type==='year-month-day'){
                return dayjs(time).format('YYYY-MM-DD')
            }
        },

        // 设置tag颜色
        getTagColor(str){
            if( str.includes('多')||str.includes('强')||str.includes('反弹') ){
                return "#DF6051";
            }else if( str.includes('空')||str.includes('调整') ){
                return "#6FC5B4";
            }else{
                return "#009fe6";
            }
        },
    },
}
</script>

<style lang="scss" scoped>
.global-pup{
    background-color: #fff;
    width: 90vw;
    min-height: 200rpx;
    font-size: 32rpx;
    .content{
        padding: 34rpx;
        text-align: center;
        min-height: 250rpx;
        display: flex;
        align-items: center;
        text-align: center;
        line-height: 1.7;
        div{
            flex: 1;
        }
    }
    .bot{
        border-top: 1px solid #dedede;
        div{
            line-height: 96rpx;
            flex: 1;
            text-align: center;
            border-right: 1px solid #dedede;
            color:#E3B377;
        }
        div:last-child {
            border: none;
        }
    }
}
    .chapter-list-wrap{
        .top-box{
            height: 418rpx;
            background-color: rgba($color: #000000, $alpha: 0.7);
            background-size: cover;
            color: #fff;
            position: relative;
            .title{
                text-align: center;
                font-size: 34rpx;
                font-weight: 600;
                padding-top: 78rpx;
            }
            .sub-title{
                font-size: 32rpx;
                text-align: center;
                width: 70%;
                margin-left: auto;
                margin-right: auto;
            }
            .top-bot{
                position: absolute;
                bottom: 70rpx;
                left: 34rpx;
                right: 34rpx;
                justify-content: space-between;
                align-items: center;
                .time-box{
                    align-items: center;
                    font-size: 24rpx;
                    .day{
                        font-size: 32rpx;
                        border-right: 1px solid #fff;
                        padding-right: 15rpx;
                        margin-right: 15rpx;
                    }
                }

                .audio-play-box{
                    align-items: center;
                    width: 180rpx;
                    height: 52rpx;
                    background-color: #E3B377;
                    border-radius: 25rpx;
                    justify-content: center;
                    color: #fff;
                    font-size: 24rpx;
                    .icon{
                        width: 34rpx;
                        height: 34rpx;
                        margin-right: 8rpx;
                    }
                }
            }
            .stage-num-week{
                position: absolute;
                top: 40rpx;
                left: 34rpx;
            }
            .stage-num-day{
                position: absolute;
                right: 34rpx;
                bottom: 70rpx;
            }
            .audio-play-set-box{
                position: absolute;
                top: 20rpx;
                right: 34rpx;
                .btn{
                    width: 91rpx;
                    height: 52rpx;
                }
                .attention-box{
                    position: absolute;
                    width: 634rpx;
                    right: 20rpx;
                    top: 110%;
                    background-color: #fff;
                    color: #333;
                    box-shadow: 0px 0px 10rpx 4rpx rgba(0, 0, 0, 0.16);
                    padding: 20rpx 54rpx 20rpx 20rpx;
                    border-radius: 8rpx;
                    .close-icon{
                        width: 24rpx;
                        height: 24rpx;
                        position: absolute;
                        top: 50%;
                        transform: translateY(-50%);
                        right: 20rpx;
                    }
                    &::after{
                        content: '';
                        display:block;
                        width: 0;
                        height: 0;
                        border: 10rpx solid transparent;
                        border-bottom-color: #fff;
                        position: absolute;
                        top: -20rpx;
                        right: 20rpx;
                    }
                }
            }
            
        }
        .list-box{
            margin-top: -50rpx;
            border-top-left-radius: 40rpx;
            border-top-right-radius: 40rpx;
            min-height: 100rpx;
            background-color: #fff;
            position: relative;
            z-index: 2;
            .item{
                padding: 30rpx 34rpx;
                border-bottom: 1px solid #E5E5E5;
                .img-box{
                    width: 104rpx;
                    height: 104rpx;
                    box-sizing: border-box;
                    border-radius: 8rpx;
                    border: solid 2.5rpx #E5E5E5;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-right: 20rpx;
                    .img{
                        width: 60rpx;
                        height: 60rpx;
                    }
                }
                .con{
                    flex: 1;
                    position: relative;
                    .title{
                        font-size: 28rpx;
                        color: #57768D;
                        font-weight: bold;
                        margin-bottom: 5rpx;
                        .tag{
                            font-size: 20rpx;
                            color: #fff;
                            font-weight: normal;
                            display: inline-block;
                            background-color: #1E88E5;
                            line-height: 37rpx;
                            padding: 0 6rpx;
                            border-radius: 4rpx;
                            margin-left: 10rpx;
                        }
                    }
                    .sub-title{
                        color: #999;
                    }
                    .update-time{
                        color: #D4D4D4;
                        font-size: 24rpx;
                        margin-top: 5rpx;
                    }
                    .audio-icon-box{
                        position: absolute;
                        top: 50%;
                        right: 0;
                        width: 60rpx;
                        height: 56rpx;
                        transform: translateY(-50%);
                        background: linear-gradient(180deg, #F3A52F 0%, #E3B377 100%);
                        border-radius: 12rpx;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        .icon{
                            width: 40rpx;
                            height: 40rpx;
                        }
                    }
                }
            }
        }
        .no-auth-box{
            text-align: center;
            font-size: $global-font-size-lg;
            /* color: #E3B377; */
            img{
                width: 100%;
                margin-bottom: 50rpx;
            }
            .btn{
                /* width: 90%;
                margin-left: auto;
                margin-right: auto;
                line-height: 80rpx;
                background-color: #E6B77D;
                border-radius: 4rpx;
                color: #fff;
                margin-top: 100rpx;
                display: block; */
                width: 380rpx;
                line-height: 70rpx;
                margin-left: auto;
                margin-right: auto;
                margin-top: 40rpx;
            }
        }
    }
</style>