let langPage = 'zh'

//   初始化后

// 监听页面可见性变化事件
document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'visible') {
        chrome.storage.sync.get([ "token","ext_lang"], function (result) {
        console.log(langPage,result.ext_lang ,'监听页面可见性变化事件');
     });
    }
});
let timmer = null;
let params;
let isStart = false;
let appointmentDate = '';
let tabId;
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log("收到来自扩展的消息：", message, sender);
  // 退出登录
  if(message.changeLang === 1){
   const lang = message.lang;
      if(!lang === 'zh'){
         langPage = lang
      }
  }
  if(message.type === 'start') {
    isStart = true;
    params = message.params;
    tabId = message.tabActiveId;
    stepOne('start');
  } else if(message.type === 'selectWarehouse' || message.type === 'chooseDate') {
    if(timmer) return;
    timmer = setTimeout(() => {
        if(message.type === 'chooseDate') {
            stepThree();
        } else {
            stepTwo();
        }
        timmer = null;
    }, 500)
  } else if(message.type === 'cancel') {
    isStart = false;
  } else if(message.type === 'getWarsehouseInfo') {
    tabId = message.tabActiveId;
    getParamsInfo();
  } else if(message.type === 'checkUrl') {
    getParamsInfo('url');
  }
});

let nextStep = async (type) => {
    await simulateComplexMouseAction('.Steps__buttons-next__XFoWeh8mmg .button__3Fti4q6ulA.m__HHCrW92un8.fullWidth__q6ejLUQ5rB', type);
}
let previousStep = async () => {
    await simulateComplexMouseAction('.Steps__buttons-back .button__MXCYWuCbQ1.m__SN8tqZ8j6X.onlyIcon__iaBpex4HKr');
}

let stepOne = (type) => {
    nextStep(type);
}
let btnClass = '.Warehouse-select__container__V5KEe0TU5e>div>div:nth-child(2)';
let stepTwo = async () => {
    let inputState = await observeInputState(btnClass, 0);

    if(inputState) {
        await simulateComplexMouseAction(btnClass);
        setTimeout(async () => {
            const isMatchWarehouse = await matchWarseHouse('._rt-list-virtual_k094q_1 li');
            if(isMatchWarehouse) {
                let packageCard = await mutationObseverEl('.Min-supplies-types__supplies-container__51JyJyrdb5');
                let deliveryTarget = packageCard.children[params.deliveryType].children[0];
                if(!deliveryTarget.children[0].children[0].children[0].disabled) {
                    deliveryTarget.click();
                    if(params.transitWarehouseId) {
                        let transitWarse = await handleTransitWarehouse();
                        if(transitWarse) {
                            nextStep();
                        } else {
                            previousStep();
                        }
                        return;
                    }
                    nextStep();
                } else {
                    if(params.deliveryType === '1') {
                        isStart = false;
                        chrome.runtime.sendMessage({ action: 'cancel', tabId });
                        return;
                    }
                    previousStep();
                }
            } else {
                previousStep();
            }
        }, 1500);
        let modal = await mutationObseverEl('.Planning-goods-modal__AEZaocalzg');
        if(modal) {
            isStart = false;
            chrome.runtime.sendMessage({ action: 'cancel', tabId });
        }
    }
}
let stepThree = async () => {
    let checkDate = await check(params);
    if(checkDate) {
        let selectTarget = document.querySelector('.Calendar-cell--is-checked__yqCU5qaqQv').children[0];
        appointmentDate = selectTarget.children[0].children[0].textContent;
        await nextStep();
        let error = await mutationObseverEl('.Notifications-modals-container__modal-animation-box');
        if(error) {
            previousStep();
        }
    } else {
        previousStep();
    }
}
// 按钮点击事件
async function simulateComplexMouseAction(el, type) {
    let targetEl = await mutationObseverEl(el);
    
    // 创建并触发鼠标悬停
    const mouseOver = new MouseEvent('mouseover', {
        bubbles: true,
        cancelable: true
    });
    targetEl.dispatchEvent(mouseOver);
    
    // 等待后点击
    await new Promise(resolve => setTimeout(resolve, type ? 10 : 1500));
    if(!isStart) {
        return;
    }
    targetEl.click();
}

