let reloadTimeout;
// 存储已知符合条件的PageType
const supportedPageTypes = new Set();

// 添加CSS规则来加速过渡
$(document).ready(function() {
    // 添加CSS样式，使过渡更平滑
    $('<style>')
        .prop('type', 'text/css')
        .html(`
            .layout-side-section {
                transition: width 0.2s ease-out;
            }
            .form-sidebar .form-attachments .attachment-row img {
                opacity: 0;
                transition: opacity 0.3s;
            }
            .form-sidebar .form-attachments .attachment-row img.loaded {
                opacity: 1;
            }
            textarea[data-fieldtype="Small Text"][data-pagetype="Ai Agent"]{
                min-height: 120px !important;
            }
        `)
        .appendTo('head');
    
    // 监听路由变化前的事件，只对已知符合条件的PageType预先应用样式
    $(document).on('routing-before', function() {
        // 检查URL，提取PageType
        const hash = window.location.hash;
        if (hash.includes('Form/')) {
            const parts = hash.split('/');
            if (parts.length >= 2) {
                const pagetype = parts[1];
                // 只有已知支持的PageType才预先应用样式
                if (supportedPageTypes.has(pagetype)) {
                    $('div[class*="layout-side-section"]').removeClass('col-lg-1 col-lg-2').addClass('col-lg-6');
                } else {
                    // 对不确定的PageType恢复默认样式
                    $('div[class*="layout-side-section"]').removeClass('col-lg-6').addClass('col-lg-1');
                }
            }
        }
    });
    
    handlePageChange();
    setupAutoResize();
});

// 监听页面变化事件
if (window.jingrow && jingrow.router && typeof jingrow.router.on === 'function') {
    jingrow.router.on('change', function() {
        handlePageChange();
        setupAutoResize();
    });
}

// 使用全局form-refresh事件来监听所有表单的刷新
$(document).on("form-refresh", function(e, frm) {
    // 要排除的PageType列表
    const excludedPageTypes = ['Ai Agent'];
    
    // 检查是否符合条件：存在status和image_model字段，且不在排除列表中
    if (frm && frm.meta && frm.meta.fields && 
        frm.meta.fields.some(field => field.fieldname === 'image_model') &&
        !excludedPageTypes.includes(frm.pagetype)) {
        
        // 记录符合条件的PageType
        if (frm.pagetype) {
            supportedPageTypes.add(frm.pagetype);
        }
        
        // 当表单刷新时处理附件显示（只在满足条件时执行）
        if (isDetailPage() && cur_frm) {
            // 立即调整布局
            adjustLayout();
            
            // 然后处理附件
            setTimeout(function() {
                updateAttachments();
                observeAttachmentChanges();
            }, 100); // 减少延迟时间
        }
        
        // 处理进度条
        if (frm.is_new()) {
            frm.set_df_property('progress', 'hidden', 1);
        } else {
            frm.set_df_property('progress', 'hidden', 0);
            updateCustomProgressBar(frm);
        }
        
        // 添加自定义按钮
        // 通用函数，添加按钮并设置相应状态
        function add_custom_button_with_status(label, status_value) {
            frm.add_custom_button(__(label), function() {
                jingrow.confirm(`确认执行${label}操作?`, function() {
                    frm.set_value('status', status_value);
                    frm.save()
                        .catch((error) => {
                            jingrow.msgprint({
                                title: __('Error'),
                                indicator: 'red',
                                message: __('Failed to trigger webhook: ' + error.message)
                            });
                            console.error('Error triggering webhook:', error);
                        });
                });
            });
        }

        // 添加不同的按钮，每个按钮对应不同的状态值
        frm.add_custom_button(__('清空附件'), function() {
            jingrow.confirm(__('确认清空所有附件图片？此操作不可恢复！'), function() {
                jingrow.call({
                    method: 'jingrow.ai.utils.utils.clear_current_page_images',
                    args: {
                        pg_name: frm.pg.name,
                        pagetype: frm.pagetype
                    },
                    callback: function(r) {
                        if (r.message) {
                            jingrow.msgprint({
                                title: __('提示'),
                                indicator: 'green',
                                message: r.message
                            });
                            // 刷新表单以更新附件显示
                            frm.reload_doc();
                        }
                    }
                });
            });
        });
        add_custom_button_with_status('图片放大', '待放大图片');
        add_custom_button_with_status('转矢量图', '待转换为矢量图');
        add_custom_button_with_status('添加背景', '待添加背景颜色');
        add_custom_button_with_status('去背景', '待去背景');
        add_custom_button_with_status('图片描述', '待描述');
        add_custom_button_with_status('翻译', '待翻译');
        add_custom_button_with_status('出图', '待出图');
    } else {
        // 如果不符合条件，则恢复默认布局
        resetLayout();
    }
});

