import PhotoSwipe from "photoswipe";
import photoswipeDefault from "photoswipe/dist/photoswipe-ui-default";
import {Tpl} from "./imgViewTpl"
import {fetch} from '@core/component//httpClient';
import Message from '@core/component/message';
import domain from "../../../util/domain";
const ImageView = (($) => {
    const DefaultConfig = {
            imgList: [], 
            index: 0,
            node: null, 
        };
    class ImageView {
        imageDataList = [
        ];
        treeDataMap = new Map();
        listen = null; 
        constructor(config) {
            this.config = this._getConfig(config);
            if (!this.config.imgList) {
                console.log("没有传入要展示的图片列表!");
                return;
            }
            
            if(!this.config.node) {
                $(document.body).append($(Tpl));
            } 
            setTimeout(()=>{
                this._init(); 
                this._bindEventOnce();
            });
        }
        _init() {
            
            if(!this.config.node) {
                this.config.node = $('.pswp');
            } 
            let pswpElement = this.config.node;
            
            let items = [];
            for(let img of this.imageDataList) {
                items.push({
                    src: img.url,
                    w: img.width,
                    h: img.height,
                });
            }
            if(items.length <= 0) return;
            let options = {
                index: this.config.index, 
                shareEl: false,
                loop: false,
                closeOnScroll: false,
                bgOpacity: 0.7,
            };
            this.viewe = new PhotoSwipe( pswpElement[0], photoswipeDefault, items, options);
            this.viewe.init();
            this.listen = this.viewe.listen;
            this._setImageInfo();
            this._bindEvent();
        }
        
        _getConfig(config) {
            if(!!config.treeData) {
                if(this.treeDataMap.size !== config.treeData.length) {
                    for (let d of config.treeData) {
                        let id = d.cateId || d.id;
                        this.treeDataMap.set(id, {
                            name: d.cateName || d.name,
                            id: id,
                            pId: d.pId,
                            rootType: d.rootType,
                        });
                    }
                }
            }
            this.imageDataList = [];
            if(!!config.imgList) {
                for(let img of config.imgList) {
                    if(!img.imgUrl) continue;
                    let cate = this.treeDataMap.get(img.cateId);
                    this.imageDataList.push({
                        id: img.imgId,
                        url: img.imgUrl,
                        width: img.imgWidth,
                        height: img.imgHeight,
                        name: img.imgName, 
                        updateTime: img.updateTime, 
                        size: img.imgSize,
                        cateData: cate,
                    });
                }
            }
            return $.extend(true, this.config, DefaultConfig, config);
        }
        
        _bindEvent() {
            if(!this.viewe){
                return;
            }
            this.viewe.listen('afterChange', ()=>{
                this._setImageInfo();
            });
        }
        _bindEventOnce() {
            if(!this.viewe){
                return;
            }
            
            this.config.node.find('.imv__bottom-bar').on('click', '.imv__bottom-original', (e)=>{
                let index = this.viewe.getCurrentIndex(); 
                let data = this.imageDataList[index];
                if(data.url) {
                    window.open(data.url);
                }
            });
            this.config.node.find('.imv__bottom-bar').on('click', 'li', (event)=>{
                let index = this.viewe.getCurrentIndex(); 
                let data = this.imageDataList[index];
                let operateType = $(event.currentTarget).data('type');
                if(!operateType) return;
                let getPicInfo = {
                    id: data.id,
                    name: data.name,
                    width: data.width,
                    height: data.height,
                    url: data.url
                };
                if((/slice|remove/gi).test(operateType)) {
                    this.close();
                }
                if(this.config.picOperateClickCallBack) {
                    this.config.picOperateClickCallBack(operateType, getPicInfo);
                }
            });
        }
        _copy(text) {
            $('body').data('copyUrl', text);  
            try {
                if (document.execCommand('copy', false, null)) {
                    Message.success("复制成功，请用ctrl＋V后粘贴即可");
                } else {
                    this._copyPicDialog(text);
                }
            } catch (err) {
                this._copyPicDialog(text);
            }
        }
        
        _copyPicDialog(url) {
            Message.warn("该浏览器不支持复制，请手动选取复制, 地址如下:</br>" + url, 7000);
        }
        onPicOperateClick(fun) {
            if(!!fun) {
                this.config.picOperateClickCallBack = fun;
            }
        }
        
        _setImageInfo() {
            let index = this.viewe.getCurrentIndex(); 
            let imgData = this.imageDataList[index];
            this.config.node.find('.imv__image-info-name').html(imgData.name);
            fetch({
                url: `${domain.material}/shopImg/getImgRet`,
                method: 'post',
                dataType: 'json',
                contentType:"application/json;charset=utf-8",
                xhrFields: {
                    withCredentials: true
                },
                data: JSON.stringify({
                    imgId: imgData.id,
                    cateId: imgData.cateData.id
                })
            }).then((data) => {
                if(data.data.result.length){
                    let info = `<span>大小：${(imgData.size / 1024).toFixed(2)}KB</span><span>尺寸：${imgData.width}*${imgData.height}</span><span>上传时间：${data.data.result[0].created}</span><span>所属文件夹：${$('.J_sourceCrumbs span').last().text()}</span>`;
                    $('.imv__image-info .imv__image-info-detail').html(info);
                }
            });
        }
        
        reset(config) {
            this.config = this._getConfig(config);
            this._init();
        }
        
        dispose() {
            this.close();
            delete this;
        }
        close() {
            this.viewe.close();
        }
    }
    return ImageView;
})($);
export default ImageView;