import os
import re

ROOT = "D:/work/绿水青山/清道夫App/src"

# 路径替换映射：旧路径 -> 新路径
PATH_REPLACEMENTS = {
    "/pages/common/projectList": "/subPackages/pages-common/projectList",
    "/pages/common/projectDetail": "/subPackages/pages-common/projectDetail",
    "/pages/common/addProject": "/subPackages/pages-common/addProject",
    "/pages/common/publishTask": "/subPackages/pages-common/publishTask",
    "/pages/common/taskDetail": "/subPackages/pages-common/taskDetail",
    "/pages/common/changePassword": "/subPackages/pages-common/changePassword",
    "/pages/common/noticeList": "/subPackages/pages-common/noticeList",
    "/pages/common/noticeDetail": "/subPackages/pages-common/noticeDetail",
    "/pages/common/messageList": "/subPackages/pages-common/messageList",
    "/pages/common/messageDetail": "/subPackages/pages-common/messageDetail",
    "/pages/common/helpCenter": "/subPackages/pages-common/helpCenter",
    "/pages/common/knowledgeList": "/subPackages/pages-common/knowledgeList",
    "/pages/common/knowledgeDetail": "/subPackages/pages-common/knowledgeDetail",
    "/pages/sales/taskReminder": "/subPackages/pages-sales/taskReminder",
    "/pages/sales/notification": "/subPackages/pages-sales/notification",
    "/pages/sales/knowledgeList": "/subPackages/pages-sales/knowledgeList",
    "/pages/sales/knowledgeDetail": "/subPackages/pages-sales/knowledgeDetail",
    "/pages/sales/messageList": "/subPackages/pages-sales/messageList",
    "/pages/sales/messageDetail": "/subPackages/pages-sales/messageDetail",
    "/pages/dispatch/schedule": "/subPackages/pages-dispatch/schedule",
    "/pages/dispatch/taskDetail": "/subPackages/pages-dispatch/taskDetail",
    "/pages/dispatch/publishTask": "/subPackages/pages-dispatch/publishTask",
    "/pages/dispatch/vehicleList": "/subPackages/pages-dispatch/vehicleList",
    "/pages/dispatch/availableVehicles": "/subPackages/pages-dispatch/availableVehicles",
    "/pages/dispatch/personnel": "/subPackages/pages-dispatch/personnel",
    "/pages/dispatch/onDutyStaff": "/subPackages/pages-dispatch/onDutyStaff",
    "/pages/dispatch/emergencyTeam": "/subPackages/pages-dispatch/emergencyTeam",
    "/pages/dispatch/emergencyStandby": "/subPackages/pages-dispatch/emergencyStandby",
    "/pages/dispatch/visualization": "/subPackages/pages-dispatch/visualization",
    "/pages/dispatch/noticeList": "/subPackages/pages-dispatch/noticeList",
    "/pages/dispatch/noticeDetail": "/subPackages/pages-dispatch/noticeDetail",
    "/pages/dispatch/notification": "/subPackages/pages-dispatch/notification",
    "/pages/construction/taskDetail": "/subPackages/pages-construction/taskDetail",
    "/pages/construction/dailyTask": "/subPackages/pages-construction/dailyTask",
    "/pages/construction/historyTask": "/subPackages/pages-construction/historyTask",
    "/pages/construction/tomorrowTask": "/subPackages/pages-construction/tomorrowTask",
    "/pages/construction/noticeList": "/subPackages/pages-construction/noticeList",
    "/pages/construction/noticeDetail": "/subPackages/pages-construction/noticeDetail",
    "/pages/construction/notification": "/subPackages/pages-construction/notification",
    # 被删除/合并的页面统一指向 common
    "/pages/sales/changePassword": "/subPackages/pages-common/changePassword",
    "/pages/sales/helpCenter": "/subPackages/pages-common/helpCenter",
    "/pages/dispatch/changePassword": "/subPackages/pages-common/changePassword",
    "/pages/dispatch/helpCenter": "/subPackages/pages-common/helpCenter",
    "/pages/construction/changePassword": "/subPackages/pages-common/changePassword",
    "/pages/construction/helpCenter": "/subPackages/pages-common/helpCenter",
    # tabBar 页
    "/pages/common/taskList": "/pages/task/task",
    "/pages/common/profile": "/pages/my/my",
    "/pages/sales/home": "/pages/home/home",
    "/pages/dispatch/home": "/pages/home/home",
    "/pages/dispatch/taskList": "/pages/task/task",
    "/pages/dispatch/myPage": "/pages/my/my",
    "/pages/construction/home": "/pages/home/home",
    "/pages/construction/taskList": "/pages/task/task",
    "/pages/construction/myPage": "/pages/my/my",
}

# tabBar 目标路径，需要把 navigateTo/reLaunch 改为 switchTab
TABBAR_PATHS = [
    "/pages/home/home",
    "/pages/task/task",
    "/pages/my/my",
]

# 扫描的文件后缀
EXTS = (".vue", ".ts", ".js")


def replace_paths(content: str) -> str:
    # 1. 替换路径字符串
    for old, new in PATH_REPLACEMENTS.items():
        content = content.replace(old, new)
    return content


def fix_tabbar_navigation(content: str) -> str:
    # 把指向 tabBar 页面的 navigateTo/reLaunch 改成 switchTab
    # 匹配 uni.navigateTo({ url: '...' }) 或 uni.reLaunch({ url: '...' })
    pattern = re.compile(
        r"uni\.(navigateTo|reLaunch)\(\{\s*url\s*:\s*['\"]([" + "".join(re.escape(p) for p in TABBAR_PATHS) + r"][^'\"]*)['\"]\s*\}\)"
    )

    def replacer(match):
        method = match.group(1)
        url = match.group(2)
        return f"uni.switchTab({{ url: '{url}' }})"

    # 由于 TABBAR_PATHS 是固定的简单字符串，直接用更简单的方式
    for path in TABBAR_PATHS:
        for method in ("navigateTo", "reLaunch"):
            content = re.sub(
                rf"uni\.{method}\(\{{\s*url\s*:\s*['\"]{re.escape(path)}[^'\"]*['\"]\s*\}}\)",
                lambda m, p=path: f"uni.switchTab({{ url: '{p}' }})",
                content,
            )
    return content


def process_file(filepath: str):
    with open(filepath, "r", encoding="utf-8") as f:
        content = f.read()

    new_content = replace_paths(content)
    new_content = fix_tabbar_navigation(new_content)

    if new_content != content:
        with open(filepath, "w", encoding="utf-8") as f:
            f.write(new_content)
        print(f"Updated: {filepath}")


def main():
    for dirpath, _, filenames in os.walk(ROOT):
        for filename in filenames:
            if filename.endswith(EXTS):
                process_file(os.path.join(dirpath, filename))


if __name__ == "__main__":
    main()
