#!/bin/bash

# 智慧畜牧业小程序矩阵构建脚本
# 用于批量构建所有小程序应用

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 小程序应用列表
APPS=(
    "farming-manager:养殖管理小程序"
    "cattle-trading:牛只交易小程序"
    "beef-mall:牛肉商城小程序"
    "bank-supervision:银行监管小程序"
    "insurance-supervision:保险监管小程序"
)

# 支持的平台
PLATFORMS=(
    "mp-weixin:微信小程序"
    "mp-alipay:支付宝小程序"
    "mp-baidu:百度小程序"
    "mp-toutiao:字节跳动小程序"
    "mp-qq:QQ小程序"
    "h5:H5网页版"
)

# 检查环境
check_environment() {
    log_info "检查构建环境..."
    
    # 检查 Node.js
    if ! command -v node &> /dev/null; then
        log_error "Node.js 未安装"
        exit 1
    fi
    
    # 检查 npm
    if ! command -v npm &> /dev/null; then
        log_error "npm 未安装"
        exit 1
    fi
    
    # 检查项目目录
    if [ ! -d "mini_program" ]; then
        log_error "mini_program 目录不存在"
        exit 1
    fi
    
    # 检查 package.json
    if [ ! -f "mini_program/package.json" ]; then
        log_error "package.json 文件不存在"
        exit 1
    fi
    
    log_success "环境检查通过"
}

# 安装依赖
install_dependencies() {
    log_info "安装项目依赖..."
    
    cd mini_program
    
    if [ -f "package-lock.json" ]; then
        npm ci --silent
    else
        npm install --silent
    fi
    
    log_success "依赖安装完成"
    cd ..
}

# 清理构建文件
clean_build() {
    log_info "清理构建文件..."
    
    cd mini_program
    
    # 清理构建目录
    rm -rf dist/
    rm -rf unpackage/
    
    # 清理各个小程序的构建文件
    for app_info in "${APPS[@]}"; do
        app_dir=$(echo $app_info | cut -d: -f1)
        if [ -d "$app_dir/dist" ]; then
            rm -rf "$app_dir/dist"
        fi
        if [ -d "$app_dir/unpackage" ]; then
            rm -rf "$app_dir/unpackage"
        fi
    done
    
    log_success "清理完成"
    cd ..
}

# 生成构建信息
generate_build_info() {
    log_info "生成构建信息..."
    
    local build_time=$(date "+%Y-%m-%d %H:%M:%S")
    local git_commit=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
    local git_branch=$(git branch --show-current 2>/dev/null || echo "unknown")
    local build_number=${BUILD_NUMBER:-$(date +"%Y%m%d%H%M%S")}
    
    cat > mini_program/build-info.json << EOF
{
  "buildTime": "$build_time",
  "buildNumber": "$build_number",
  "gitCommit": "$git_commit",
  "gitBranch": "$git_branch",
  "nodeVersion": "$(node --version)",
  "npmVersion": "$(npm --version)",
  "environment": "${BUILD_ENV:-production}"
}
EOF
    
    log_success "构建信息生成完成"
}

# 构建单个应用
build_app() {
    local app_dir=$1
    local app_name=$2
    local platform=$3
    local platform_name=$4
    
    log_info "构建 ${app_name} - ${platform_name}..."
    
    cd mini_program
    
    # 设置当前构建的应用
    export UNI_INPUT_DIR="$app_dir"
    
    # 执行构建命令
    case $platform in
        "mp-weixin")
            npm run build:mp-weixin --silent
            ;;
        "mp-alipay")
            npm run build:mp-alipay --silent
            ;;
        "mp-baidu")
            npm run build:mp-baidu --silent
            ;;
        "mp-toutiao")
            npm run build:mp-toutiao --silent
            ;;
        "mp-qq")
            npm run build:mp-qq --silent
            ;;
        "h5")
            npm run build:h5 --silent
            ;;
        *)
            log_error "不支持的平台: $platform"
            cd ..
            return 1
            ;;
    esac
    
    # 检查构建结果
    if [ $? -eq 0 ]; then
        log_success "${app_name} - ${platform_name} 构建成功"
        
        # 移动构建文件到指定目录
        if [ -d "dist/build/$platform" ]; then
            mkdir -p "builds/$app_dir/$platform"
            cp -r "dist/build/$platform/"* "builds/$app_dir/$platform/"
        fi
    else
        log_error "${app_name} - ${platform_name} 构建失败"
        cd ..
        return 1
    fi
    
    cd ..
}

