#!/bin/bash

# Report Service 部署脚本

set -e

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

# 配置
SERVICE_NAME="report-service"
SERVICE_PORT=8084
DOCKER_IMAGE="erp-registry.cn-hangzhou.cr.aliyuncs.com/erp/report-service:1.0.0"
NAMESPACE="erp"

echo -e "${GREEN}======================================"
echo -e "  Report Service 部署脚本"
echo -e "======================================${NC}"

# 构建项目
build_project() {
    echo -e "${YELLOW}[1/5] 构建项目...${NC}"
    cd "$(dirname "$0")/.."
    mvn clean package -DskipTests -U
    echo -e "${GREEN}构建完成${NC}"
}

# 构建Docker镜像
build_docker() {
    echo -e "${YELLOW}[2/5] 构建Docker镜像...${NC}"
    cd "$(dirname "$0")/.."
    docker build -t "$DOCKER_IMAGE" -f deploy/Dockerfile .
    echo -e "${GREEN}Docker镜像构建完成${NC}"
}

# 推送Docker镜像
push_docker() {
    echo -e "${YELLOW}[3/5] 推送Docker镜像...${NC}"
    docker push "$DOCKER_IMAGE"
    echo -e "${GREEN}Docker镜像推送完成${NC}"
}

# 部署到K8s
deploy_k8s() {
    echo -e "${YELLOW}[4/5] 部署到Kubernetes...${NC}"
    kubectl apply -f deploy/k8s-deployment.yaml -n "$NAMESPACE"
    echo -e "${GREEN}K8s部署完成${NC}"
}

# 等待服务就绪
wait_for_service() {
    echo -e "${YELLOW}[5/5] 等待服务就绪...${NC}"
    kubectl rollout status deployment/report-service -n "$NAMESPACE" --timeout=300s
    
    # 检查健康状态
    for i in {1..30}; do
        HEALTH=$(kubectl get pods -n "$NAMESPACE" -l app=report-service -o jsonpath='{.items[0].status.phase}')
        if [ "$HEALTH" == "Running" ]; then
            echo -e "${GREEN}服务已就绪${NC}"
            return 0
        fi
        sleep 2
    done
    
    echo -e "${RED}服务启动超时${NC}"
    return 1
}

# 显示服务状态
show_status() {
    echo -e "${GREEN}======================================"
    echo -e "  服务状态"
    echo -e "======================================${NC}"
    kubectl get pods -n "$NAMESPACE" -l app=report-service
    echo ""
    kubectl get svc -n "$NAMESPACE" -l app=report-service
}

# 主流程
main() {
    case "${1:-deploy}" in
        build)
            build_project
            ;;
        docker)
            build_project
            build_docker
            ;;
        push)
            build_project
            build_docker
            push_docker
            ;;
        deploy)
            build_project
            build_docker
            push_docker
            deploy_k8s
            wait_for_service
            show_status
            ;;
        status)
            show_status
            ;;
        restart)
            kubectl rollout restart deployment/report-service -n "$NAMESPACE"
            wait_for_service
            show_status
            ;;
        scale)
            kubectl scale deployment/report-service --replicas="${2:-2}" -n "$NAMESPACE"
            ;;
        logs)
            kubectl logs -f deployment/report-service -n "$NAMESPACE" "${@:2}"
            ;;
        *)
            echo "用法: $0 {build|docker|push|deploy|status|restart|scale|logs}"
            exit 1
            ;;
    esac
}

main "$@"
