<template>
    <div class="pdfpreview" :class="isOpen?'drawer' : ''">
        <span :class="['toggle-left',isOpen?'toggle-arraw' : '']" @click="simgs('0')"><font-awesome-icon icon="angle-double-right" /></span>
        <div class='pageitem-group'>
            <div class='pageitem' v-for="(item,index) in imgArr" :key="index" :name="index+1" :class="{'selectPage':slide==index+1}">
                <img :src="item" alt="" @click="setCarousel(index)"><div class='pagebadge'>{{index+1}}</div>
            </div>
        </div>
        <!-- <div class="q-pa-md">
            <q-carousel animated v-model="slide" ref="carousel" thumbnails infinite :class="isOpen?'drawer' : ''">
                <q-carousel-slide v-for="(item,index) in imgArr" :key="index" :name="index+1" :img-src="item" style="display:none"> -->
                    <!--<q-carousel-slide v-for="(item,index) in imgArr" v-if="index >=1" :name="index" style="display:none" :img-src="item">-->
                    <!--<p v-if="boardImg['page'+(slide)+'']">{{boardImg['page'+(slide)+'']['num']}}</p>
    <p v-if="boardImg['page'+(slide)+'']">{{boardImg['page'+(slide)+'']['src']}}</p>
    <img v-if="boardImg" :src="boardImg['page'+(slide-1)+'']['src']" alt="">
    <img v-if="boardImg" :src="boardImg['page1']" alt="">
    <p v-if="boardImg">{{boardImg['page'+(index+1)+'']}}</p>
    <img v-if="boardImg['page'+(slide)+'']" :src="boardImg['page'+(slide)+'']['src']" alt="">-->
                <!-- </q-carousel-slide>
            </q-carousel>
        </div> -->
        <div class='btn-group'>
            <div @click='addNew()' class='delpage-btn'><svg-icon icon-class="new-page" class="stroke-icon" /> </div>
            <div @click='deleteSelectPage()' class='delpage-btn'><svg-icon icon-class="Close"  class="fill-icon" /> </div>
        </div>
    </div>
