<script setup name="reportChapterList">
import {nextTick, reactive, ref} from 'vue'
import { useRoute, useRouter } from "vue-router";
import apiReport from '@/api/report'
import {apiGetWXQRCodeImg} from '@/api/common'
import moment from 'moment';
import { showToast,showDialog } from 'vant';
import { useWindowSize } from '@vueuse/core'
import {useCachedViewsStore} from '@/store/modules/cachedViews'
import EditBaseInfo from './components/EidtBaseInfo.vue'
import html2canvas from "html2canvas";
import {transfImgTobase64} from '@/hooks/common'

const cachedViewsStore=useCachedViewsStore()
const { width, height } = useWindowSize()


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

//基础信息
const showBaseInfoPop=ref(false)
//更新基本信息
function handleUpdateBaseInfo(e){
    reportInfo.value.Title=e.title
    reportInfo.value.Author=e.author
    reportInfo.value.CreateTime=e.createtime
    showBaseInfoPop.value=false
}

// 获取报告详情
let reportInfo=ref(null)
async function getReportDetail(){
    const res=await apiReport.getReportDetail({ReportId:Number(route.query.id)})
    if(res.Ret===200){
        reportInfo.value=res.Data
        document.title=res.Data.ClassifyNameFirst
    }
    getChapterList()
}
getReportDetail()

// 获取章节列表
let chapterList=ref([])
async function getChapterList(){
    const res=await apiReport.getChapterList({ReportId:Number(route.query.id)})
    if(res.Ret===200){
        chapterList.value=res.Data||[]
        getChapterTrendTagList()
    }
}


// 获取章节标签数据
let tagOpts=ref([])
function getChapterTrendTagList(){
    apiReport.getChapterTagList().then(res=>{
        if(res.Ret===200){
            tagOpts.value=res.Data
        }
    })
}

const showTagPop=ref(false)
const isEditTag=ref(false)
const customFieldName={
    text: 'KeyWord',
    value: 'KeyWord',
}
const temTrendTagData=reactive({
    ReportChapterId:'',
    tagVal:['']
})
function handleShowTrendTag(item){
    temTrendTagData.ReportChapterId=item.ReportChapterId
    temTrendTagData.tagVal[0]=item.Trend||tagOpts.value[0].KeyWord
    showTagPop.value=true
    isEditTag.value=item.Trend?true:false
}
function handleConfirmEditTrendTag(){
    if(reportInfo.value.State==2){
        showToast('报告已发布，不可修改')
        return
    }
    apiReport.editChapterTrendTag({
        ReportChapterId:Number(temTrendTagData.ReportChapterId),
        Trend:temTrendTagData.tagVal[0]||''
    }).then(res=>{
        if(res.Ret===200){
            showToast('修改成功')
            showTagPop.value=false
            getChapterList()
        }
    })
}


// 跳转章节详情
function goChapterDetail(item){
    router.push({
        path:'/report/chapter/detail',
        query:{
            id:item.ReportChapterId
        }
    })
}


// 保存报告信息
async function handleSaveReportInfo(){
    if(!reportInfo.value.Title){
        showToast('请填写报告标题')
        return
    }
    const params={
        ReportId:reportInfo.value.Id,
        Title:reportInfo.value.Title,
        ReportType:reportInfo.value.ClassifyNameFirst=='周报'?'week':'day',
        CreateTime:moment(reportInfo.value.CreateTime).format('YYYY-MM-DD'),
        Author:reportInfo.value.Author
    }
    const res=await apiReport.editDayWeekReport(params)
    if(res.Ret===200){
        showToast('保存成功')
    }
}

// 周报校验音频是否都上传了
async function handlePublishValid(){
    if(reportInfo.value.ClassifyNameFirst==='周报'){
        const validRes=await apiReport.weekReportValidAudio({ReportId:Number(reportInfo.value.Id)})
        if(validRes.Ret===200){
            if(validRes.Data){
                showDialog({
                    title: '发布提示',
                    message: `报告未上传录音：${validRes.Data.join('、')}，确定发布吗？`,
                    showCancelButton:true
                }).then(() => {
                    // on close
                    handlePublishReport()
                }).catch(()=>{})
            }
        }
        return
    }else{
        handlePublishReport()
    }
}