function handlePageChange() {
    if (isDetailPage()) {
        // 检查当前PageType是否已知符合条件
        const hash = window.location.hash;
        const parts = hash.split('/');
        if (parts.length >= 2) {
            const pagetype = parts[1];
            if (supportedPageTypes.has(pagetype)) {
                // 对已知符合条件的PageType立即应用样式
                adjustLayout();
            }
        }
        
        // 等待cur_frm加载完成再处理附件
        if (typeof cur_frm !== 'undefined' && cur_frm) {
            setTimeout(function() {
                try {
                    // 检查是否符合条件
                    if (cur_frm && cur_frm.meta && cur_frm.meta.fields && 
                        cur_frm.meta.fields.some(field => field.fieldname === 'status') && 
                        cur_frm.meta.fields.some(field => field.fieldname === 'image_model') &&
                        cur_frm.pagetype !== 'Ai Agent') {
                        updateAttachments();
                        observeAttachmentChanges();
                    }
                } catch(e) {
                    console.error("处理附件时出错:", e);
                }
            }, 100); // 减少延迟时间
        } else {
            // 如果cur_frm还没有加载，延迟执行
            setTimeout(handlePageChange, 100); // 减少重试间隔
        }
    } else {
        resetLayout();
    }
}

function isDetailPage() {
    var dataRoute = $('body').attr('data-route');
    return dataRoute && dataRoute.includes('Form/');
}

function adjustLayout() {
    // 修改左侧和右侧区域的宽度
    $('div[class*="layout-side-section"]').removeClass('col-lg-1 col-lg-2').addClass('col-lg-6');

    // 修改附件显示样式
    let attachmentList = $('.form-sidebar .form-attachments');
    if (attachmentList && attachmentList.length) {
        attachmentList.addClass('row').css('margin', '0');
        attachmentList.find('li.attachments-actions').css('width', '100%');
        attachmentList.find('li.attachment-row').css('width', '50%').css('float', 'left').css('padding', '10px');
    }
}

function resetLayout() {
    // 恢复左侧和右侧区域的默认宽度
    $('div[class*="layout-side-section"]').removeClass('col-lg-6').addClass('col-lg-1');

    // 移除附件样式的修改
    let attachmentList = $('.form-sidebar .form-attachments');
    if (attachmentList && attachmentList.length) {
        attachmentList.removeClass('row').css('margin', '');
        attachmentList.find('li.attachments-actions').css('width', '');
        attachmentList.find('li.attachment-row').css('width', '').css('float', '').css('padding', '');
    }
}

