<script setup name="reportChapterDetail">
import {ref,onMounted,onUnmounted, reactive, nextTick} from 'vue'
import apiReport from '@/api/report'
import apiChart from '@/api/chart'
import { useRoute, useRouter } from 'vue-router'
import EditChapterBaseInfo from './components/EditChapterBaseInfo.vue'
import AudioBox from '../components/AudioBox.vue'
import ReportInsertContent from '../components/reportInsert/Index.vue'
import moment from 'moment'
import {useInitFroalaEditor} from '@/hooks/useFroalaEditor'
import {useUserInfo,isWeiXin} from '@/hooks/common'
import { showToast,showDialog } from 'vant'
import {useUploadFileToOSS} from '@/hooks/useUploadFileToOSS'
import MD5 from 'js-md5'
import {reportManageBtn} from '@/hooks/useAuthBtn'
import {usePublicSettingStore} from '@/store/modules/publicSetting'

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

const userInfo=useUserInfo()
const publicSettingStore = usePublicSettingStore()

const {lastFocusPosition,initFroalaEditor,imgUploadFlag,frolaEditorContentChange}=useInitFroalaEditor()
let reportContentEditorIns=null//报告内容编辑器实例

let autoSaveTimer=null

onMounted(() => {
    getChapterDetail()
    autoSaveTimer=setInterval(() => {
        autoSaveReportContent()
    }, 6000);
})
onUnmounted(()=>{
    clearInterval(autoSaveTimer)
})
// 自动保存
function autoSaveReportContent(e){
    if(!e&&!frolaEditorContentChange.value) return
    if(!imgUploadFlag.value){
        e==='cg'&&showToast('有图片未上传完成,请稍等')
        return
    }
    let arr=[]
    ticketList.value.forEach(item=>{
        let obj={
            ticker:'',
            sort:1,
            lable:''
        }
        if(item.Selected){
            obj.ticker=item.BaseColumnTicker
			obj.sort=arr.length+1
			obj.lable=item.BaseColumnName
			arr.push(obj)
        }
    })
    //如果富文本中有未上传完成的图片,去除这个dom
	$('.fr-element').find('img.fr-uploading').length&&$('.fr-element').find('img.fr-uploading').remove()
    apiReport.chapterDetailSave({
        ReportChapterId: Number(route.query.id),
		Title:chapterBaseInfo.title,
		AddType:chapterBaseInfo.addType,
		Author:chapterBaseInfo.author,
		CreateTime:chapterBaseInfo.createTime,
		TickerList:arr,
		Content: $('.fr-element').html(),
		VideoUrl:chapterBaseInfo.audioUrl,
		VideoName:`${chapterBaseInfo.title}(${moment().format('MMDD')})`,
		VideoPlaySeconds:Number(chapterBaseInfo.audioDuration).toFixed(2).toString(),
		VideoSize:Number(chapterBaseInfo.audioSize).toFixed(2).toString()
    }).then(res=>{
        if(res.Ret===200){
            if(e==='cg'){
                showToast('保存成功')
            }
        }
        frolaEditorContentChange.value=false
    })
}


let info=ref(null)
function getChapterDetail(){
    apiReport.getChapterDetail({
        ReportChapterId:Number(route.query.id)
    }).then(res=>{
        if(res.Ret===200){
            info.value=res.Data
            document.title=`${res.Data.ClassifyNameFirst}-${res.Data.TypeName}`

            chapterBaseInfo.type=res.Data.TypeName
            chapterBaseInfo.title=res.Data.Title
            chapterBaseInfo.addType=res.Data.AddType
            chapterBaseInfo.author=res.Data.Author||userInfo.value.RealName
            chapterBaseInfo.createTime=moment(res.Data.CreateTime).format('YYYY-MM-DD')
            if(res.Data.VideoKind==1){
                chapterBaseInfo.audioUrl=res.Data.VideoUrl
                chapterBaseInfo.audioDuration=res.Data.VideoPlaySeconds
                chapterBaseInfo.audioSize=res.Data.VideoSize
            }

            // 晨报获取指标数据
            if(res.Data.ReportType=='day'){
                getDayTicketList()
            }
            
            // 由于周报有个上传音频区域 所以得在此处初始化富文本区域 不然高度有问题
            nextTick(()=>{
                const el=document.getElementById('editor')
                reportContentEditorIns=initFroalaEditor('#editor',{height:el.offsetHeight-150})
                setTimeout(() => {
                    reportContentEditorIns.html.set(res.Data.Content);
                }, 100);
            })
            
        }
    })
}