// 发布报告 晨报提示是否推送客群
async function handlePublishReport(){
    const res=await apiReport.publishDayOrWeekReport({ReportId:Number(reportInfo.value.Id)})
    if(res.Ret!=200)return
    // 清除列表缓存
    cachedViewsStore.removeCaches('ReportList')

    if(reportInfo.value.ClassifyNameFirst==='周报'){
        showToast('发布成功')
        router.back()
        return
    }
    // 晨报
    if(res.Data){
        showDialog({
            title: '发布提示',
            message: res.Data,
        }).then(()=>{
            showDialog({
                title: '发布提示',
                message: `发布后，是否推送模板消息和客户群？`,
                showCancelButton:true,
                confirmButtonText:'推送',
                cancelButtonText:'不推送'
            }).then(async() => {
                // on close
                const pushRes=await apiReport.reportMessageSend({ReportId:Number(reportInfo.value.Id)})
                if(pushRes.Ret===200){
                    showToast('推送成功')
                    router.back()
                }
            }).catch(()=>{
                showToast('发布成功')
                router.back()
            })
        })
    }else{
        showDialog({
            title: '发布提示',
            message: `发布后，是否推送模板消息和客户群？`,
            showCancelButton:true,
            confirmButtonText:'推送',
            cancelButtonText:'不推送'
        }).then(async() => {
            // on close
            const pushRes=await apiReport.reportMessageSend({ReportId:Number(reportInfo.value.Id)})
            if(pushRes.Ret===200){
                showToast('推送成功')
                router.back()
            }
        }).catch(()=>{
            showToast('发布成功')
            router.back()
        })
    }
}

// 显示海报
const showChapterItemPoster=ref(false)
const chapterItemPosterInfo=ref(null)
const posterImgBase64=ref('')
async function handleShowPoster(item){
    if(!item.QRCodeImg){//获取二维码
        const res=await apiGetWXQRCodeImg({
            CodeScene:JSON.stringify({chapterId:item.ReportChapterId.toString()}),
            CodePage:'pages-report/chapterDetail'
        })
        if(res.Ret===200){
            item.QRCodeImg=res.Data
        }
    }
    chapterItemPosterInfo.value=item
    chapterItemPosterInfo.value.TypeEditImg=await transfImgTobase64(chapterItemPosterInfo.value.TypeEditImg)
    chapterItemPosterInfo.value.QRCodeImg=await transfImgTobase64(chapterItemPosterInfo.value.QRCodeImg)

    nextTick(()=>{
        const targetEl = document.getElementById('chapter-poster-box');
        if(targetEl){
            html2canvas(targetEl,{
                backgroundColor: "#ffffff",
                useCORS: true, // 允许图片跨域
                allowTaint: true, // 在渲染前测试图片
                imageTimeout: 0, // 加载延时
                scale:3,
            }).then(res=>{
                let img = res.toDataURL("image/png");
                posterImgBase64.value=img
                showChapterItemPoster.value=true
            })
        }
    })
}

</script>

<template>
    <div class="report-chapterlist-page" v-if="reportInfo">
        <van-cell title="基础信息" is-link @click="showBaseInfoPop=true"/>
        <div class="chapter-list-wrap">
            <div class="top-box">
                <span class="list-lable">章节列表</span>
            </div>
            
            <ul class="chapter-list">
                <li class="item" v-for="item in chapterList" :key="item.ReportChapterId" @click="goChapterDetail(item)">
                    <div class="img-box">
                        <img :src="item.TypeEditImg" alt="">
                        <span>{{item.TypeName}}</span>
                    </div>
                    <div class="content">
                        <div class="title">{{item.TypeName}}</div>
                        <div class="tag-text" v-if="item.Trend">#{{item.Trend}}</div>
                        <div class="time">{{item.ModifyTime}}</div>
                        <!-- 上传了音频icon -->
                        <img class="audio-icon" src="@/assets/imgs/report/icon_audio.png" alt="" v-if="reportInfo.ClassifyNameFirst=='周报'&&item.VideoUrl&&item.VideoKind==1">
                        <div :class="['status',item.PublishState!=1&&'status-success']">{{item.PublishState==1?'未发布':'已发布'}}</div>
                        <img @click.stop="handleShowTrendTag(item)" class="icon icon-tag" src="@/assets/imgs/report/icon_tag.png" alt="">
                        <img v-if="item.PublishState==2" @click.stop="handleShowPoster(item)" class="icon icon-wx" src="@/assets/imgs/report/icon_wx.png" alt="">
                    </div>
                </li>
            </ul>
        </div>

        <div class="bot-btns">
            <van-button class="bot-btn" type="default" @click="handlePublishValid">发布</van-button>
            <van-button class="bot-btn" type="primary" @click="handleSaveReportInfo">保存</van-button>
        </div>
    </div>

    <!-- 基础信息 -->
    <van-popup 
        v-model:show="showBaseInfoPop" 
        position="bottom"
        :style="{height:'100%'}"
    >
        <EditBaseInfo 
            v-if="showBaseInfoPop" 
            :defaultData="reportInfo"
            @close="showBaseInfoPop=false"
            @confirm="handleUpdateBaseInfo"
        />
    </van-popup>

    <!-- 选择标签 -->
    <van-popup 
        v-model:show="showTagPop" 
        round 
        :position="width>650?'center':'bottom'"
        :style="width>650?{ width: '400px'}:''"
    >
        <van-picker
            :title="isEditTag?'编辑标签':'添加标签'"
            v-model="temTrendTagData.tagVal"
            :columns="tagOpts"
            :columns-field-names="customFieldName"
            @cancel="showTagPop = false"
            @confirm="handleConfirmEditTrendTag"
        />
    </van-popup>

    <!-- 海报 -->
    <van-popup 
        v-model:show="showChapterItemPoster" 
        round
    >
        <img class="chapter-poster-img" :src="posterImgBase64" alt="">
    </van-popup>

    <!-- 海报dom模块 -->
        <div v-if="chapterItemPosterInfo" class="select-text-disabled chapter-poster-box" id="chapter-poster-box">
            <img class="bg" :src="chapterItemPosterInfo.TypeEditImg" alt="">
            <h2 class="title">【第{{reportInfo.Stage}}期|{{reportInfo.ClassifyNameFirst}}|{{chapterItemPosterInfo.TypeName}}】{{chapterItemPosterInfo.Title}}</h2>
            <img class="code-img" :src="chapterItemPosterInfo.QRCodeImg" alt="">
            <p class="tips">长按保存图片，发送给好友</p>
        </div>
