#!/bin/bash

echo "================================"
echo "修复资产API接口"
echo "================================"

# 备份原文件
echo "步骤1: 备份原文件..."
cp src/main/java/com/it/rattan/monisuo/service/AssetService.java \
   src/main/java/com/it/rattan/monisuo/service/AssetService.java.backup

echo "✅ 备份完成"
echo ""

# 使用 sed 修改文件
echo "步骤2: 修改AssetService.java..."

# 1. 修改 totalAssets -> totalAsset
sed -i '' 's/put("totalAssets"/put("totalAsset"/g' \
    src/main/java/com/it/rattan/monisuo/service/AssetService.java

# 2. 修改 tradeValue -> tradeBalance
sed -i '' 's/put("tradeValue"/put("tradeBalance"/g' \
    src/main/java/com/it/rattan/monisuo/service/AssetService.java

# 3. 修改变量名
sed -i '' 's/BigDecimal tradeValue/BigDecimal tradeBalance/g' \
    src/main/java/com/it/rattan/monisuo/service/AssetService.java

sed -i '' 's/tradeValue = tradeValue/tradeBalance = tradeBalance/g' \
    src/main/java/com/it/rattan/monisuo/service/AssetService.java

sed -i '' 's/tradeValue\.add/tradeBalance.add/g' \
    src/main/java/com/it/rattan/monisuo/service/AssetService.java

sed -i '' 's/BigDecimal totalAssets/BigDecimal totalAsset/g' \
    src/main/java/com/it/rattan/monisuo/service/AssetService.java

sed -i '' 's/totalAssets = fund/totalAsset = fund/g' \
    src/main/java/com/it/rattan/monisuo/service/AssetService.java

sed -i '' 's/\.add(tradeValue)/.add(tradeBalance)/g' \
    src/main/java/com/it/rattan/monisuo/service/AssetService.java

echo "✅ 修改完成"
echo ""

# 编译
echo "步骤3: 编译项目..."
mvn clean package -DskipTests 2>&1 | tail -20

if [ $? -eq 0 ]; then
    echo "✅ 编译成功"
    echo ""
    
    echo "步骤4: 重启服务..."
    pkill -f monisuo-1.0.jar
    sleep 2
    
    export JAVA_HOME=/opt/homebrew/Cellar/openjdk@17/17.0.18/libexec/openjdk.jdk/Contents/Home
    export PATH=$JAVA_HOME/bin:$PATH
    nohup java -jar target/monisuo-1.0.jar --server.port=5010 > logs/app.log 2>&1 &
    
    echo "等待服务启动..."
    sleep 15
    
    echo "✅ 服务已重启"
    echo ""
    
    echo "步骤5: 测试验证..."
    ./test_asset_api.sh
else
    echo "❌ 编译失败"
    echo "恢复备份..."
    cp src/main/java/com/it/rattan/monisuo/service/AssetService.java.backup \
       src/main/java/com/it/rattan/monisuo/service/AssetService.java
fi