</template>
<script>
    import PDFJS from 'pdfjs-dist';
    const width = window.innerWidth * 0.73;
    const height = window.innerHeight * 0.81;
    export default {
        props: {
            url: {
                type: String,
                required: true
            },
            manualRender: {
                type: Boolean,
                default: false
            },
            renderPages: { // 前后各预渲染多少页
                type: Number,
                default: 5
            },
            showPageLine: {
                type: Boolean,
                default: true
            }
        },
        data() {
            return {
                isOpen: true,
                value1: 0,
                slide: 1,
                imgArr: [],
                imgArr2: [],
                pdfDoc: null,
                pageNum: 1,
                pageRendering: false,
                pageNumPending: null,
                scale: 0.9,
                pages: 0,
                currentPage: 0,
                pageHeight: 0,
                renderList: [], // 渲染的页码数组
                timerIndex: 0,
                height: height,
                boardImg: {},
                startNew: 1,
                allPages: this.$store.state.totalpage,
                whiteBG: require('../assets/img/white.jpg'),
                visible: true,
                showSimulatedReturnData: false,
                fileType: '',
            }
        },
        methods: {
             addNew() {
                this.$store.state.addNew = true
            },
            deleteSelectPage(){
                console.log(this.slide)
                this.$store.state.deletePage=true;
                this.$store.state.deletePageNum=this.slide;
                //之後處理都送到Board.vue那支去處理
            },
            setCarousel(index){
                this.slide=index+1
            },
            pdf(pageNow) {
                var that = this
                that.imgArr = []
                //var url = 'https://teammodelstorage.blob.core.chinacloudapi.cn/teammodelos/wordfiles/IES%20Kubernetes%20on%20Aliyun.pdf'
                var url = this.$store.state.uploadUrl
                console.log(url, '新的url地址')
                var pages = []; var heights = []; var width = 0; var height = 0; var currentPage = pageNow
                var scale = 1.5
                function draw() {
                    var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d')
                    canvas.width = window.innerWidth
                    canvas.height = window.innerHeight
                    for (var i = 0; i < pages.length; i++) { ctx.putImageData(pages[i], 0, heights[i]) }
                    // document.body.appendChild(canvas);
                }
                PDFJS.disableWorker = true // due to CORS
                if (!url) {
                    that.imgArr[0] = that.whiteBG
                    that.allPages = that.$store.state.imgArr.length
                    var newArr = []; var newArr2 = []
                    for (var i = 0; i < that.imgArr.length; i++) {
                        newArr = newArr.concat(that.imgArr[i])
                        newArr2 = newArr.concat(that.imgArr[i])
                    }
                    that.$store.state.totalpage = that.allPages
                    that.$store.state.imgArr = newArr// 缩略图数组
                    that.$store.state.imgArrOld = newArr2// 缩略图数组
                    that.$parent.$parent.pen(0)// 拿到数组后渲染第一页
                    that.init()
                    return
                }
                //this.$emit('PdfLoding',1)
                that.$parent.$parent.beginPdfshowLoading(1)
                PDFJS.getDocument(url).then(function (pdf) {
                    console.log(pdf.numPages, '页数')
                    if (pdf.numPages > 100) {
                        console.log('超过100页了 不渲染')
                        that.pdfuploaderror()
                        return
                    } else {
                        getPage()
                        function getPage() {
                            pdf.getPage(currentPage).then(function (page) {
                                var viewport = page.getViewport(scale)
                                var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d')
                                var renderContext = { canvasContext: ctx, viewport: viewport }
                                canvas.height = viewport.height
                                canvas.width = viewport.width
                                page.render(renderContext).then(function () {
                                    pages.push(ctx.getImageData(0, 0, canvas.width, canvas.height))
                                    heights.push(height)
                                    height += canvas.height
                                    that.imgArr.push(canvas.toDataURL('images/jpeg',0.9))
                                    //if (width < canvas.width) width = canvas.width
                                    if (currentPage < pdf.numPages) {
                                        currentPage++
                                        getPage()
                                    } else {
                                        draw()// 页数加载完成后渲染页面
                                        that.allPages = pdf.numPages
                                        that.startNew = currentPage
                                        var newArr = []; var newArr2 = []
                                        for (var i = 0; i < that.imgArr.length; i++) {
                                            console.log(i, '缩略图的页数')
                                            console.log(that.imgArr[i], '缩略图的内容')
                                            newArr = newArr.concat(that.imgArr[i])
                                            newArr2 = newArr.concat(that.imgArr[i])
                                        }
                                        that.$store.state.totalpage = that.allPages
                                        that.$store.state.imgArr = newArr// 缩略图数组
                                        that.$store.state.imgArrOld = newArr2// 缩略图数组
                                        let ImgArrs = that.$store.state.imgArr.length
                                        let imageData = []
                                        let f = async function () {
                                            for (let i = 0; i < ImgArrs; i++) {
                                                that.$parent.$parent.PdfshowLoading(1, i + 1)
                                                await that.$parent.$parent.pen(i).then(res => {
                                                    console.log(i, 'PDF加载的页数')
                                                    that.$parent.$parent.LoadingPage(i)
                                                    if (res === 200) {
                                                        let stageImg = that.$parent.$parent.stage.toDataURL()// 画布截图
                                                        //that.$store.state.imgArr[i] = stageImg
                                                        imageData = imageData.concat(stageImg)
                                                    }
                                                });
                                            }
                                            that.imgArr = imageData
                                            that.$store.state.imgArr = imageData
                                            console.log(imageData, '打印查看内容')
                                            that.init()
                                            that.pdfGetidtpe()
                                        }
                                        f()
                                    }
                                })
                            })
                        }
                    }
                })
            },
            //缩略图
            simgs(status) {
                this.fileType = localStorage.getItem('fileType')
                if (status === '0') {
                    this.isOpen = !this.isOpen
                    this.allPages = this.$store.state.totalpage
                    if (this.isOpen === false && this.fileType === 'ppt') { this.inspectLitimg() };
                }
                this.imgArr = this.$store.state.imgArr
                this.showTextLoading();
            },
            uploadImgs(images) { // 获取醍摩豆TOKEN
                let that = this
                that.$api.uploadBase64(
                    {
                        'params': images,
                        'method': 'api/file/uploadBase64'
                    }
                ).then(res => {
                    console.log(res)
                }).catch(res => {
                    console.log(res)
                })
            },
            init() {
                if (localStorage.getItem('boardImg')) {
                    this.boardImg = JSON.parse(localStorage.getItem('boardImg'))
                }
                this.$store.state.carousel = this.$refs.carousel
                this.imgArr = this.$store.state.imgArr
                localStorage.removeItem('msgBody')
                localStorage.removeItem('stageInfo')
                this.$emit('PdfLoding', 0)
                this.$parent.$parent.pen(0)
            },
            pdfuploaderror() {
                this.$Message.error('页数超过100，请重新选择上传PDF');
                this.$emit('PdfLoding', 0)
                this.$parent.$parent.modalUpload = true
            },
            //loading
            showTextLoading() {
                this.visible = true
                //this.showSimulatedReturnData = false
                setTimeout(() => {
                    this.visible = false
                    //this.showSimulatedReturnData = true
                }, 9000)
            },
            //处理PDF生成id和typeId
            pdfGetidtpe() {
                this.imgArr.idArr = []
                for (var i = 0; i < this.imgArr.length; i++) {
                    let idTypes = {
                        "pageid": this.$parent.$parent.genID(),
                        "pagetype": "Quiz",
                        "page": i
                    }
                    this.imgArr.idArr.push(idTypes)
                }
                this.$store.state.imgArr = this.imgArr
            },
            //检查缩略图
            async inspectLitimg() {
                var litimaArr = this.$store.state.imgArr
                var totalPages = this.$store.state.totalpage
                var cycleNum = this.$store.state.AfterParsing
                return new Promise(async (r, j) => {
                    for (var i = 0; i < litimaArr.length; i++) {
                        console.log(litimaArr[i], i, '循环的内容')
                        if (litimaArr[i] == undefined || litimaArr[i] == "") {
                            console.log(i,'进入到判断方法内')
                            let ss = await this.$parent.$parent.initCanvas(i+1, 'readyRenderBox', 'preparative')
                        }
                    }
                })
            }
        },
        created() {
            //this.pdf(1)
        },
        mounted() {
            // if(!JSON.parse(localStorage.getItem('PDFArr'))){
            //this.pdf(1)
            // }
            if (localStorage.getItem('boardImg')) {
                this.boardImg = JSON.parse(localStorage.getItem('boardImg'))
            }
            this.$store.state.carousel = this.$refs.carousel
        },
        computed: {
            watchUrl() {
                return this.$store.state.uploadUrl
            },
            watchImgArr() {
                return this.$store.state.imgArr
            },
            watchSlide() {
                return this.slide
            },
            watchCarouselSlide() { // 新增
                return this.$store.state.carouselSlide
            }
        },
        watch: {
            watchUrl(e) {
                if (e) {
                    this.pdf(1)
                }
            },
            watchImgArr(e) {
                console.log(e,'监听到缩略图发生变化')
                if (e) {
                    this.imgArr = this.$store.state.imgArr
                    this.allPages = this.$store.state.imgArr.length
                    //this.pdfGetidtpe()
                }
            },
            watchSlide(e) {
                if (e) {
                    this.$store.state.oldSlide = this.$store.state.carouselSlide
                    this.$store.state.carouselSlide = this.slide
                    this.boardImg = JSON.parse(localStorage.getItem('boardImg'))
                }
            },
            //监听当前页数
            watchCarouselSlide(e) {
                if (e) {
                    this.$store.state.oldSlide = this.$store.state.carouselSlide
                    this.slide = this.$store.state.carouselSlide
                    localStorage.setItem('slide', this.slide)
                }
            },
        },
        beforeDestroy() {
            if (this.timer !== void 0) {
                clearTimeout(this.timer)
                this.$q.loading.hide()
            }
        }
    }