</template>

<style lang="scss" scoped>
.report-chapterlist-page{
    height: 100dvh;
    min-height: 95vh;
    display: flex;
    flex-direction: column;
    padding-bottom: 130px;
    .bot-btns{
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 99;
        padding: 20px 0;
        display: flex;
        justify-content: center;
        .bot-btn{
            width: 315px;
            margin: 0 10px;
        }
    }
}

.chapter-list-wrap{
    flex: 1;
    overflow-y: auto;
    padding: 60px $page-padding;
    .list-lable{
        display: block;
        font-size: 32px;
        margin-bottom: 30px;
    }

}
.chapter-list{
    .item{
        display: flex;
        padding:20px;
        border: 1px solid $border-color;
        border-radius: 8px;
        margin-bottom: 20px;
        .img-box{
            position: relative;
            width: 160px;
            height: 160px;
            overflow: hidden;
            border-radius: 8px;
            img{
                width: 100%;
                height: 100%;
            }
            span{
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%,-50%);
                color: #fff;
                font-size: 24px;
                display: inline-block;
                width: 80%;
                text-align: center;
            }
        }
        .content{
            padding-left: 20px;
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            position: relative;
            .title{
                font-size: 32px;
                font-weight: 600;
                padding-right: 160px;
            }
            .time{
                color: $font-grey;
            }
            
            .audio-icon{
                position: absolute;
                width: 36px;
                height: 36px;
                top: 0;
                right: 100px;
            }

            .status{
                position: absolute;
                top: 0;
                right: 0;
                color: $font-grey_999;
                &.status-success{
                    color: $font-success;
                }
            }

            .icon{
                width: 70px;
                height: 70px;
                position: absolute;
                bottom: 0;
            }
            .icon-tag{
                right: 0;
            }
            .icon-wx{
                right: 108px;
            }

        }
    }
}

.chapter-poster-img{
    display: block;
    width: 300PX;
    border-radius: 6PX;
    padding: 10PX;
}
.chapter-poster-box{
    position: fixed;
    z-index: -100;
    width: 300PX;
    border-radius: 6PX;
    padding: 10PX;
    background-color: #fff;
    .bg{
        width: 280PX;
        height: 280PX;
        display: block;
    }
    .title{
        font-size: 16PX;
    }
    .code-img{
        width: 140PX;
        height: 140PX;
        display: block;
    }
    .tips{
        color: $font-grey;
        font-size: 14PX;
        margin-top: 5PX;
    }
}

.report-baseinfo-wrap{
    height: 100%;
    position: relative;
    background-color: $page-bg-grey;
}

@media screen and (min-width:$media-width){
    .report-chapterlist-page{
        padding-bottom: 80px;
        .bot-btns{
            padding: 10px 0;
        }
    }
    .chapter-list-wrap{
        border: none;
        padding: var(--van-padding-md);
        .list-lable{
            font-size: 16px;
            margin-bottom: 15px;
        }
        .top-box{
            margin-bottom: 15px;
            .btn{
                width: 35px;
                height: 35px;
            }
        }
        .list-lable{
            font-size: 16px;
        }
    }
    .chapter-list{
        .item{
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 10px;
            .img-box{
                width: 80px;
                height: 80px;
                border-radius: 4px;
                span{
                    font-size: 12px;
                }
            }
            .content{
                padding-left: 10px;
                .title{
                    font-size: 16px;
                    padding-right: 100px;
                }
                .audio-icon{
                    width: 18px;
                    height: 18px;
                    right: 60px;
                }

                .icon{
                    width: 35px;
                    height: 35px;
                }
                .icon-wx{
                    right: 54px;
                }
            }
        }
    }
}
</style>