// 检测数据是否加载完
let observeInputState = (el, inx, type) => {
    return new Promise(resolve => {
        const targetInput = document.querySelectorAll(el)[inx]?.children[0];
        if (targetInput.dataset.surfaceState !== 'disabled') {
            resolve(true); // 如果输入框已启用，则立即返回 true
            return;
        }

        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                if (targetInput.dataset.surfaceState !== 'disabled') {
                    observer.disconnect();
                    resolve(true);
                }
            });
        });

        observer.observe(targetInput, {
            attributes: true,
            cancelable: true
        });
    })
}
// 匹对仓库
let matchWarseHouse = async (el) => {
    let isMatch = false;
    if(document.querySelector(btnClass)?.value === params.targetWarehouseName) {
        isMatch = true;
    } else {
        const inputElement = document.querySelector('form[data-testid] input');
        inputElement.focus();
        document.execCommand('insertText', false, params.targetWarehouseName);
        inputElement.dispatchEvent(new Event('input', { bubbles: true }));
        await new Promise(resolve => {
            setTimeout(() => {
                document.querySelectorAll(el).forEach((item) => {
                    let elText = item.querySelector('.rt-0-body-md-regular.rt-0-text.rt-0-text--color-main')?.innerText;
                    if(elText === params.targetWarehouseName && !item.querySelector('input').disabled) {
                        item.querySelector('label').click();
                        isMatch = true;
                    }
                });
                resolve(isMatch);
            }, 1000);
        });
    };
    return isMatch;
}

let btn2Class = '.Transit-warehouse-select__container__xGAd523Wgm>div>div:nth-child(2)'
let handleTransitWarehouse = async () => {
    return new Promise(async (resolve) => {
        let inputState = await observeInputState(btn2Class, 0, 'transit');
        if(inputState) {
            setTimeout(() => {
                document.querySelectorAll(btn2Class)[0].click();
                setTimeout(() => {
                    let isMatch = false;
                    document.querySelectorAll('._rt-list-virtual_k094q_1 li').forEach(item => {
                        if(item.innerText === params.transitWarehouseName && !item.querySelector('input').disabled) {
                            item.querySelector('label').click();
                            isMatch = true;
                            resolve(true);
                        }
                    })
                    if(!isMatch) {
                        resolve(false);
                    }
                }, 1500)
            }, 1500)
        }
    })
}

// 检索元素并返回
let mutationObseverEl = (el) => {
    return new Promise((resolve) => {
        let found;
        // 立即检查是否已存在
        found = document.querySelector(el);
        if (found) return resolve(found);

        let observer = new MutationObserver((mutations) => {
            found = document.querySelector(el);
            if (found) {
                observer.disconnect();
                resolve(found);
            }
        })
        observer.observe(document.body, { childList: true, subtree: true, attributes: true, characterData: true });
    })
}

const orderDetailPage = 'https://seller.wildberries.ru/supplies-management/all-supplies/supply-detail';
let timerMap = new Map();

