<template>
    <!-- 预览图片弹窗 -->
    <div class="viewall_img" id="viewall_img">
        <el-dialog id="viewall_img_dialog" :append-to-body="appendBody" :title="`${title}（${imgListlognum+1}/${imgList.length}）`" width="840px" top="6vh"
                   :visible.sync="flag"  :modal="modal" ref="sadsdada" :before-close="close" v-bind="$attrs">
            <div class="viewall_img_count"></div>
           <div class="viewall_img_header" v-if="imgList.length">
                <div v-if="imgList[imgListlognum]&&imgList[imgListlognum].type!='video'" @click="sliderFlag=!sliderFlag"> <i class="el-icon-zoom-in"></i> </div>
                <div v-if="imgList[imgListlognum]&&imgList[imgListlognum].type!='video'" @click.stop="rotatess"> <i class="el-icon-refresh-right"></i> </div>
                <div v-if="imgList[imgListlognum]&&imgList[imgListlognum].type!='video'&&!deleteFlag" @click="deleteImg"> <i class="el-icon-delete"></i> </div>
                <div @click="downs(imgList[imgListlognum],'photo')"> <i class="el-icon-download"></i> </div>
                <el-tooltip class="item" effect="dark" content="在新窗口查看" placement="top-start">
                      <div v-if="imgList[imgListlognum]&&imgList[imgListlognum].type=='pdf'" @click="perviewPdf"> <i class="el-icon-reading"></i> </div>
                </el-tooltip>

                <div v-if="sliderFlag" class="imgSlider">
                    <el-slider v-model="sliderValue" :max="300"></el-slider>
                </div>
            </div>
            <div class="img_body">
                <el-carousel indicator-position="none" :initial-index="showIndex" :loop="true" :autoplay="false" :arrow="imgList.length<2?'hover':'always'" ref="viewall_img_dialog" @change="carouselChange2">
                    <el-carousel-item v-for="(i,index) in imgList" :key="index">
                        <div class="movediv">
							<video ref="videoControl" :src="i.url" controls="controls" height="100%" width="540px" :preload="true"
							     v-if="imgListlognum==index&&i.type=='video'"></video>
                      <iframe ref="pdfControl" :src="i.url" height="100%" width="540px"
                           v-if="imgListlognum==index&&i.type=='pdf'"></iframe>
                           <img :src="i.url + '&getOriginFile=true'" style="cursor:pointer" @mousedown="move"
                                 v-else
                                 :style="{transform:transform}" alt="">
					            </div>
                    </el-carousel-item>
                </el-carousel>
            </div>
            <div slot="footer" class="viewall_img_footer">
                <div class="viewall_img_Swiper">
                    <swiper ref="mySwiper" class="mySwiper" :options="swiperOptions">
                        <swiper-slide v-for="(i,index2) in imgList" :key="index2">
                          <video v-if="i.type=='video'" height="100%" width="100%" :class="[index2==imgListlognum?'active':'']" @click="imgClick(index2)" :src="i.url + '&getOriginFile=true'" alt=""></video>
                          <img v-else-if="i.type=='pdf'" :class="[index2==imgListlognum?'active':'']" style="object-fit: contain;" @click="imgClick(index2)" src="../../images/icon_pdf.png" alt=""></img>
                          <img v-else :class="[index2==imgListlognum?'active':'']" @click="imgClick(index2)" :src="i.url" alt=""></img>
                        </swiper-slide>
                        <div class="swiper-pagination" slot="pagination"></div>
                    </swiper>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {
        Swiper,
        SwiperSlide,
        directive
    } from 'vue-awesome-swiper'
    import '../../style/swiper.css'
    export default {
		name:'enoPreviewPictures',
        components: {
            Swiper,
            SwiperSlide
        },
        props: {
            flag: Boolean,
            imgList: {
                type: Array,
                default: ()=>{
                  return []
                }
            },
            deleteFlag:{
                type: Boolean,
                default: false
            },
            disabled: {
                type: Boolean,
                default: false
            },
            title:{
                type: String,
                default: '附件查看'
            },
            appendBody:{
                type: Boolean,
                default: false
            },
			modal:{
                type: Boolean,
                default: true
            },
			showIndex:{
				type: Number,
				default: 0
			}
        },
        data() {
            return {
                imgListlognum: 0,
                imgListlogold: null,
                imgListall: false,
                rotate: 0,
                showDialog:this.flag,
                swiperOptions: {
                    slidesPerView: 3,
                    slidesPerGroup: 1,
                    // centeredSlides: true,
                },
                sliderValue: 0,
                sliderFlag: false,
                transformRotate:'',
                transformscale:''

                //
            };
        },
        computed: {
            swiper() {
                return this.$refs.mySwiper.$swiper
            },
            transform(){
              let rotateStyle = ``;
              let scaleStyle = ``;
              if(this.rotate){
                rotateStyle = `rotate(${this.rotate * 90}deg)`;
              }
              if(this.sliderValue){
                scaleStyle = `scale(${this.sliderValue==0?1:1+this.sliderValue/100})`
              }
              return `${rotateStyle} ${scaleStyle}`
            }
        },
        watch: {
			flag(val){
				if(this.showIndex > 0){
					this.setActiveItem(this.showIndex)
				}
			}

        },
        created() {

        },
        mounted() {
			if(this.showIndex > 0){
				this.imgListlognum = this.showIndex;
			}
        },
        methods: {
			perviewPdf(){
				window.open(this.imgList[this.imgListlognum].url, '_blank')
			},
            move(e) {
                if (this.sliderValue != 0) {
                    event.preventDefault();
                    let odiv = e.target; // 获取目标元素
                    //计算出鼠标相对点击元素的位置,e.clientX获取的是鼠标的位置，OffsetLeft是元素相对于外层元素的位置
                    let x = e.clientX - odiv.offsetLeft;
                    let y = e.clientY - odiv.offsetTop;
                    console.log(odiv.offsetLeft, odiv.offsetTop)
                    document.onmousemove = (e) => {
                        // 获取拖拽元素的位置
                        let left = e.clientX - x;
                        let top = e.clientY - y;
                        this.positionX = left;
                        this.positionY = top;
                        //console.log(document.documentElement.clientHeight,odiv.offsetHeight)
                        // 把拖拽元素 放到 当前的位置
                        // if (left <= 0) {
                        //     // left = 0;
                        // } else if (left >= document.documentElement.clientWidth - odiv.offsetWidth) {
                        //     //document.documentElement.clientWidth 屏幕的可视宽度
                        //     left = document.documentElement.clientWidth - odiv.offsetWidth;
                        // }

                        // if (top <= 0) {
                        //     // top = 0;
                        // } else if (top >= document.documentElement.clientHeight - odiv.offsetHeight) {
                        //     // document.documentElement.clientHeight 屏幕的可视高度
                        //     top = document.documentElement.clientHeight - odiv.offsetHeight

                        // }
                        odiv.style.left = left + "px";
                        odiv.style.top = top + "px";

                    }
                    // 为了防止 火狐浏览器 拖拽阴影问题
                    document.onmouseup = (e) => {
                        document.onmousemove = null;
                        document.onmouseup = null;
                    }
                }

            },
            imgClick(e) {
                if (e === this.imgListlognum) return;
                this.imgListlognum = e;
                this.setActiveItem(e);
            },
            setActiveItem(index) {
                this.sliderValue = 0;
                this.sliderFlag = false;
                this.imgListlognum = index;
                let i = index.toString();
                this.$refs.viewall_img_dialog.setActiveItem(i);
            },
            carouselChange2(e) {
                this.imgListlognum = e;
                this.sliderValue = 0;
                this.sliderFlag = false;
                this.swiper.slideTo(e, 1000, false);
            },
            deleteImg() {
                this.$emit("deleteImg", this.imgListlognum);
            },
            close() {
                this.sliderFlag = false;
                this.sliderValue = 0;
				if(this.$refs.videoControl){
					this.$refs.videoControl.forEach(res=>{
						res.pause();
						res.currentTime = 0;
					})
				}

                this.$emit("close");
                // this.setActiveItem(0)
            },
            getUrlBase64(url) {
                return new Promise((resolve, reject) => {
                    try {
                        let canvas = document.createElement("canvas");
                        let ctx = canvas.getContext("2d");
                        let img = new Image();
                        img.crossOrigin = "anonymous"; //允许跨域
                        img.src = url;
                        img.onload = function() {
                            (canvas.height = img.height),
                            (canvas.width = img.width);
                            ctx.drawImage(img, 0, 0, img.width, img.height);
                            let dataURL = canvas.toDataURL("image/png");
                            canvas = null;
                            resolve(dataURL);
                        };
                    } catch (err) {
                        reject(err)
                    }

                })
            },
            downs(url) {
                if(url.type == 'pdf'){
                    this.$eno.downFileUrl(this, item.id);
				}
				else if(url.type == 'video'){
					fetch(url.url).then(res => res.blob()).then(blob => {
						 const a = document.createElement('a');
						  document.body.appendChild(a)
						  a.style.display = 'none'
						  const link = window.URL.createObjectURL(blob);
						  a.href = link;
						  a.download = url.name || '视频.mp4';
						  a.click();
						  document.body.removeChild(a)
						  window.URL.revokeObjectURL(link);
					});
				}
				else{
					this.getUrlBase64(`${url.url}&getOriginFile=true`)
					    .then(base64 => {
					        let link = document.createElement("a");
					        link.href = base64;
					        link.target = "_blank";
					        link.download = url.name || "qrCode.png";
					        link.click();
					    })
					    .catch(err => {
					        console.log(err);
					    });
				}

            },
            rotatess() {
                // let e = this.$refs.viewall_img_dialog.$children[this.imgListlognum]
                //     ._vnode.children[1].elm.lastChild;
                // console.log(this.$refs.viewall_img_dialog.$children[this.imgListlognum]._vnode.children[1].elm.lastChild)
                this.transformRotate = `rotate(${this.rotate * 90}deg)`;
                // if (this.rotate == 2) e.style.transform = "none";
                if (this.rotate == 4) {
                    this.rotate = 0;
                }
                this.rotate = this.rotate + 1;
            }
        }
    };
</script>

<style lang="less">
    /*el-carousel__arrow*/
    #viewall_img{
        .el-carousel__arrow{
            width: 36px!important;
            height: 36px!important;
        }
    }
</style>
