
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
OUTPUT_FOLDER="${SCRIPT_DIR}/加载图输出"
LOADINGBG_FOLDER="/storage/emulated/0/Android/data/com.tencent.tmgp.pubgmhd/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/ImageDownloadV3/LoadingBG"
SUPPORT_IMG_TYPES=("png" "jpg" "jpeg" "bmp" "webp")
TOTAL_TARGET=61

TARGET_ALL=(
    "139f7ca4602884c210afd4193459d03b" "33b643f557f43d5b254340100d981d10" "350eef5300f19b90cb99babf6d97b038"
    "6800fb237e5eb16cd726bb9201b07051" "6f1f2da5655591f3e414f9cb2f637364" "8450181c81be27e448abc8b2eb24b49b"
    "9bb41bcd562fb5e08f8efbf064957d60" "d1f95cf4b3f8990d8b0444575a1fbb61" "dc9de740a5e4939f041c7c33fe6e5abd"
    "2b3ee26822e44e9ee5fae90181d534d3" "33d6d44faa806c43197c2a92aabc7460" "59f95ac8c3555e4af9ef92cd881f0612"
    "6e0156c739f31797a89122c009afb3fb" "711e059443369ce055b46dc56f9cf40a" "864f05443816f3c3f9aa9b0fdceb7f38"
    "a26516845498fc100bbc825b7b68af7c" "bdb5cb02a2256317c81129c65d9e417b" "de97370724f88a85edd5866d2c3182c3"
    "ffc29f7b097133e8f3d39ee61269cb91" "1307d8cb164b1716150b1193661d419e" "43c0dd62e8ff2873ab30390dfff69bec"
    "453adf21a45ebd52f922bae31adfb2ce" "68db71d6258d3baed1064cb9d26dabe8" "712a425e67ea455e5c0e1a010f2beed2"
    "8aefdd285ef0b319c6c654cebe042c00" "984c5a0871c77b4be3f35e50b5562169" "a7cda6b5093f2ed4432a65fdfc1e3ae8"
    "df257341f217aa7c08d73cc0f0c1ee6d" "fc97d5aec6ecb8150a455e5c0e1a010f2beed2" "fdbf63af94954971ad1fea90533664d8"
    "08c12c2475fff37179438cc4f325f08f" "28c4eae03701eb484686d5b1d4f9c0e8" "368d5e16e8498530a4551a883b4d532d"
    "52a710e8c12b81f03f91b32a49e4b587" "685aacc44cfa18a28d38c4a07cbc1c9a" "7319d40ff352f0f743fb0337253366c3"
    "90c97b7b09f2921ba967bdac17e0633e" "a978a939e073614558b000d814a847a2" "e28867b2c4fd1f02db9d61427d8284ab"
    "3d0669e39a72cbcaffbf11e15e62c4ce" "461f2f063269ccd64880179ae909bd37" "4e014cdb4f6c86fb58fb53f03bf4a51b"
    "75a9e7dc45a1a4923e414cdb4f6c86fb" "8f399605f7eaefc627b4ad657686403d" "919bfd8d9c899b8ccbeec86f25435864"
    "ae33b94972013f4dcaf978c9f2df79c5" "eb0529ed435d48cada1e8ccd524688a4" "0ba735da8cdf5051002edf4e081f4dac"
    "15af1123e6120451c93ddd34eb6f9568" "252418a57d99663ca1e3a88b74e583e7" "77fe6105888e1c96f2cae3eae8394140"
    "987c58e6d4ce229193e7c8664ef66ad9" "a67bcfa3f48e06d8f37206b57fbf85f9" "b91ada8a1edb5fc4351f6943e23f95d1"
    "e56bcefea38cb6bae624bbeedbef6a01" "ed7decac5bd9bf7f527508b4e52d95d2" "7e2deab32ce95d434b42639c74fdba12"
    "9a1a58aaf8002720b19a4cc5cecf28e0" "b99fb15b059585b2e437ff5b3690a676" "fc85adec013f896f21544c549fb35960"
    "059b9b9068b8d0d806a5e134fff970ce"
)