const defaultColor = 'rgba(211, 211, 211, 0.445)';
let colorAnimation;
let isAnimating = false;
function normalizeUiText(value) {
    return (value ?? '').toString().replace(/\s+/g, ' ').trim();
}
function isSelectActionText(value) {
    const text = normalizeUiText(value).toLowerCase();
    const keywords = ['选择', 'select', 'choose', 'выбрать'];
    return keywords.some(k => text === k || text.startsWith(k + ' '));
}
function isSelectAnotherDateText(value) {
    const text = normalizeUiText(value).toLowerCase();
    if (text === '选择另一个日期' || text.startsWith('选择另一个日期 ')) return true;
    if ((text.includes('select') || text.includes('choose')) && text.includes('another') && text.includes('date')) return true;
    if (text.includes('выбрать') && text.includes('друг') && text.includes('дат')) return true;
    return false;
}
function isNoSlotsText(value) {
    const text = normalizeUiText(value).toLowerCase();
    const patterns = [
        /还没有/,
        /no\s*(slots|time\s*slots|availability|available)/i,
        /not\s*available/i,
        /пока\s*нет/i,
        /пока\s*недоступно/i,
        /нет\s*(слотов|доступных|времени)/i
    ];
    return patterns.some(p => p.test(text));
}
function extractCoefficientValue(value) {
    const text = normalizeUiText(value);
    const patterns = [
        /承兑\s*[×xх]\s*(\d+)/i,
        /(acceptance)\s*[×xх]\s*(\d+)/i,
        /(Приёмка|акцепт|при[её]мк[аи]|коэффициент\s*при[её]мк[иы])\s*[×xх]\s*(\d+)/i,
        /[×xх]\s*(\d+)/i
    ];
    for (const pattern of patterns) {
        const match = text.match(pattern);
        if (!match) continue;
        for (let i = match.length - 1; i >= 1; i--) {
            const n = parseInt(match[i], 10);
            if (!Number.isNaN(n)) return n;
        }
    }
    return 0;
}
function check(order) {
    return new Promise(async (resolve) => {
        const allButtons = Array.from(document.querySelectorAll('button'));
        const selectAnotherDateButton = allButtons.find(btn => isSelectAnotherDateText(btn.textContent));
        if (selectAnotherDateButton) {
            console.log("已点击选择另一个日期");
            simulateFullClick(selectAnotherDateButton);
        }
            const warehouseName = params.targetWarehouseName;
            // simulateFullClick(scheduleDeliveryButton);
            //点击安排交货按钮后等待页面加载完成
            const observer = new MutationObserver(async (mutations, obs) => {
                //使用 querySelector 查询 类名是 Calendar-plan-table-view 的 div 元素
                const CalendarPlanTableView = document.querySelector('div.Calendar-plan-table-view');
                try {
                    if (CalendarPlanTableView) {
                        console.log('发现日历表格上层DIV');
                        obs.disconnect();

                        // 设置托盘数量
                        if (params.deliveryType === '1') {
                            const amountPalletInput = document.querySelector('#amountPallet');
                            console.log("pallets: " + order.pallets);
                            //console.log('找到amountPalletInput');
                            amountPalletInput.value = order.pallets; // 设置值
                            // 触发 input 事件
                            amountPalletInput.dispatchEvent(new Event('input', { bubbles: true }));
                            // 触发 change 事件（有些页面需要）
                            amountPalletInput.dispatchEvent(new Event('change', { bubbles: true }));
                        } else {
                            console.log('未找到amountPalletInput');
                        }

                        const calendarTable = CalendarPlanTableView.querySelector('table[class^="Calendar-plan-table-view__calendar-table__"]');
                        if (calendarTable) {
                            console.log('发现日历表格');
                            const tds = calendarTable.querySelectorAll('tbody > tr > td');
                            if (tds.length > 0) {
                                console.log('找到单元格，数量' + tds.length);
                                // 过滤掉tds中内容为''的td
                                const notEmptyTds = Array.from(tds).filter(td => td.textContent.trim() !== '');
                                let nofoundNumber = 0;
                                let hoveredTds = [];

                                Array.from(notEmptyTds).forEach((td, index) => {
                                    const text = td.textContent.trim();
                                    if (!text) {
                                        return;
                                    } else {
                                        if (isNoSlotsText(text)) {
                                            nofoundNumber++;
                                        } else {
                                            let coefficientValue = extractCoefficientValue(text);
                                            hoveredTds.push({ "index": index, "td": td, "coefficient": coefficientValue });
                                        }
                                    }
                                });
                                if (notEmptyTds.length == nofoundNumber) {
                                    const cancelButton = document.querySelector('div.Calendar-plan-buttons__cancel > button');
                                    if (cancelButton) {
                                        console.log("找到取消按钮");
                                        simulateFullClick(cancelButton);
                                        resolve(false);
                                        return;
                                    } else {
                                        console.log("没有找到取消按钮");
                                    }
                                } else {
                                    hoveredTds.sort((a, b) => a.coefficient - b.coefficient);
                                    // 日期优先
                                    if (order.monitorType === 1) {
                                        // 遍历hoveredTds, 如果对象的 index 属性 >=order.start 并且 <=order.end ，那么鼠标悬停到该对象对应的 td
                                        for (let i = 0; i < hoveredTds.length; i++) {
                                            if (order.dateMode === 1) {
                                                if (hoveredTds[i].index >= order.start && hoveredTds[i].index <= order.end) {
                                                    let submitResult = await submitOrder(hoveredTds[i]);
                                                    if(submitResult) {
                                                        resolve(true);
                                                        break;
                                                    }
                                                } else {
                                                    console.log("动态时间段不在设定的日期范围内" + hoveredTds[i].index);
                                                }
                                            }
                                            if (order.dateMode === 2) {
                                                if (hoveredTds[i].index >= getDaysDiffLocal(order.startFixed) && hoveredTds[i].index <= getDaysDiffLocal(order.endFixed)) {
                                                    let submitResult = await submitOrder(hoveredTds[i]);
                                                    if(submitResult) {
                                                        resolve(true);
                                                        break;
                                                    }
                                                } else {
                                                    console.log("固定时间段不在设定的日期范围内" + hoveredTds[i].index);
                                                }
                                            }
                                        }
                                        resolve(false);
                                        return;
                                    }
                                    // 费率优先
                                    if (order.monitorType === 2) {
                                        for (let i = 0; i < hoveredTds.length; i++) {
                                            if (order.dateMode === 1) {
                                                if (hoveredTds[i].index >= order.start && hoveredTds[i].index <= order.end && hoveredTds[i].coefficient >= order.minRate && hoveredTds[i].coefficient <= order.maxRate) {
                                                    let submitResult = await submitOrder(hoveredTds[i]);
                                                    if(submitResult) {
                                                        resolve(true);
                                                        break;
                                                    }
                                                } else {
                                                    console.log("动态时间段不在设定的日期和费率范围内" + hoveredTds[i].index + " " + hoveredTds[i].coefficient);
                                                }
                                            }
                                            if (order.dateMode === 2) {
                                                if (hoveredTds[i].index >= getDaysDiffLocal(order.startFixed) && hoveredTds[i].index <= getDaysDiffLocal(order.endFixed) && hoveredTds[i].coefficient >= order.minRate && hoveredTds[i].coefficient <= order.maxRate) {
                                                    
                                                    let submitResult = await submitOrder(hoveredTds[i]);
                                                    console.log('submitResult:', submitResult);
                                                    
                                                    if(submitResult) {
                                                        resolve(true);
                                                        break;
                                                    }
                                                } else {
                                                    console.log("固定时间段不在设定的日期和费率范围内" + hoveredTds[i].index + " " + hoveredTds[i].coefficient);
                                                }
                                            }
                                        }
                                        resolve(false);
                                        return;
                                    }
                                }
                            } else {
                                console.log("没发现td");
                                resolve(false);
                            }
                        } else {
                            console.log('未发现日历表格');
                            resolve(false);
                        }
                    } else {
                        console.log('未发现日历表格上层 DIV');
                        //resolve(false);
                    }
                } catch (error) {
                    //reject(error); // 捕获异常
                    console.error("检查过程中发生错误:", error);
                    obs.disconnect();
                    resolve(false);
                }
            });
            observer.observe(document.body, { childList: true, subtree: true });
            // 添加超时兜底逻辑（防止无限等待）
            setTimeout(() => {
                observer.disconnect();
                resolve(false); // 超时视为未找到元素
            }, 15000);
        // } else {
        //     console.log("未发现安排交货按钮");
        //     resolve(false);
        // }
    })
};
function submitOrder(hoveredTd) {
    return new Promise(async (resolve) => {
        simulateHover(hoveredTd.td);
        // 等待动态内容出现
        const selectButton = await waitForElementInContainer(
            hoveredTd.td,
            'button, span',
            el => isSelectActionText(el.textContent),
            2500
        );
        
        if (selectButton) {
            console.log('找到"选择"按钮并点击');
            simulateFullClick(selectButton);
            resolve(true);
        } else {
            console.log('未找到"选择"按钮');
            resolve(false);
        }
    });
};
function sendNotify(orderId, companyName, appointmentDate) {
    // 发送邮件
   let port = chrome.runtime.connect({name: 'sendNotify'});
   let message = {
        orderId,
        taskName: params.taskName,
        enterprise: companyName,
        appointmentDate,
        tabId
   }
    port.postMessage(message); // 发送消息
    console.log(`订单: ${orderId} ,成功预约仓库: ${companyName}`);
};
$(document).on('click','#stopMonitor',function () {
    const urlParams = new URLSearchParams(window.location.search);
    const preorderId = urlParams.get('preorderId');
    if (preorderId) {
        if (timerMap.has(preorderId)) {
            clearTimeout(timerMap.get(preorderId));
            timerMap.delete(preorderId);
            alert('已停止监控');
        }
    }
});
//     const yuananniu = document.getElementById('yuananniu');
//     // 初始化颜色显示
//     yuananniu.style.backgroundColor = defaultColor;