function getHiddenImages() {
    let hiddenFields = ['reference_image_1', 'reference_image_2', 'reference_image_3', 'reference_image_4']; 
    let hiddenImages = [];
    
    // 检查cur_frm是否存在并且已经加载
    if (!cur_frm || !cur_frm.pg) {
        return hiddenImages;
    }
    
    hiddenFields.forEach(field => {
        let fieldValue = cur_frm.pg[field];
        
        if (fieldValue) {
            // 存储原始值
            hiddenImages.push(fieldValue);
            
            // 存储URL编码版本
            try {
                let encodedValue = encodeURI(fieldValue);
                if (encodedValue !== fieldValue) {
                    hiddenImages.push(encodedValue);
                }
                
                // 有时URL可能已经部分编码，尝试解码再编码
                let decodedValue = decodeURIComponent(fieldValue);
                let reEncodedValue = encodeURI(decodedValue);
                if (reEncodedValue !== fieldValue && reEncodedValue !== encodedValue) {
                    hiddenImages.push(reEncodedValue);
                }
            } catch (e) {
                // URL编码/解码出错
            }
            
            // 如果URL不包含协议，尝试添加相对路径版本
            if (!fieldValue.startsWith('http') && !fieldValue.startsWith('/files/')) {
                let relativeUrl = '/files/' + fieldValue;
                hiddenImages.push(relativeUrl);
                
                // 添加编码版本的相对路径
                try {
                    hiddenImages.push(encodeURI(relativeUrl));
                } catch (e) {
                    // 相对路径URL编码出错
                }
            }
        }
    });
    
    return hiddenImages;
}