</script>
<style lang='less'>
@import '../assets/css/pdfPreview.less';
</style>
<style>
    .foot {
        position: fixed;
        top: 10px;
        left: 10px;
    }

    .q-pa-md {
        position: absolute;
        padding: 0 !important;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
    }

    .q-carousel {
        height: 100% !important;
    }

    .q-carousel__slide {
        background-repeat: no-repeat;
        background-size: contain !important;
        padding: 0 !important;
    }

    .q-carousel__control {
        position: fixed;
        z-index: 99;
    }

    .q-carousel__navigation {
        position: fixed !important;
        width: 210px;
        top: 40px;
        left: 0;
        background: #f9fafb;
        padding: 10px !important;
        transition: 0.5s;
        overflow: auto;
    }

    .drawer .q-carousel__navigation {
        left: -210px;
    }

    .q-carousel__navigation img {
        display: block !important;
        width: 100% !important;
        height: auto !important;
        margin: 12px 0 !important;
        min-height: 100px;
        max-height:100px;
        border-color: #ddd !important;
        background: #fff;
    }

        .q-carousel__navigation img.q-carousel__thumbnail--active {
            border-color: #ff9800 !important;
            max-height:100px;
        }

    .q-carousel__navigation-inner.flex {
        display: block !important;
    }

    .pages {
        position: fixed;
        width: 210px;
        height: 40px;
        line-height: 40px;
        top: 0;
        left: 0;
        background: #dfe4e8;
        color: #757f83;
        font-size: 14px;
        padding: 0 10px;
        transition: 0.5s;
        z-index: 999;
    }

    .drawer.pdfpreview {
        left: -280px;
    }

    .imgbox {
        padding: 15px;
    }
</style>