//     // 创建背景色变换动画
//     function createColorAnimation() {
//         return anime({
//             targets: yuananniu,
//             backgroundColor: [
//                 '#00f5d4'
//             ],
//             duration: 2000,
//             easing: 'easeInOutSine',
//             loop: true,
//             autoplay: false,
//             complete: function () {
//                 if (!isAnimating) return;
//                 // 循环完成后重新开始
//                 colorAnimation.restart();
//             }
//         });
//     }

//     // 初始化动画
//     colorAnimation = createColorAnimation();

//     if (isAnimating) return;
//     isAnimating = true;
//     colorAnimation.play();
// };
// function stopAnime() {
//     const yuananniu = document.getElementById('yuananniu');
//     if (!isAnimating) return;
//     isAnimating = false;
//     colorAnimation.pause();
//     // 平滑过渡回默认颜色
//     anime({
//         targets: yuananniu,
//         backgroundColor: defaultColor,
//         duration: 800,
//         easing: 'easeOutExpo'
//     });
// };
function simulateFullClick(element) {
    // 1. 创建并触发 mousedown 事件（按下鼠标）
    const mouseDownEvent = new MouseEvent('mousedown', {
        view: window,
        bubbles: true,
        cancelable: true,
        button: 0 // 0 表示左键[7,13](@ref)
    });
    element.dispatchEvent(mouseDownEvent);

    // 2. 创建并触发 mouseup 事件（释放鼠标）
    const mouseUpEvent = new MouseEvent('mouseup', {
        view: window,
        bubbles: true,
        cancelable: true,
        button: 0
    });
    element.dispatchEvent(mouseUpEvent);

    // 3. 创建并触发 click 事件（完整点击）
    const clickEvent = new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: true,
        button: 0
    });
    element.dispatchEvent(clickEvent);
};
function simulateHover(element) {
    element.dispatchEvent(new PointerEvent('pointerover', {
        bubbles: true,
        cancelable: true,
        view: window
    }));
    element.dispatchEvent(new MouseEvent('mouseover', {
        bubbles: true,
        cancelable: true,
        view: window
    }));
    element.dispatchEvent(new PointerEvent('pointerenter', {
        bubbles: true,
        cancelable: true,
        view: window
    }));
    element.dispatchEvent(new MouseEvent('mouseenter', {
        bubbles: true,
        cancelable: true,
        view: window
    }))
};
function waitForElementInContainer(container, selector, condition, timeout = 5000) {
    return new Promise((resolve) => {
        const startTime = Date.now();

        // 立即检查是否已存在
        const existing = Array.from(container.querySelectorAll(selector)).find(condition);
        if (existing) return resolve(existing);

        // 设置MutationObserver监听变化
        const observer = new MutationObserver((mutations) => {
            const found = Array.from(container.querySelectorAll(selector)).find(condition);
            if (found) {
                observer.disconnect();
                resolve(found);
            }
            // 超时检查
            else if (Date.now() - startTime > timeout) {
                observer.disconnect();
                resolve(null);
            }
        });

        observer.observe(container, {
            childList: true,
            subtree: true,
            attributes: true,
            characterData: true
        });
    });
};
function getDaysDiffLocal(targetDateStr) {
    const targetDate = new Date(targetDateStr);
    const currentDate = new Date();
    targetDate.setHours(0, 0, 0, 0);
    currentDate.setHours(0, 0, 0, 0);
    const timeDiff = targetDate.getTime() - currentDate.getTime();
    return Math.floor(timeDiff / (86400000));
};
$(function() {
    setupMutationObserver();
    getParamsInfo('info');
    getParamsInfo('url');
});