function updateAttachments() {
    // 确保cur_frm存在
    if (!cur_frm || !cur_frm.$wrapper) {
        return;
    }
    
    // 尝试多种选择器找到附件列表
    let attachment_wrapper = $('.form-sidebar .form-attachments');
    if (!attachment_wrapper.length) {
        attachment_wrapper = cur_frm.$wrapper.find('.form-sidebar .form-attachments');
    }
    if (!attachment_wrapper.length) {
        attachment_wrapper = $('div.layout-side-section .form-attachments');
    }
    
    // 获取需要隐藏的图片字段的值
    let hiddenImages = getHiddenImages();

    if (attachment_wrapper.length) {
        attachment_wrapper.find('.attachment-row').each(function() {
            // 尝试从两个位置获取文件URL
            let file_url = $(this).find('a[target="_blank"]').attr('href');
            
            // 如果找不到直接链接，尝试从其他元素获取
            if (!file_url) {
                file_url = $(this).find('span.pill-label a').attr('href');
            }
            
            if (!file_url) {
                return; // 继续下一个附件
            }
            
            // 提取文件名用于更灵活的匹配
            let fileName = file_url.split('/').pop();
            let decodedFileName = "";
            try {
                decodedFileName = decodeURIComponent(fileName);
            } catch (e) {
                decodedFileName = fileName;
            }
            
            let shouldHide = false;
            
            // 尝试多种方式匹配URL
            const normalizeForCompare = (url) => {
                if (!url) return "";
                try {
                    // 尝试解码URL以比较实际内容
                    return decodeURIComponent(url).toLowerCase();
                } catch (e) {
                    return url.toLowerCase();
                }
            };
            
            const normalized_file_url = normalizeForCompare(file_url);
            
            // 检查URL匹配（宽松比较）
            for (let i = 0; i < hiddenImages.length; i++) {
                if (!hiddenImages[i]) continue;
                
                const normalized_hidden = normalizeForCompare(hiddenImages[i]);
                
                if (normalized_file_url === normalized_hidden) {
                    shouldHide = true;
                    break;
                }
                
                // 比较文件名（不考虑编码）
                const hiddenFileName = hiddenImages[i].split('/').pop();
                let decodedHiddenFileName = "";
                try {
                    decodedHiddenFileName = decodeURIComponent(hiddenFileName);
                } catch (e) {
                    decodedHiddenFileName = hiddenFileName;
                }
                
                if (decodedFileName === decodedHiddenFileName) {
                    shouldHide = true;
                    break;
                }
            }
            
            if (shouldHide) {
                $(this).hide(); // 隐藏指定的附件行
            } else if (file_url.match(/\.(jpeg|jpg|gif|png)$/i)) {
                // 显示此附件
                $(this).show();
                
                // 如果图片元素不存在，则创建并添加
                if (!$(this).find('img.attachment-image-preview').length) {
                    let img_element = $('<img>').attr({
                        'src': file_url,
                        'class': 'attachment-image-preview'
                    }).css({
                        'width': '100%',
                        'height': 'auto',
                        'margin-bottom': '10px',
                        'border': '1px solid #ddd',
                        'border-radius': '4px',
                        'padding': '5px',
                        'box-shadow': '0 2px 4px rgba(0,0,0,0.1)',
                        'cursor': 'pointer'
                    });

                    // 添加加载完成事件，逐步显示图片
                    img_element.on('load', function() {
                        $(this).addClass('loaded');
                    });

                    // 添加点击事件，弹出显示大图（支持左右切换）
                    img_element.on('click', function() {
                        // 收集所有可预览图片的URL
                        let allImgs = [];
                        let allRows = $(this).closest('.form-attachments').find('.attachment-row:visible');
                        allRows.each(function() {
                            let url = $(this).find('a[target="_blank"]').attr('href');
                            if (url && url.match(/\.(jpeg|jpg|gif|png)$/i)) {
                                allImgs.push(url);
                            }
                        });
                        let currentIndex = allImgs.indexOf(file_url);
                        if (currentIndex === -1) currentIndex = 0;

                        // 创建弹窗
                        let modal = $('<div>').css({
                            'display': 'flex',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'position': 'fixed',
                            'top': '0',
                            'left': '0',
                            'width': '100vw',
                            'height': '100vh',
                            'background': 'rgba(0, 0, 0, 0.85)',
                            'z-index': '10000',
                            'user-select': 'none',
                            'overflow': 'auto',
                            'transition': 'background 0.2s'
                        }).appendTo('body');

                        // 图片容器
                        let imgWrap = $('<div>').css({
                            'display': 'flex',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'width': '100vw',
                            'height': '100vh',
                            'max-width': '100vw',
                            'max-height': '100vh',
                            'flex-direction': 'column',
                            'position': 'relative'
                        }).appendTo(modal);

                        // 新增：图片和按钮的相对定位容器
                        let imgBox = $('<div>').css({
                            'position': 'relative',
                            'display': 'inline-block',
                            'max-width': '90vw',
                            'max-height': '80vh',
                        }).appendTo(imgWrap);
                        let modal_img = $('<img>').attr('src', allImgs[currentIndex]).css({
                            'max-width': '100%',
                            'max-height': '100%',
                            'border': '5px solid #fff',
                            'border-radius': '10px',
                            'box-shadow': '0 2px 4px rgba(0,0,0,0.1)',
                            'transition': 'opacity 0.2s',
                            'opacity': 1,
                            'background': '#fff',
                            'object-fit': 'contain',
                            'display': 'block',
                        }).appendTo(imgBox);

                        // 左右切换按钮（插入到imgBox内，保证居中于图片）
                        let btnBaseStyle = {
                            'position': 'absolute',
                            'top': '50%',
                            'transform': 'translateY(-50%)',
                            'background': 'rgba(30,30,30,0.32)',
                            'border': 'none',
                            'color': '#fff',
                            'font-size': '24px',
                            'width': '38px',
                            'height': '38px',
                            'border-radius': '50%',
                            'cursor': 'pointer',
                            'outline': 'none',
                            'z-index': '10001',
                            'display': 'flex',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'transition': 'background 0.18s',
                            'padding': 0,
                            'box-shadow': 'none',
                            'opacity': 0.92
                        };
                        let leftBtn = $('<button>').html('<svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" fill="currentColor"/></svg>')
                            .css(Object.assign({}, btnBaseStyle, {'left': '-18px'}))
                            .on('mouseenter', function(){ $(this).css('background', 'rgba(30,30,30,0.48)'); })
                            .on('mouseleave', function(){ $(this).css('background', 'rgba(30,30,30,0.32)'); });
                        let rightBtn = $('<button>').html('<svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6z" fill="currentColor"/></svg>')
                            .css(Object.assign({}, btnBaseStyle, {'right': '-18px'}))
                            .on('mouseenter', function(){ $(this).css('background', 'rgba(30,30,30,0.48)'); })
                            .on('mouseleave', function(){ $(this).css('background', 'rgba(30,30,30,0.32)'); });
                        imgBox.append(leftBtn, rightBtn);

                        // 索引区域美化
                        let idxText = $('<div>').text((currentIndex+1) + ' / ' + allImgs.length)
                            .css({
                                'color': '#fff',
                                'font-size': '16px',
                                'background': 'rgba(30,30,30,0.32)',
                                'border-radius': '12px',
                                'padding': '4px 16px',
                                'margin': '0 auto 8px auto',
                                'position': 'relative',
                                'z-index': '10003',
                                'user-select': 'none',
                                'pointer-events': 'auto',
                                'box-shadow': 'none',
                                'font-weight': 400
                            }).appendTo(imgWrap);

                        // 切换图片函数
                        let switching = false;
                        function showImg(idx) {
                            if (switching) return;
                            switching = true;
                            if (idx < 0) idx = allImgs.length - 1;
                            if (idx >= allImgs.length) idx = 0;
                            currentIndex = idx;
                            modal_img.css('opacity', 0.2);
                            setTimeout(function() {
                                modal_img.attr('src', allImgs[currentIndex]);
                                idxText.text((currentIndex+1) + ' / ' + allImgs.length);
                                modal_img.css('opacity', 1);
                                setTimeout(function(){ switching = false; }, 180);
                            }, 120);
                        }
                        leftBtn.on('click', function(e) {
                            e.stopPropagation();
                            showImg(currentIndex - 1);
                        });
                        rightBtn.on('click', function(e) {
                            e.stopPropagation();
                            showImg(currentIndex + 1);
                        });

                        // 1. 点击图片左/右半区切换，2. 点击非图片区域关闭弹窗
                        imgWrap.on('click', function(e) {
                            // 如果点击的是按钮或索引，不处理
                            if ($(e.target).is('button') || $(e.target).closest('button').length) return;
                            if ($(e.target).is(idxText) || $(e.target).closest(idxText).length) return;
                            if ($(e.target).is(modal_img[0])) {
                                // 判断点击位置
                                let offset = modal_img.offset();
                                let x = e.pageX - offset.left;
                                let w = modal_img.width();
                                if (x < w / 2) {
                                    showImg(currentIndex - 1);
                                } else {
                                    showImg(currentIndex + 1);
                                }
                                return;
                            }
                            // 其他区域关闭弹窗
                            modal.remove();
                        });
                        // modal本身点击（非imgWrap区域）也关闭
                        modal.on('click', function(e) {
                            if (e.target === this) modal.remove();
                        });

                        // 移动端滑动切换
                        let startX = 0, endX = 0, moved = false;
                        imgWrap.on('touchstart', function(e) {
                            if (e.originalEvent.touches.length === 1) {
                                startX = e.originalEvent.touches[0].clientX;
                                moved = false;
                            }
                        });
                        imgWrap.on('touchmove', function(e) {
                            if (e.originalEvent.touches.length === 1) {
                                endX = e.originalEvent.touches[0].clientX;
                                moved = true;
                            }
                        });
                        imgWrap.on('touchend', function(e) {
                            let deltaX = endX - startX;
                            if (moved && Math.abs(deltaX) > 30) {
                                if (deltaX < 0) {
                                    // 向左滑，下一张
                                    showImg(currentIndex + 1);
                                } else {
                                    // 向右滑，上一张
                                    showImg(currentIndex - 1);
                                }
                            }
                            startX = endX = 0;
                            moved = false;
                        });
                    });

                    // 确保在合适的位置添加图片预览
                    $(this).append(img_element);
                }
            } else {
                // 非图片附件，显示
                $(this).show();
            }
        });
    } else {
        // 如果附件列表不存在，可能是页面还没有完全加载，稍后再尝试
        setTimeout(updateAttachments, 500); // 减少重试间隔
    }
}