// 获取晨报指标数据
let ticketList=ref([])
async function getDayTicketList(){
    const res=await apiReport.chapterDayReportTicketList({
        ReportChapterId:info.value.ReportChapterId
    })
    if(res.Ret===200){
        ticketList.value=res.Data||[]
    }
}

// 报告基本内容
const showChapterBaseInfo=ref(false)
const chapterBaseInfo=reactive({
    type:'',
    title:'',
    addType:'',
    author:'',
    createTime:'',
    audioUrl:'',
    audioDuration:0,
    audioSize:0,
})
// 更新报告基本内容
async function handleChapterBaseInfoSave(e){
    console.log(e);
    chapterBaseInfo.type=e.type
    chapterBaseInfo.title=e.title
    chapterBaseInfo.author=e.author
    chapterBaseInfo.createTime=e.createTime
    ticketList.value=e.ticket

    // 如果修改报告的新增方式 则刷新数据
    if(chapterBaseInfo.addType!=e.addType){
        chapterBaseInfo.addType=e.addType
        // 继承报告
        if(e.addType==2){
            const res=await apiReport.chapterReportPreContent({
                TypeId:info.value.TypeId,
                ReportType:info.value.ReportType
            })
            if(res.Ret===200){
                chapterBaseInfo.type=res.Data.TypeName
                chapterBaseInfo.title=res.Data.Title
                chapterBaseInfo.author=res.Data.Author||userInfo.RealName
                chapterBaseInfo.createTime=moment(res.Data.CreateTime).format('YYYY-MM-DD')
                reportContentEditorIns.html.set(res.Data.Content);
                // 晨报获取指标数据
				if(res.Data.ReportType=='day'){
					getDayTicketList()
				}
            }
        }else{
            reportContentEditorIns.html.set('');
        }
    }
    
    
    showChapterBaseInfo.value=false
}

// 上传音频
const showUploadAudio=ref(false)
const temAudioData=reactive({
    time:0,
    size:0,
    url:'',
})
function handleShowUploadAudio(){
    temAudioData.time=chapterBaseInfo.audioDuration
    temAudioData.size=chapterBaseInfo.audioSize
    temAudioData.url=chapterBaseInfo.audioUrl
    showUploadAudio.value=true
}
// 获取音频时长
function handleGetAudioDuration(file){
    return new Promise((resolve,reject)=>{
        if(isWeiXin()){
            console.log('微信？');
            resolve(0)
        }

        const fileUrl=URL.createObjectURL(file)
        const audioEl=new Audio(fileUrl)
        audioEl.addEventListener('loadedmetadata',(e)=>{
            console.log('e.path',e.path)
            console.log('e.composedPath',e.composedPath())
            console.log('获取音频时长',e.composedPath()[0].duration);
            console.log(audioEl.duration);
            const t=e.composedPath()[0].duration
            resolve(t)
        })
    })
}
function handleAudioUploadBeforeRead(e){
    const allowedTypes = ['audio/mpeg', 'audio/mp4','audio/aac','audio/x-m4a','audio/wav']
    //由于部分安卓机的部分浏览器无法获取到文件类型，无法判断故先去除判断
    // if(!allowedTypes.includes(e.type)){
    //     showToast('上传失败，上传音频格式不正确')
    //     return false
    // }
    return true
}
async function handleAudioUploadAfterRead(e){
    // console.log(e);
    const duration=await handleGetAudioDuration(e.file)
    // if(duration>60*15){
    //     showToast('音频时长不得超过15分钟')
    //     return
    // }
    temAudioData.time=duration||0
    temAudioData.size=e.file.size/1024/1024 //单位MB
    temAudioData.name=e.file.name
    console.log('音频数据temAudioData',temAudioData);
    // 生成文件名
    const t=new Date().getTime().toString()
    const temName=`static/yb/audio/${import.meta.env.MODE}/${MD5(t)}.${e.file.type.split('/')[1]}`
    console.log(temName);
    temAudioData.url=await useUploadFileToOSS(e.file,temName)
}
function handleUpdateAudio(){
    chapterBaseInfo.audioUrl=temAudioData.url
    chapterBaseInfo.audioDuration=temAudioData.time
    chapterBaseInfo.audioSize=temAudioData.size
    showUploadAudio.value=false
}
//更新下音频时长
function handleUpdateAudioTime(e){
    temAudioData.time=e
}

