$(document).ready(function() {
    var loadIndex = null;

	new WOW({
		mobile: false,
		animateClass: 'animate__animated',
	}).init();

	setTimeout(function() {
		$('.prelodaer-wrap').fadeOut('slow');
	}, 4500);

	//Ajax Form Send START
	$('#contact-form').on('submit', function() {
		var th = $(this);
		$.ajax({
			type: 'POST',
			url: 'mail.php',
			data: th.serialize(),
			success: function() {
				th.trigger('reset');
				$('.input-field').removeClass('is-active');
				$.magnificPopup.open({
					items: {
						src: '<div class="form-alert"><p>Your application has been successfully sent. <br> Expect a call!</p></div>',
						type: 'inline'
					}
				});
			},
			error: function() {
				th.trigger('reset');
				$('.input-field').removeClass('is-active');
				$.magnificPopup.open({
					items: {
						src: '<div class="form-alert"><p>An error occurred, please try again</p></div>',
						type: 'inline'
					}
				});
			}
		});
		return false;
	});
	//Ajax Form Send END

	// Banner START
	const swiperBanner = new Swiper('.swiper-banner', {
		speed: 800,
		spaceBetween: 100,
		effect: 'fade',
			fadeEffect: {
				crossFade: true
		},
		navigation: {
			nextEl: '.swiper-banner .swiper-button-next',
			prevEl: '.swiper-banner .swiper-button-prev',
		},
		scrollbar: {
			el: '.swiper-banner .swiper-scrollbar',
			enabled: true,
			draggable: true
		},
	});
	// Banner END



	// Menu START
	$('body').on('click', '.hamburger-button', function(e) {
		e.preventDefault();

            hamburger_click = 1;
            hamburgerButton = $('.hamburger-button');
            hamburgerMenuWrap = $('.menu-wrap');
            hamburgerMenuItem = $('.menu-nav');

            hamburgerMenuWrap.addClass('menu-active');
            hamburgerMenuItem.addClass('menu-item-active');
            menuOverlay = $('.menu-overlay');

            if ( window.innerWidth <= 768) {
                $(".content").css("padding-left","257px");
            } else {
                $(".content").css("padding-left","264px");
            }

	});

    /*
	$('.menu-close__wrap').on('mouseup', function(e) {
		e.preventDefault();
		menuClose = $('.menu-close');
		hamburgerMenuWrap = $('.menu-wrap');
		hamburgerMenuItem = $('.menu-nav');
		menuOverlay = $('.menu-overlay');

		if (!hamburgerMenuWrap.is(e.target) && hamburgerMenuWrap.has(e.target).length === 0) {
			hamburgerMenuWrap.removeClass('menu-active');
			hamburgerMenuItem.removeClass('menu-item-active');
			menuOverlay.removeClass('menu-overlay__active');
		}

		menuClose.on('mousedown', function() {
			hamburgerMenuWrap.removeClass('menu-active');
			hamburgerMenuItem.removeClass('menu-item-active');
			menuOverlay.removeClass('menu-overlay__active');
		});

        $(".content").css("padding-left","80px");
	});
	*/
    $('.menu-close__wrap').on('click', function(e) {
        e.preventDefault();
        menuClose = $('.menu-close');
        hamburgerMenuWrap = $('.menu-wrap');
        hamburgerMenuItem = $('.menu-nav');
        menuOverlay = $('.menu-overlay');
        hamburgerMenuWrap.removeClass('menu-active');
        hamburgerMenuItem.removeClass('menu-item-active');
        menuOverlay.removeClass('menu-overlay__active');
        if ( window.innerWidth <= 768) {
            $(".content").css("padding-left","0px");
        } else {
            $(".content").css("padding-left","80px");
        }

    });
	// Menu END


	// Contact START
	$('.input-field input, textarea').on('input', function() {
		var inputValue = $(this).val();
		var inputpParent = $(this).parent('.input-field');
		if (inputValue.length > 0) {
		  inputpParent.addClass('is-active');
		} else {
		  inputpParent.removeClass('is-active');
		}
	  });
	// Contact END

	// Gallery Single page START
	$('.grid-single .grid-item img').parazoom({
		customCursorIcon: 'images/magnify.svg',
    	customCursorSize: '30px',
		transitionTime: '1s',
    	transitionTimeLeave: '1s'
	});

	var $grid = $('.grid-single').masonry({
		itemSelector: '.grid-single .grid-item',
		percentPosition: true,
		columnWidth: '.grid-single .grid-sizer'
	});
	$grid.imagesLoaded().progress( function() {
		$grid.masonry({
			gutter: 15
		});
	});

	$('.grid-single .grid-item a').magnificPopup({
		type:'image',
		removalDelay: 500,
		gallery: {
			enabled: true
		},
		callbacks: {
			beforeOpen: function() {
				this.st.image.markup = this.st.image.markup.replace('mfp-figure', 'mfp-figure mfp-with-anim');
				this.st.mainClass = this.st.el.attr('data-effect');
			}
		},
	});
	// Gallery Single page END

	// Album page START
	function albumMasonry() {
		var $gridAlbum = $('.grid-album').masonry({
			itemSelector: '.grid-album .grid-item',
			percentPosition: true,
			columnWidth: '.grid-album .grid-sizer'
		});
		$gridAlbum.imagesLoaded().progress( function() {
             if ( window.innerWidth <= 575) {
                $gridAlbum.masonry({
                    gutter: 38
                });
                return;
            } else if ( window.innerWidth <= 768) {
                 $gridAlbum.masonry({
                     gutter: 38
                 });
                 return;
             } else if ( window.innerWidth <= 992) {
                 $gridAlbum.masonry({
                     gutter: 35
                 });
                 return;
             } else if ( window.innerWidth <= 1656) {
                 $gridAlbum.masonry({
                     gutter: 35
                 });
                 return;
             }else   {
                 $gridAlbum.masonry({
                     gutter: 40
                 });
                 return;
             }
		});
	}
	albumMasonry();

	var bLazy = new Blazy();
	$('.album-tab a').on('click', function(e) {
		e.preventDefault();
		var href = $(this).attr('href');
		$('.album-tab a').removeClass('is-active');
		$(this).addClass('is-active');

		$('.grid-album').removeClass('is-active');
		$(href).addClass('is-active');

		$(href).addClass('animate__animated animate__slideInUp');
		$('.grid-album.is-active:not(' + href + ')').removeClass('animate__animated animate__slideInUp');

		albumMasonry();

        let column = $(this).attr('column');
        if (column == 'pdf' || column == 'video') {
            $(".download-all").hide();
        } else {
            $(".download-all").show();
        }
	});
	// Album page END


	// Settings START
	$('.settings-btn').on('click', function() {
		var settings = $('.settings-wrap');
		settings.toggleClass('is-active');
	});
	var savedColor = localStorage.getItem('boxColor');
	if (savedColor) {
		$(':root').css('--color-def', savedColor);
	}
	$('.settings-color-item').on('click', function() {
		var color = $(this).css('background-color');
		$('.settings-color-item').css('border-color', '#fff');
		$(this).css('border-color', color);
		$(':root').css('--color-def', color);
		localStorage.setItem('boxColor', color);
	});
	// Settings END

    // $('.menu-nav-item').first().click(function () {
    //     console.log('first11');
    //     $(this).parent().find('.menu-nav-son').stop(true, true).slideToggle(200);
    // });

    $('.menu-nav-item').each(function() {
        var firstLink = $(this).find('a').first();
        firstLink.on('click', function(event) {
            event.preventDefault(); // 阻止默认行为（如跳转）
            $(this).parent().find('.menu-nav-son').stop(true, true).slideToggle(200);
        });
    });


	// $('.menu-nav-son-li').hover(
	// 	function () {
	// 		// 显示当前 li 的子菜单
	// 		$(this).find('.menu-nav-son2').stop(true, true).slideDown(200);
	// 	}
	// );
    //
	// // 当鼠标离开 .menu-nav ul 时
	// $('.menu-nav-son-li').mouseleave(function () {
	// 	// 隐藏所有子菜单
	// 	$('.menu-nav-son2').stop(true, true).slideUp(0);
	// });


    var checkDownloadStatus = function() {
        var intervalId = setInterval(function() {
            //console.log('checkDownloadStatus ....');
            $.ajax({
                url: '/download-status',
                method: 'GET',
                dataType: 'json',
                data: { reset: 0 },
                success: function(response) {
                    console.log(response);
                    if (response.status == "2") {
                        console.log('clean');
                        clearInterval(intervalId);
                        layer.close(loadIndex); // 关闭加载层
                    }
                }
            });
        }, 1000); // 每秒请求一次
    }

    // 放大图片 start
// 创建全屏遮罩层
    $('.album-thumb-detail').on('click', function (event) {
        // 如果点击的是 download-icon，阻止后续代码执行
        if ($(event.target).closest('.download-icon').length) {
            return;
        }

        // 获取当前点击的 .album-thumb-detail 的父级 .grid-album 元素
        var $parentAlbum = $(this).closest('.grid-album');

        // 获取当前父级下所有 .album-thumb-detail img 的 src
        var imageSrcArray = [];
        $parentAlbum.find('.album-thumb-detail img').each(function () {
            src = $(this).attr('data-src')+"?x-oss-process=image/resize,w_800";
            // newSrc = src.split('?')[0];
            imageSrcArray.push(src);
        });

        // 获取当前点击图片在数组中的索引
        var $albumThumbs = $parentAlbum.find('.album-thumb-detail');
        var currentImageIndex = $albumThumbs.index(this);
        // console.log(currentImageIndex);

        const $fullscreenMask = $('<div>').addClass('fullscreen-mask');
        const $fullscreenImg = $('<img>').attr('src', imageSrcArray[currentImageIndex]);
        const $btnLeft = $('<div>').addClass('fullscreen-btn fullscreen-btn-left').html('&lt;');
        const $btnRight = $('<div>').addClass('fullscreen-btn fullscreen-btn-right').html('&gt;');
        const $btnDownload = $('<div>').addClass('fullscreen-btn fullscreen-btn-download').html('&#11123;'); // 下载图标

        $fullscreenMask.append($fullscreenImg, $btnLeft, $btnRight, $btnDownload);

        // 将遮罩层添加到 body
        $('body').append($fullscreenMask);
        setTimeout(function () {
            $fullscreenMask.addClass('active');
        }, 10);

        // 点击遮罩层时关闭
        $fullscreenMask.on('click', function (e) {
            if (!$(e.target).is($btnLeft) && !$(e.target).is($btnRight) && !$(e.target).is($btnDownload)) {
                $fullscreenMask.removeClass('active');
                setTimeout(function () {
                    $fullscreenMask.remove();
                }, 300);
            }
        });

        // 点击左按钮显示上一张图片
        $btnLeft.on('click', function () {
            currentImageIndex--;
            if (currentImageIndex < 0) {
                currentImageIndex = imageSrcArray.length - 1;
            }
            $fullscreenImg.attr('src', imageSrcArray[currentImageIndex]);
        });

        // 点击右按钮显示下一张图片
        $btnRight.on('click', function () {
            currentImageIndex++;
            if (currentImageIndex >= imageSrcArray.length) {
                currentImageIndex = 0;
            }
            $fullscreenImg.attr('src', imageSrcArray[currentImageIndex]);
        });

        // 点击下载按钮下载当前图片
        $btnDownload.on('click', function (e) {
            e.stopPropagation(); // 阻止事件冒泡

            loadIndex = layer.load(2, { shade: [0.8, '#000'] });
            $.ajax({
                url: '/download-status',
                method: 'GET',
                dataType: 'json',
                data: { reset: 1 },
                success: function(response) {
                    const currentImageSrc = imageSrcArray[currentImageIndex];
                    // 下载图片 js urlencode
                    href_url = '/download-image?url='+encodeURIComponent(currentImageSrc);
                    window.location.href = href_url;
                    //延迟执行，等待下载完成
                    // setTimeout(function() {
                    //     layer.close(loadIndex); // 关闭加载层
                    // }, 2000);
                    checkDownloadStatus();
                }
            });
        });
    });

    // 放大图片 end


	const $overlay = $('#overlay');
	const $videoPlayer = $('#videoPlayer');
	const $closeBtn = $('#closeBtn');
	const $videoBtns = $('.video-btn');

	// 点击播放按钮
	$videoBtns.on('click', function() {
		const videoSrc = $(this).data('src'); // 获取 data-src 属性
		$videoPlayer.attr('src', videoSrc); // 设置视频源
        $videoPlayer[0].autoplay = true; // 设置自动播放
		$overlay.css('display', 'flex'); // 显示遮罩层
	});

	// 点击关闭按钮
	$closeBtn.on('click', function() {
		$videoPlayer[0].pause(); // 暂停视频
		$videoPlayer.attr('src', ''); // 清空视频源
		$overlay.hide(); // 隐藏遮罩层
	});

	// 点击遮罩层关闭
	$overlay.on('click', function(event) {
		if (event.target === $overlay[0]) { // 判断是否点击的是遮罩层本身
			$videoPlayer[0].pause(); // 暂停视频
			$videoPlayer.attr('src', ''); // 清空视频源
			$overlay.hide(); // 隐藏遮罩层
		}
	});

	// 为 .log-date 绑定点击事件
	$('.log-date').on('click', function() {
		// 找到当前 .log-date 的同级 .log-line 元素
		$(this).siblings('.log-line').toggleClass('active');
	});

    //日志
    // 检查 update-log 是否存在
    if ($('.update-log').length > 0) {
        // 定义一个函数来执行 AJAX 请求
        function fetchUpdate() {
            $.ajax({
                url: '/next-log', // 替换为你的 API 端点
                method: 'GET', // 根据你的需求选择 GET 或 POST
                dataType: 'json', // 根据你的 API 返回的数据类型选择
                success: function(response) {
                    // 假设 response 包含 timestamp 和 message
                    var created_at = response.data.created_at;
                    var action = response.data.action;
                    if (action == 'aa') {
                        action = '新增了';
                    } else {
                        action = '更新了';
                    }
                    var model = "<a href='/detail?id="+response.data.content_id+"'>" + response.data.model + '</a> 的';
                    var content = response.data.content;
                    var user_name = response.data.user_name;

                    // 更新 timestamp 和 message
                    $('.update-log .update-time').text(created_at);
                    $('.update-log .user_name').text(user_name);
                    $('.update-log .action').text(action);
                    $('.update-log .model').html(model);
                    $('.update-log .log-content').text(content);
                },
                error: function(xhr, status, error) {
                    console.error('AJAX 请求失败:', status, error);
                }
            });
        }
        // 立即执行一次
        fetchUpdate();
        // 每 10 秒执行一次
        setInterval(fetchUpdate, 20000); // 10000 毫秒 = 10 秒
    }


    var downdHref = function() {
        // 查找 .album-tab 中带有 is-active 类的 <a> 标签
        let activeTab = $('.album-tab a.is-active').attr('href');
        // 将 #album- 替换为空，得到 tab 变量
        let tab = activeTab.replace('#album-', '');
        // 获取当前 URL 中的 id 参数
        let currentUrl = window.location.href;
        let urlParams = new URLSearchParams(currentUrl.split('?')[1]);
        let id = urlParams.get('id');
        // 拼接新的 URL
        let newUrl = `/download-all?id=${id}&tab=${tab}&refresh=true`;
        // 跳转到新 URL
        window.location.href = newUrl;
    }

    //ajax 定时请求 /download-status，直到返回状态为 0 时


    // 监听 .download-all 的点击事件
    $('.download-all').on('click', function() {
        loadIndex = layer.load(2, { shade: [0.8, '#000'] }); // 参数1表示加载样式，shade
        //jquery  请求 /download-status
        $.ajax({
            url: '/download-status',
            method: 'GET',
            dataType: 'json',
            data: { reset: 1 },
            success: function(response) {
                downdHref();
                checkDownloadStatus();
            }
        });
    });

    $('.download-btn').on('click', function() {
        loadIndex = layer.load(2, { shade: [0.8, '#000'] }); // 参数1表示加载样式，shade
        //jquery  请求 /download-status
       // window.location.href = $(this).attr('url');
        //
        setTimeout(function() {
            layer.close(loadIndex); // 关闭加载层
        }, 1500);
    });



    if ( window.innerWidth <= 768) {
        hamburgerMenuWrap = $('.menu-wrap');
        hamburgerMenuWrap.removeClass('menu-active');
        $(".content").css("padding-left","0px");
    }


    $(".download-icon").on('click', function() {
        loadIndex = layer.load(2, {shade: [0.8, '#000']});
        const currentImageSrc = $(this).attr('data-src');
        $.ajax({
            url: '/download-status',
            method: 'GET',
            dataType: 'json',
            data: {reset: 1},
            success: function (response) {
                // 下载图片 js urlencode
                href_url = '/download-image?url=' + encodeURIComponent(currentImageSrc);
                window.location.href = href_url;
                checkDownloadStatus();
            }
        });
    });
});

function changeIframeSrc(url) {
    // 获取 iframe 元素
    const iframe = document.getElementById('myFrame');
    // 改变 iframe 的 src 属性
    iframe.src = url;
    if ( window.innerWidth <= 768) {
        hamburgerMenuWrap = $('.menu-wrap');
        hamburgerMenuWrap.removeClass('menu-active');
        $(".content").css("padding-left","0px");
    }
}

function logout() {
    layer.confirm('是否确定退出登录？', {
        btn: ['确定', '关闭'] //按钮
    }, function(){
        window.top.location.href = "/logout";
    }, function(){
        layer.close();
    });
}