function observeAttachmentChanges() {
    let attachment_wrapper = cur_frm.$wrapper.find('.form-sidebar .form-attachments')[0];
    if (attachment_wrapper) {
        let observer = new MutationObserver(function(mutations) {
            let shouldReload = false;
            mutations.forEach(function(mutation) {
                if (mutation.type === 'childList') {
                    shouldReload = true;
                }
            });
            if (shouldReload) {
                if (!reloadTimeout) {
                    reloadTimeout = setTimeout(function() {
                        updateAttachments();
                        adjustLayout(); // 调整布局
                        reloadTimeout = null;
                    }, 1000);  // 1秒钟内只允许一次重新加载附件
                }
            }
        });
        let config = { childList: true, subtree: true };
        observer.observe(attachment_wrapper, config);
    } else {
        // Attachment wrapper not found for observer
    }
}

function updateCustomProgressBar(frm) {
    let progress = frm.pg.progress || 0;
    let progressBarContainer = frm.fields_dict["progress"].$wrapper;
    
    // 动态调整父容器的样式，确保宽度为100%
    progressBarContainer.css({
        'max-width': '100%',
        'padding-right': '0'
    });
    
    // 清空容器内容
    progressBarContainer.empty();
    
    // 添加进度条
    let progressBar = $(`
        <div style="background-color: #f3f3f3; border-radius: 50px; overflow: hidden; width: 100%; margin-bottom:15px;">
            <div style="width: ${progress}%; background-color: #4caf50; border-radius: 50px; height: 10px;"></div>
        </div>
    `);
    
    progressBarContainer.append(progressBar);
}