// 报告插入数据弹窗
const showReportInsertPop=ref(false)
/**
 * list:[UniqueCode] 图表code
 * type:iframe/img 插入的为iframe或者图片
 * chartType: chart-图表,sheet-表格
 */
function handleInsert({list,type,chartType}){
    reportContentEditorIns.events.focus()
    if(lastFocusPosition.value){
        reportContentEditorIns.selection.get().removeAllRanges()
        reportContentEditorIns.selection.get().addRange(lastFocusPosition.value)
    }
    if(type==='iframe'){
        let link=publicSettingStore.publicSetting.ChartViewUrl;
        if(chartType==='chart'){
            // link=import.meta.env.MODE==='production'?'https://chartlib.hzinsights.com/chartshow':'https://charttest.hzinsights.com/chartshow'
            link=link+'/chartshow'
            list.forEach(item => {
                reportContentEditorIns.html.insert(`<p style='text-align:left; margin-top:10px;'>
						<iframe src='${link}?code=${item}&fromPage=' width='100%' height='350' style='border-width:0px; min-height:350px;'></iframe>
					</p>`)
            });
        }else if(chartType==='sheet'){
            // link=import.meta.env.MODE==='production'?'https://chartlib.hzinsights.com/sheetshow':'https://charttest.hzinsights.com/sheetshow'
            link=link+'/sheetshow'
            list.forEach(item => {
                reportContentEditorIns.html.insert(`<p style='text-align:left; margin-top:10px;'>
						<iframe src='${link}?code=${item}' class='iframe${item}'  width='100%' style='border-width:0px;'></iframe>
					</p>`)
            });
        }
    }else if(type==='img'){
        list.forEach(item=>{
            reportContentEditorIns.html.insert(`<img style='width:100%' src='${item}' />`)
        })
    }

    showReportInsertPop.value=false
}

// 更新sheet表格高度
function reInitSheetIframe(e){
    const { height,code } = e.data;
    let iframeDom = document.getElementsByClassName(`iframe${code}`)
    Array.prototype.forEach.call(iframeDom, function (ele) {
        ele.height = `${height+45}px`;
    });
}
onMounted(()=>{
    window.addEventListener('message',reInitSheetIframe)
})
onUnmounted(()=>{
    window.removeEventListener('message',reInitSheetIframe)
})

// 刷新所有图表
async function handleRefreshAllChart(){
    let code_arr = [];
    $('iframe').each((k,i) => {
        try {
          let href = $(i).attr('src');
          code_arr.push(href.slice(href.indexOf('code=') + 5));
        } catch (err) {
        }
    });
    if(!code_arr.length) return showToast('请插入图表');
    
    if(route.query.id) {
        let res = await apiChart.getReportrefreshStatus({
            Source: 'report',
            ReportId: Number(route.query.id),
            ReportChapterId: 0
        });
        
        if(!res.Data.RefreshResult) return showToast('图表正在刷新中，请勿重复操作')
    }
    const res=await apiChart.refreshChartMultiple({ChartInfoCode:code_arr})
    if(res.Ret===200){
        $('iframe').each((k,i) => {
          $(i).attr('src',$(i).attr('src'))
        });
        showToast('刷新成功')
    }
}

//周报校验是否上传了音频
function handleWeekValidAudio(){
    return new Promise((resolve,reject)=>{
        showDialog({
            title: '发布提示',
            message: '您还未上传录音文件，确定发布报告吗？',
            showCancelButton:true
        }).then(()=>{
            resolve(true)
        }).catch(()=>{
            resolve(false)
        })
    })
}