clear_output_folder() {
    if [ -d "$OUTPUT_FOLDER" ]; then
        rm -rf "${OUTPUT_FOLDER}/"*
        echo -e "\033[38;2;100;200;255m📂 已清空加载图输出目录：$OUTPUT_FOLDER\033[0m"
    else
        mkdir -p "$OUTPUT_FOLDER"
        echo -e "\033[38;2;100;200;255m📂 已创建加载图输出目录：$OUTPUT_FOLDER\033[0m"
    fi
}

get_gradient_color() {
    local index=$1
    local total=$2
    local r=$((255 - (255 * index / total)))
    local g=128
    local b=$((255 * index / total))
    echo -ne "\033[38;2;${r};${g};${b}m"
}

parse_range() {
    local input="$1"
    local result=()
    for part in $input; do
        if [[ "$part" =~ ^[0-9]+-[0-9]+$ ]]; then
            start=${part%-*}
            end=${part#*-}
            start=$((10#$start))
            end=$((10#$end))
            for ((i=start; i<=end; i++)); do
                result+=("$i")
            done
        else
            result+=("$part")
        fi
    done
    echo "$(echo "${result[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' ')"
}

get_file_size() {
    local file="$1"
    local size=$(ls -lh "$file" | awk '{print $5}')
    echo "$size"
}

convert_size_to_bytes() {
    local size="$1"
    local num=$(echo "$size" | sed 's/[^0-9.]//g')
    local unit=$(echo "$size" | sed 's/[0-9.]//g' | tr '[:lower:]' '[:upper:]')
    case "$unit" in
        K) num=$(echo "$num * 1024" | bc) ;;
        M) num=$(echo "$num * 1024 * 1024" | bc) ;;
        G) num=$(echo "$num * 1024 * 1024 * 1024" | bc) ;;
    esac
    echo "$num"
}

convert_bytes_to_human() {
    local bytes="$1"
    if (( $(echo "$bytes >= 1024*1024*1024" | bc -l) )); then
        echo "$(echo "scale=1; $bytes / (1024*1024*1024)" | bc)G"
    elif (( $(echo "$bytes >= 1024*1024" | bc -l) )); then
        echo "$(echo "scale=1; $bytes / (1024*1024)" | bc)M"
    elif (( $(echo "$bytes >= 1024" | bc -l) )); then
        echo "$(echo "scale=1; $bytes / 1024" | bc)K"
    else
        echo "${bytes}B"
    fi
}

calculate_gen_info() {
    local src_files=("$@")
    local total_src=${#src_files[@]}
    local per_file=$((TOTAL_TARGET / total_src))
    local remain=$((TOTAL_TARGET % total_src))
    local total_bytes=0
    local purple="\033[38;2;150;0;255m"
    local green="\033[38;2;0;255;0m"
    local cyan="\033[38;2;100;255;255m"
    local reset="\033[0m"

    echo -e "\n\033[36m📄 文件信息：\033[0m"
    for ((i=0; i<total_src; i++)); do
        local file="${src_files[$i]}"
        local size=$(get_file_size "$file")
        local size_num=$(echo "$size" | sed 's/[^0-9.]//g')
        local size_unit=$(echo "$size" | sed 's/[0-9.]//g')
        local gen_count=$per_file
        if [ $i -lt $remain ]; then
            gen_count=$((gen_count + 1))
        fi
        local size_bytes=$(convert_size_to_bytes "$size")
        local req_bytes=$(echo "$size_bytes * $gen_count" | bc)
        local req_human=$(convert_bytes_to_human "$req_bytes")
        total_bytes=$(echo "$total_bytes + $req_bytes" | bc)
        if [ $remain -gt 0 ] && [ $i -eq $((total_src - 1)) ]; then
            echo -e "文件大小：${purple}$size_num${reset}$size_unit  将会生成${green}$gen_count${reset}个文件，需要内存${cyan}$req_human${reset}"
            echo -e "剩余${green}$remain${reset}个文件，随机选择"
        else
            echo -e "文件大小：${purple}$size_num${reset}$size_unit  将会生成${green}$gen_count${reset}个文件，需要内存${cyan}$req_human${reset}"
        fi
    done
    local total_human=$(convert_bytes_to_human "$total_bytes")
    echo -e "\n总计需要内存${cyan}$total_human${reset}"
    echo -n "是否继续？继续回车："
    read -r confirm
}

check_root() {
    if [ "$(id -u)" -eq 0 ]; then
        echo -e "\033[38;2;0;255;0m✅ 当前为Root权限，支持自动替换\033[0m"
        return 0
    else
        echo -e "\033[38;2;255;200;0m⚠️ 当前为非Root权限，需手动替换文件\033[0m"
        return 1
    fi
}

filter_img_files() {
    local files=("$@")
    local filtered=()
    for file in "${files[@]}"; do
        local ext="${file##*.}"
        for type in "${SUPPORT_IMG_TYPES[@]}"; do
            if [[ "$ext" == "$type" || "$ext" == "${type^^}" ]]; then
                filtered+=("$file")
                break
            fi
        done
        if [[ "$file" == *"/"* && ! "$file" =~ \. ]]; then
            filtered+=("$file")
        fi
    done
    filtered=($(echo "${filtered[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))
    echo "${filtered[@]}"
}

show_list_with_gradient() {
    local items=("$@")
    local total=${#items[@]}
    for ((i=0; i<total; i++)); do
        local color=$(get_gradient_color $i $total)
        local reset="\033[0m"
        echo -e "${color}[$((i+1))] ${items[$i]}${reset}"
    done
}

specify_path() {
    local input="$1"
    local files=()
    local paths=($input)
    
    for path in "${paths[@]}"; do
        if [[ ! "$path" =~ ^$SCRIPT_DIR/ ]]; then
            path="${SCRIPT_DIR}/${path}"
        fi
        local real_p=$(readlink -f "$path" 2>/dev/null || echo "$path")
        
        if [ -f "$real_p" ] && [[ "$real_p" =~ ^$SCRIPT_DIR/ ]]; then
            files+=("$real_p")
            echo -e "\033[38;2;0;255;0m✅ 检测到文件：$real_p\033[0m"
        elif [ -d "$real_p" ] && [[ "$real_p" =~ ^$SCRIPT_DIR/ ]]; then
            echo -e "\033[38;2;100;200;255m📂 检测到文件夹，递归搜索${real_p}下文件...\033[0m"
            while IFS= read -r file; do
                [ -f "$file" ] && files+=("$file")
            done < <(find "$real_p" -type f ! -path "${OUTPUT_FOLDER}/*")
        else
            echo -e "\033[38;2;255;100;100m⚠️  路径$path无效或不在脚本目录内，已跳过\033[0m"
        fi
    done
    
    files=($(filter_img_files "${files[@]}"))
    echo "${files[@]}"
}

precision_search() {
    local keyword="$1"
    local files=()
    local keywords=($(parse_range "$keyword"))
    for kw in "${keywords[@]}"; do
        while IFS= read -r file; do
            [ -f "$file" ] && files+=("$file")
        done < <(find "$SCRIPT_DIR" -type f -name "$kw" ! -path "${OUTPUT_FOLDER}/*")
    done
    files=($(filter_img_files "${files[@]}"))
    echo "${files[@]}"
}

fuzzy_search() {
    local keyword="$1"
    local files=()
    local keywords=($(parse_range "$keyword"))
    for kw in "${keywords[@]}"; do
        while IFS= read -r file; do
            [ -f "$file" ] && files+=("$file")
        done < <(find "$SCRIPT_DIR" -type f -name "*${kw}*" ! -path "${OUTPUT_FOLDER}/*")
    done
    files=($(filter_img_files "${files[@]}"))
    echo "${files[@]}"
}

generate_loading_imgs() {
    local src_files=("$@")
    local total_src=${#src_files[@]}
    local per_file=$((TOTAL_TARGET / total_src))
    local remain=$((TOTAL_TARGET % total_src))
    
    mkdir -p "$OUTPUT_FOLDER"
    echo -e "\n\033[38;2;100;200;255m🚀 开始生成${TOTAL_TARGET}个加载图文件...\033[0m"
    
    local success=0
    local idx=0
    for ((i=0; i<total_src; i++)); do
        local src="${src_files[$i]}"
        local gen_count=$per_file
        [ $i -lt $remain ] && gen_count=$((gen_count+1))
        
        for ((j=0; j<gen_count; j++)); do
            [ $idx -ge $TOTAL_TARGET ] && break
            local target="${OUTPUT_FOLDER}/${TARGET_ALL[$idx]}"
            cp -f "$src" "$target" 2>/dev/null && success=$((success+1))
            idx=$((idx+1))
        done
    done
    
    echo -e "\n🎉 生成完成：\033[38;2;0;255;0m成功${success}个\033[0m | \033[38;2;255;0;0m失败$((TOTAL_TARGET-success))个\033[0m"
    echo -e "\033[38;2;100;200;255m📁 输出目录：$OUTPUT_FOLDER\033[0m"
}

auto_replace() {
    if check_root; then
        echo -e "\n\033[38;2;100;200;255m📂 开始自动替换到游戏目录...\033[0m"
        mkdir -p "$LOADINGBG_FOLDER"
        rm -rf "${LOADINGBG_FOLDER}/"*
        cp -f "${OUTPUT_FOLDER}/"* "$LOADINGBG_FOLDER/" 2>/dev/null
        echo -e "\033[38;2;0;255;0m✅ 自动替换完成\033[0m"
    fi
}

select_files() {
    local prompt="$1"
    local -n selected_arr=$2
    local count=${#SEARCHED_FILES[@]}
    
    while true; do
        echo -n "$prompt"
        read -r input
        [ -z "$input" ] && input="1"
        
        local nums=($(parse_range "$input"))
        local valid=0
        selected_arr=()
        for num in "${nums[@]}"; do
            if ! [[ "$num" =~ ^[0-9]+$ ]] || [ "$num" -lt 1 ] || [ "$num" -gt "$count" ]; then
                echo -e "\033[38;2;255;100;100m⚠️  序号$num无效，已跳过\033[0m"
                continue
            fi
            local file="${SEARCHED_FILES[$((num-1))]}"
            selected_arr+=("$file")
            echo -e "\033[38;2;0;255;0m✅ 选中：$file\033[0m"
            valid=1
        done
        
        if [ $valid -eq 1 ]; then
            calculate_gen_info "${selected_arr[@]}"
            return 0
        else
            echo -e "\033[38;2;255;0;0m❌ 未选中任何有效文件，请重新输入！\033[0m"
        fi
    done
}

main() {
    clear
    clear_output_folder
    
    echo -e "\033[38;2;255;150;0m==================== 和平精英加载图替换工具 ====================\033[0m"
    check_root
    
    echo -e "\n请选择文件获取方式："
    echo -e "\033[38;2;255;100;100m[1] 精准搜索（完全匹配文件名，支持连号/多关键词）\033[0m"
    echo -e "\033[38;2;100;200;255m[2] 模糊搜索（文件名包含关键词，支持连号/多关键词）\033[0m"
    echo -e "\033[38;2;100;255;100m[3] 指定路径（直接输入文件完整路径）\033[0m"
    echo -n "输入选项编号（1-3）："
    read -r mode
    
    local files=()
    case "$mode" in
        1)
            echo -n "输入精准搜索关键词（例：0 1-3 png）："
            read -r kw
            files=($(precision_search "$kw"))
            ;;
        2)
            echo -n "输入模糊搜索关键词（例：0-2 jpg 1）："
            read -r kw
            files=($(fuzzy_search "$kw"))
            ;;
        3)
            echo -n "输入文件完整路径（多个路径用空格分隔）："
            read -r path
            files=($(specify_path "$path"))
            ;;
        *)
            echo -e "\033[38;2;255;0;0m❌ 选项错误，脚本退出\033[0m"
            exit 1
            ;;
    esac
    
    if [ ${#files[@]} -eq 0 ]; then
        echo -e "\033[38;2;255;0;0m❌ 未找到任何有效文件\033[0m"
        exit 1
    fi
    
    export SEARCHED_FILES=("${files[@]}")
    echo -e "\n\033[38;2;0;255;0m✅ 共搜索到${#files[@]}个有效文件：\033[0m"
    show_list_with_gradient "${files[@]}"
    
    local selected_files=()
    select_files "输入选择的序号（支持连号如1-5，空格分隔）：" selected_files
    
    generate_loading_imgs "${selected_files[@]}"
    auto_replace
    
    echo -e "\n\033[38;2;100;200;255m📌 非Root替换指引：\033[0m"
    echo "1. 打开MT管理器，进入${OUTPUT_FOLDER}"
    echo "2. 全选文件，复制到${LOADINGBG_FOLDER}"
    echo "3. 覆盖原有文件完成替换"
}

main
echo -e "\n操作完成，按回车键退出..."
read -r
exit 0