# 构建所有应用
build_all_apps() {
    local target_platform=$1
    local target_app=$2
    
    log_info "开始批量构建..."
    
    # 创建构建输出目录
    mkdir -p mini_program/builds
    
    local success_count=0
    local total_count=0
    
    for app_info in "${APPS[@]}"; do
        app_dir=$(echo $app_info | cut -d: -f1)
        app_name=$(echo $app_info | cut -d: -f2)
        
        # 如果指定了特定应用，只构建该应用
        if [ -n "$target_app" ] && [ "$target_app" != "$app_dir" ]; then
            continue
        fi
        
        # 检查应用目录是否存在
        if [ ! -d "mini_program/$app_dir" ]; then
            log_warning "应用目录不存在: $app_dir"
            continue
        fi
        
        for platform_info in "${PLATFORMS[@]}"; do
            platform=$(echo $platform_info | cut -d: -f1)
            platform_name=$(echo $platform_info | cut -d: -f2)
            
            # 如果指定了特定平台，只构建该平台
            if [ -n "$target_platform" ] && [ "$target_platform" != "$platform" ]; then
                continue
            fi
            
            total_count=$((total_count + 1))
            
            if build_app "$app_dir" "$app_name" "$platform" "$platform_name"; then
                success_count=$((success_count + 1))
            fi
        done
    done
    
    log_info "构建完成: $success_count/$total_count 成功"
    
    if [ $success_count -eq $total_count ]; then
        log_success "所有应用构建成功！"
        return 0
    else
        log_warning "部分应用构建失败"
        return 1
    fi
}