// 发布章节报告
async function chapterReportPublish(PublishReport){
    let arr=[]
    ticketList.value.forEach(item=>{
        let obj={
            ticker:'',
            sort:1,
            lable:''
        }
        if(item.Selected){
            obj.ticker=item.BaseColumnTicker
			obj.sort=arr.length+1
			obj.lable=item.BaseColumnName
			arr.push(obj)
        }
    })
    //如果富文本中有未上传完成的图片,去除这个dom
	$('.fr-element').find('img.fr-uploading').length&&$('.fr-element').find('img.fr-uploading').remove()
    const res=await apiReport.chapterReportPublish({
        ReportChapterId: Number(route.query.id),
		Title:chapterBaseInfo.title,
		AddType:chapterBaseInfo.addType,
		Author:chapterBaseInfo.author,
		CreateTime:chapterBaseInfo.createTime,
		TickerList:arr,
		Content: $('.fr-element').html(),
        PublishReport:PublishReport,
		VideoUrl:chapterBaseInfo.audioUrl,
		VideoName:`${chapterBaseInfo.title}(${moment().format('MMDD')})`,
		VideoPlaySeconds:Number(chapterBaseInfo.audioDuration).toFixed(2).toString(),
		VideoSize:Number(chapterBaseInfo.audioSize).toFixed(2).toString()
    })
    if(res.Ret===200){
        showToast('发布成功')
        setTimeout(() => {
            router.back()
        }, 1000);
    }
}

// 发布报告-fb;保存-cg;预览-yl
async function handleReportOpt(type){
    if(type==='yl'){

        const params={
            Title:chapterBaseInfo.title,
            Author:chapterBaseInfo.author,
            PublishTime:chapterBaseInfo.createTime,
            Abstract:'',
            Content:$('.fr-element').html()
        }
        if(!params.Title){
            showToast('请填写标题')
            return
        }
        sessionStorage.setItem('reportPreData',JSON.stringify(params))
        const routerEl=router.resolve({
            path:'/report/preview',
            query:{
                id:-1
            }
        })
        window.open(routerEl.href,'_blank')
        return
    }
    if(type==='cg'){
        autoSaveReportContent('cg')
    }
    if(type==='fb'){
        if(info.value.ReportType==='week'&&!chapterBaseInfo.audioUrl){
            const validRes=await handleWeekValidAudio()
            if(!validRes) return
        }
        const res=await apiReport.chapterReportIsLast({ReportChapterId:info.value.ReportChapterId})
        if(res.Ret===200){
            if(res.Data){
                showDialog({
                    title: '发布提示',
                    message: '本期报告品种已全部更新，点击发布将同时发布周报，确认同时发布吗？',
                    showCancelButton:true
                }).then(()=>{
                    chapterReportPublish(1)
                }).catch(()=>{
                    chapterReportPublish(0)
                })
            }else{
                chapterReportPublish(0)
            }
        }
    }
}

</script>

<template>
    <div class="chapter-detail-edit-page">
        <van-cell title="章节基础配置" is-link @click="showChapterBaseInfo=true"/>
        <van-cell title="上传音频" is-link v-if="info?.ReportType==='week'" @click="handleShowUploadAudio"/>
        <div class="main-wrap">
            <div class="editor-box" id="editor"></div>
        </div>
        <!-- 底部操作 -->
        <div class="bot-action-box">
            <div class="left-box">
                <div class="item" @click="handleRefreshAllChart">
                    <img src="@/assets/imgs/report/icon_refresh.png" alt="">
                    <span>刷新</span>
                </div>
                <div class="item" @click="handleReportOpt('yl')" v-permission="reportManageBtn.reportManage_reportView">
                    <img src="@/assets/imgs/report/icon_preview.png" alt="">
                    <span>预览</span>
                </div>
                <div class="item" @click="handleReportOpt('cg')">
                    <img src="@/assets/imgs/report/icon_save2.png" alt="">
                    <span>保存</span>
                </div>
                <div class="item" @click="handleReportOpt('fb')" v-permission="reportManageBtn.reportManage_publish">
                    <img src="@/assets/imgs/report/icon_publish3.png" alt="">
                    <span>发布</span>
                </div>
            </div>
            <div class="right-btn" @click="showReportInsertPop=true">
                <svg width="28" height="28" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12.0499 15.9499V27.5H15.9499V15.9499H27.5V12.0499H15.9499V0.5H12.0499V12.0499H0.5V15.9499H12.0499Z" fill="white"/>
                </svg>
            </div>
        </div>
    </div>

    <!-- 基础信息 -->
    <van-popup 
        v-model:show="showChapterBaseInfo" 
        position="bottom"
        :style="{height:'100%'}"
    >
        <EditChapterBaseInfo
            v-if="showChapterBaseInfo"
            :ticketData="ticketList"
            :chapterInfo="info"
            :defaultData="chapterBaseInfo"
            @close="showChapterBaseInfo=false"
            @confirm="handleChapterBaseInfoSave"
        />
    </van-popup>

    <!-- 上传音频 -->
    <van-popup 
        v-model:show="showUploadAudio" 
        position="bottom"
        round
        :style="{height:'60%'}"
    >
        <div class="upload-audio-wrap" v-if="showUploadAudio">
            <div style="font-size:12px;color:#666">tips:如果是在微信中访问,请上传完音频点击播放,获取音频时长后方可保存</div>
            <template v-if="temAudioData.url">
                <h2>音频链接</h2>
                <p>{{temAudioData.url}}</p>
                <AudioBox :time="temAudioData.time" :url="temAudioData.url" @updateDuration="handleUpdateAudioTime"/>
            </template>
            <div class="bot-btns">
                <van-uploader 
                    accept="*" 
                    :after-read="handleAudioUploadAfterRead"
                    :before-read="handleAudioUploadBeforeRead"
                >
                    <van-button class="bot-btn" type="default">{{temAudioData.url?'重新上传':'上传音频'}}</van-button>
                </van-uploader>
                <van-button class="bot-btn" type="primary" :disabled="!temAudioData.url||temAudioData.time===0" @click="handleUpdateAudio">保存</van-button>
            </div>
        </div>
    </van-popup>

    <!-- 报告插入数据模块 -->
    <van-popup
        v-model:show="showReportInsertPop"
        position="bottom"
        round
    >
        <report-insert-content v-if="showReportInsertPop" @insert="handleInsert"/>
    </van-popup>