// 监听DOM变化来检测SPA路由切换
function setupMutationObserver() {
    let lastTitle = document.title;
  
    const observer = new MutationObserver(async (mutations) => {
        // 检查标题变化（很多SPA切换页面时会改标题）
        let href = window.location.href;
        getParamsInfo('url');
        if (document.title !== lastTitle) {
            lastTitle = document.title;
            getParamsInfo('info');
            if(isStart) {
                if(href.includes('/new-supply/goods')) {
                    stepOne();
                } else if(href.includes('/new-supply/recommendations')) {
                    stepTwo();
                } else if(href.includes('/new-supply/choose-date')) {
                    stepThree();
                } else if(href.includes('/new-supply/packaging')) {
                    const url = new URL(href);
                    let supplyId = url.searchParams.get('supplyID');
                    if (supplyId) {
                        isStart = false;
                        let text = await mutationObseverEl('.Text__6ZkJ5aBoOH.Text--body-m__7K7CsbK0Ne.Text--black__o8JL1JaXQy.Text--textDecoration-none__jwmF3paGFc');
                        console.log(text.innerText.split(' '));
                        let id = text.innerText.split('№')[1];
                        let companyName = document.querySelector('.chips_Chips__text__qZG82.chips_Chips__text--trim__B80rR.chips_Chips__text--textAlign-center__ZIpUT').innerText;
                        sendNotify('№'+id, companyName, appointmentDate);
                        chrome.runtime.sendMessage({ action: 'finish', tabId });
                    }
                }
            }
        }
        if(href.includes('/new-supply/goods') && !isStart) {
            let selectGoodsTabel = await mutationObseverEl(".Control-card__button-container__KFcmu532qL");
            selectGoodsTabel.addEventListener('click', bindEvent);
        }
    });

    let bindEvent = async () => {
        let saveBtn = await mutationObseverEl(".Goods-table-view__add-button__lwwO5zyFMN");
        saveBtn.children[0].addEventListener("click", async function() {
            let table = await mutationObseverEl(".Breadcrumbs-layout__content__dupFHIMwY2 .New-supply-table__tbody");
            if(table) {
                setTimeout(() => {
                    getParamsInfo();
                }, 500)
            }
        });
    }
  
    observer.observe(document.body, {
        childList: true,
        subtree: true,
        characterData: true,
        attributes: true
    });
}
    
let getParamsInfo = function (type) {
    let href = window.location.href
    if(!href.includes('https://seller.wildberries.ru/')) {
        return
    }
    const url = new URL(href);
    let draftID = url.searchParams.get('draftID');

    let token = window.localStorage.getItem('wb-eu-passport-v2.access-token');
    if(type === 'info') {
        const payload = { action: 'warehouseInfo', draftID, token };
        if (tabId) payload.tabId = tabId;
        chrome.runtime.sendMessage(payload);
    } else if(type === 'url') {
        const payload = { action: 'url', url: href };
        if (tabId) payload.tabId = tabId;
        chrome.runtime.sendMessage(payload);
    } else {
        const infoPayload = { action: 'warehouseInfo', draftID, token };
        const urlPayload = { action: 'url', url: href };
        if (tabId) {
            infoPayload.tabId = tabId;
            urlPayload.tabId = tabId;
        }
        chrome.runtime.sendMessage(infoPayload);
        chrome.runtime.sendMessage(urlPayload);
    }
}
