#!/bin/bash
#============================================
# 物流服务部署脚本
#============================================

set -e

SERVICE_NAME="logistics-service"
SERVICE_PORT=8086
IMAGE_NAME="erp-java-backend/${SERVICE_NAME}"
CONTAINER_NAME="${SERVICE_NAME}"

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

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

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

# 检查Docker是否运行
check_docker() {
    if ! docker info > /dev/null 2>&1; then
        log_error "Docker未运行，请先启动Docker"
        exit 1
    fi
}

# 停止并删除旧容器
stop_container() {
    if docker ps -a --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
        log_info "停止旧容器..."
        docker stop ${CONTAINER_NAME} 2>/dev/null || true
        docker rm ${CONTAINER_NAME} 2>/dev/null || true
    fi
}

# 构建Docker镜像
build_image() {
    log_info "构建Docker镜像..."
    docker build -t ${IMAGE_NAME}:latest .
    docker tag ${IMAGE_NAME}:latest ${IMAGE_NAME}:$(date +%Y%m%d%H%M%S)
}

# 启动容器
start_container() {
    log_info "启动容器..."
    docker run -d \
        --name ${CONTAINER_NAME} \
        --restart unless-stopped \
        -p ${SERVICE_PORT}:8086 \
        -e DB_HOST=${DB_HOST:-111.229.80.149} \
        -e DB_PORT=${DB_PORT:-3306} \
        -e DB_NAME=${DB_NAME:-erp_db} \
        -e DB_USER=${DB_USER:-root} \
        -e DB_PASSWORD=${DB_PASSWORD:-nihao588+} \
        -e REDIS_HOST=${REDIS_HOST:-111.229.80.149} \
        -e REDIS_PORT=${REDIS_PORT:-6379} \
        -e REDIS_PASSWORD=${REDIS_PASSWORD:-Y(@r5tGk9\$Lp2} \
        -e NACOS_HOST=${NACOS_HOST:-111.229.80.149} \
        -e NACOS_PORT=${NACOS_PORT:-8848} \
        -e NACOS_NAMESPACE=${NACOS_NAMESPACE:-public} \
        -e JAVA_OPTS="-Xms256m -Xmx512m" \
        --health-cmd "curl -f http://localhost:8086/actuator/health || exit 1" \
        --health-interval=30s \
        --health-timeout=10s \
        --health-retries=3 \
        --health-start-period=60s \
        ${IMAGE_NAME}:latest

    log_info "容器已启动，等待健康检查..."
    sleep 30

    # 检查容器状态
    if docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
        log_info "容器运行正常"
    else
        log_error "容器启动失败，查看日志：docker logs ${CONTAINER_NAME}"
        exit 1
    fi
}

# 查看日志
show_logs() {
    docker logs -f ${CONTAINER_NAME}
}

# 查看状态
show_status() {
    echo "=== 容器状态 ==="
    docker ps -a --filter "name=${CONTAINER_NAME}" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
    echo ""
    echo "=== 健康检查 ==="
    curl -s http://localhost:${SERVICE_PORT}/actuator/health | python3 -m json.tool 2>/dev/null || echo "无法获取健康状态"
}

# 执行数据库迁移
run_migration() {
    log_info "执行数据库初始化..."
    docker exec -it ${CONTAINER_NAME} bash -c "mysql -h\${DB_HOST} -u\${DB_USER} -p\${DB_PASSWORD} \${DB_NAME} < /app/db/init.sql" || true
}

# 主流程
main() {
    log_info "开始部署 ${SERVICE_NAME}..."

    check_docker
    stop_container
    build_image
    start_container

    log_info "部署完成！"
    echo ""
    echo "服务地址: http://localhost:${SERVICE_PORT}"
    echo "API文档: http://localhost:${SERVICE_PORT}/doc.html"
    echo ""
    echo "常用命令："
    echo "  查看日志: ./deploy.sh logs"
    echo "  查看状态: ./deploy.sh status"
    echo "  停止服务: ./deploy.sh stop"
    echo "  重启服务: ./deploy.sh restart"
}

# 根据参数执行不同操作
case "${1:-deploy}" in
    deploy)
        main
        ;;
    start)
        start_container
        ;;
    stop)
        stop_container
        log_info "服务已停止"
        ;;
    restart)
        stop_container
        start_container
        ;;
    logs)
        show_logs
        ;;
    status)
        show_status
        ;;
    rebuild)
        stop_container
        build_image
        start_container
        ;;
    *)
        echo "用法: $0 {deploy|start|stop|restart|logs|status|rebuild}"
        exit 1
        ;;
esac