</template>

<style lang="scss" scoped>
.chapter-detail-edit-page{
    height: 100dvh;
    min-height: 95vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}
.van-cell{
    flex-shrink: 0;
}
.main-wrap{
    flex: 1;
    width: calc(100% - 32PX);
    margin: 0 auto;
    margin-top: 30px;
    .editor-box{
        width: 100%;
        height: 100%;
    }
}
.bot-action-box{
    padding: 20px 16PX;
    display: flex;
    align-items: center;
    .left-box{
        flex: 1;
        background: #FFFFFF;
        box-shadow: 0px 12px 60px 10px rgba(0, 0, 0, 0.05), 0px 32px 48px 4px rgba(0, 0, 0, 0.04), 0px 16px 20px -10px rgba(0, 0, 0, 0.08);
        border-radius: 100px;
        height: 112px;
        display: flex;
        align-items: center;
        margin-right: 20px;
        padding: 0 20px;
        .item{
            flex: 1;
            text-align: center;
            font-size: 20px;
            img{
                width: 40px;
                height: 40px;
                display: block;
                margin: 5px auto;
            }
        }
    }
    .right-btn{
        flex-shrink: 0;
        position: relative;
        width: 96px;
        height: 96px;
        background-color: $theme-color;
        border-radius: 50%;
        box-shadow: 0px 6px 28px 4px rgba(0, 0, 0, 0.05), 0px 16px 20px 2px rgba(0, 0, 0, 0.06), 0px 10px 10px -6px rgba(0, 0, 0, 0.1);
        svg{
            width: 27px;
            height: 27px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
        }
    }
}

.upload-audio-wrap{
    height: 100%;
    position: relative;
    overflow: hidden;
    padding: $page-padding;
    p{
        color: rgba(0, 0, 0, 0.6);
        padding-bottom: 32px;
        border-bottom: 1px solid $border-color;
        margin-bottom: 32px;
        word-wrap: break-word;
    }
    .bot-btns{
        // width: 100%;
        position: absolute;
        bottom: 0;
        padding: 20px 0;
        text-align: center;
        .bot-btn{
            width: 315px;
            margin: 0 10px;
        }
    }
}
@media screen and (min-width:$media-width){
    .chapter-detail-edit-page{
        height: calc(100dvh - 60px);
        min-height: calc(95vh - 60px);
    }
    .main-wrap{
        margin-top: 15px;
    }
    .bot-action-box{
        margin: 0 auto;
        width: 600px;
        padding: 10px 16px;
        .left-box{
            border-radius: 50px;
            height: 56px;
            margin-right: 10px;
            padding: 0 10px;
            .item{
                font-size: 12px;
                img{
                    width: 20px;
                    height: 20px;
                    margin: 3px auto;
                }
            }
        }
        .right-btn{
            width: 48px;
            height: 48px;
            svg{
                width: 14px;
                height: 14px;
            }
        }
    }
}
</style>