# 生成构建报告
generate_build_report() {
    log_info "生成构建报告..."
    
    local report_file="mini_program/builds/build-report.html"
    local build_time=$(date "+%Y-%m-%d %H:%M:%S")
    
    cat > "$report_file" << EOF
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>构建报告 - 智慧畜牧业小程序矩阵</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .header { background: #2E8B57; color: white; padding: 20px; border-radius: 8px; }
        .summary { margin: 20px 0; padding: 15px; background: #f5f5f5; border-radius: 8px; }
        .apps { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
        .app-card { border: 1px solid #ddd; border-radius: 8px; padding: 15px; }
        .app-title { font-size: 18px; font-weight: bold; margin-bottom: 10px; }
        .platform { margin: 5px 0; padding: 5px 10px; border-radius: 4px; }
        .success { background: #d4edda; color: #155724; }
        .error { background: #f8d7da; color: #721c24; }
        .footer { margin-top: 30px; text-align: center; color: #666; }
    </style>
</head>
<body>
    <div class="header">
        <h1>智慧畜牧业小程序矩阵 - 构建报告</h1>
        <p>构建时间: $build_time</p>
    </div>
    
    <div class="summary">
        <h2>构建概要</h2>
        <p>本次构建包含 ${#APPS[@]} 个小程序应用，支持 ${#PLATFORMS[@]} 个平台</p>
    </div>
    
    <div class="apps">
EOF

    # 添加每个应用的构建状态
    for app_info in "${APPS[@]}"; do
        app_dir=$(echo $app_info | cut -d: -f1)
        app_name=$(echo $app_info | cut -d: -f2)
        
        cat >> "$report_file" << EOF
        <div class="app-card">
            <div class="app-title">$app_name</div>
EOF
        
        for platform_info in "${PLATFORMS[@]}"; do
            platform=$(echo $platform_info | cut -d: -f1)
            platform_name=$(echo $platform_info | cut -d: -f2)
            
            if [ -d "mini_program/builds/$app_dir/$platform" ]; then
                echo "            <div class=\"platform success\">✓ $platform_name</div>" >> "$report_file"
            else
                echo "            <div class=\"platform error\">✗ $platform_name</div>" >> "$report_file"
            fi
        done
        
        echo "        </div>" >> "$report_file"
    done
    
    cat >> "$report_file" << EOF
    </div>
    
    <div class="footer">
        <p>© 2024 智慧畜牧业小程序矩阵</p>
    </div>
</body>
</html>
EOF
    
    log_success "构建报告已生成: $report_file"
}

# 压缩构建文件
compress_builds() {
    log_info "压缩构建文件..."
    
    cd mini_program/builds
    
    local archive_name="xlxumu-miniprogram-builds-$(date +%Y%m%d_%H%M%S).tar.gz"
    
    tar -czf "$archive_name" */
    
    log_success "构建文件已压缩: builds/$archive_name"
    cd ../..
}

# 显示帮助信息
show_help() {
    echo "智慧畜牧业小程序矩阵构建脚本"
    echo ""
    echo "用法:"
    echo "  $0 [选项] [平台] [应用]"
    echo ""
    echo "选项:"
    echo "  -h, --help     显示帮助信息"
    echo "  -c, --clean    清理构建文件"
    echo "  -r, --report   生成构建报告"
    echo "  -z, --zip      压缩构建文件"
    echo ""
    echo "参数:"
    echo "  平台    目标平台 (mp-weixin|mp-alipay|mp-baidu|mp-toutiao|mp-qq|h5)"
    echo "  应用    目标应用 (farming-manager|cattle-trading|beef-mall|bank-supervision|insurance-supervision)"
    echo ""
    echo "示例:"
    echo "  $0                           # 构建所有应用的所有平台"
    echo "  $0 mp-weixin                 # 构建所有应用的微信小程序版本"
    echo "  $0 mp-weixin farming-manager # 构建养殖管理小程序的微信版本"
    echo "  $0 --clean                   # 清理构建文件"
    echo "  $0 --report                  # 生成构建报告"
    echo ""
    echo "支持的平台:"
    for platform_info in "${PLATFORMS[@]}"; do
        platform=$(echo $platform_info | cut -d: -f1)
        platform_name=$(echo $platform_info | cut -d: -f2)
        echo "  $platform$(printf '%*s' $((15-${#platform})) '') $platform_name"
    done
    echo ""
    echo "支持的应用:"
    for app_info in "${APPS[@]}"; do
        app_dir=$(echo $app_info | cut -d: -f1)
        app_name=$(echo $app_info | cut -d: -f2)
        echo "  $app_dir$(printf '%*s' $((20-${#app_dir})) '') $app_name"
    done
}

# 主函数
main() {
    local clean_only=false
    local report_only=false
    local compress_only=false
    local target_platform=""
    local target_app=""
    
    # 解析参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            -c|--clean)
                clean_only=true
                shift
                ;;
            -r|--report)
                report_only=true
                shift
                ;;
            -z|--zip)
                compress_only=true
                shift
                ;;
            mp-weixin|mp-alipay|mp-baidu|mp-toutiao|mp-qq|h5)
                target_platform=$1
                shift
                ;;
            farming-manager|cattle-trading|beef-mall|bank-supervision|insurance-supervision)
                target_app=$1
                shift
                ;;
            *)
                log_error "未知参数: $1"
                show_help
                exit 1
                ;;
        esac
    done
    
    # 检查环境
    check_environment
    
    # 执行相应操作
    if [ "$clean_only" = true ]; then
        clean_build
        exit 0
    fi
    
    if [ "$report_only" = true ]; then
        generate_build_report
        exit 0
    fi
    
    if [ "$compress_only" = true ]; then
        compress_builds
        exit 0
    fi
    
    # 执行完整构建流程
    log_info "开始构建智慧畜牧业小程序矩阵"
    
    # 清理旧文件
    clean_build
    
    # 生成构建信息
    generate_build_info
    
    # 安装依赖
    install_dependencies
    
    # 构建所有应用
    if build_all_apps "$target_platform" "$target_app"; then
        # 生成构建报告
        generate_build_report
        
        # 压缩构建文件
        compress_builds
        
        log_success "构建完成！"
        exit 0
    else
        log_error "构建失败！"
        exit 1
    fi
}

# 错误处理
error_handler() {
    local line_number=$1
    log_error "脚本在第 $line_number 行出错"
    exit 1
}

# 设置错误处理
trap 'error_handler $LINENO' ERR

# 执行主函数
main "$@"