// 设置textarea自动调整高度的函数
function setupAutoResize() {
    setTimeout(function() {
        $('textarea[data-fieldtype="Small Text"]').each(function() {
            $(this).off('input.autoresize');        
            autoResizeTextarea(this);
            $(this).on('input.autoresize', function() {
                autoResizeTextarea(this);
            });
        });
    }, 300);
}
function autoResizeTextarea(element) {
    var originalHeight = $(element).height();
    $(element).css('height', 'auto');
    var scrollHeight = element.scrollHeight;
    var newHeight = Math.max(60, Math.min(scrollHeight, 300));
    if (originalHeight !== newHeight) {
        $(element).css('height', newHeight + 'px');
    }
}

// 优化prompts和prompts_zh切换按钮逻辑，仅在移动端生效
$(document).on('form-refresh', function(e, frm) {
    // 判断是否为移动端
    var isMobile = /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    if (!isMobile) return;

    if (!window.jingrow) return;
    if (!jingrow.ui || !jingrow.ui.form) return;

    // 只处理有prompts和prompts_zh字段的表单
    if (!frm.fields_dict.prompts || !frm.fields_dict.prompts_zh) return;

    // 避免重复插入
    if ($('#toggle-prompts-btn').length) return;

    // 获取两个字段的控件
    var $prompts = frm.fields_dict.prompts.$wrapper;
    var $promptsZh = frm.fields_dict.prompts_zh.$wrapper;

    // 只处理当前section（section_break_gmw）下的col-sm-6变成col-sm-12
    $('.form-section[data-fieldname="section_break_gmw"] .form-column.col-sm-6').removeClass('col-sm-6').addClass('col-sm-12');

    // 默认显示中文，隐藏英文
    $prompts.hide();
    $promptsZh.show();

    // 现代化切换按钮，右对齐，圆角主色，去掉icon
    var $btnWrap = $('<div style="display:flex;justify-content:flex-end;"></div>');
    var $btn = $(
        '<button id="toggle-prompts-btn" type="button" style="background:#F3F3F3;color:#000;border:none;border-radius:18px;font-size:14px;box-shadow:0 2px 8px rgba(22,119,255,0.08);transition:background 0.2s;">' +
        '<span class="btn-text">英文</span>' +
        '</button>'
    );
    $btnWrap.append($btn);
    $btnWrap.insertBefore($promptsZh);

    $btn.on('mouseenter', function(){
        $(this).css('background', '#E0E0E0');
    }).on('mouseleave', function(){
        $(this).css('background', '#F3F3F3');
    });

    $btn.on('click', function() {
        if ($promptsZh.is(':visible')) {
            $promptsZh.hide();
            $prompts.show();
            $btn.find('.btn-text').text('中文');
        } else {
            $prompts.show();
            $prompts.hide();
            $promptsZh.show();
            $btn.find('.btn-text').text('英文');
        }
    });
});

