#!/ 异步文件上传功能集成测试脚本

# 测试说明
# 本脚本用于测试异步文件上传功能的完整流程
# 包括: 文件上传、轮询状态、 数据保存

# 测试环境
BASE_URL="http://localhost:8080"
TOKEN=""

# 颜色输出
RED='\033[0;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 获取 Token
echo -e "${YELLOW}开始获取 Token...${NC}"
TOKEN_RESPONSE=$(curl -s -X POST "${BASE_URL}/login/test?username=admin&password=admin123")
TOKEN=$(echo "$TOKEN_RESPONSE" | grep -o '"token":"[^"]*' | sed 's/.*:\([^"]*\).*/\1/')

if [ -z "$TOKEN" ]; then
    echo -e "${RED}获取 Token 失败${NC}"
    exit 1
fi
echo -e "${GREEN}Token 获取成功${NC}"

# 准备测试数据
echo -e "${YELLOW}准备测试项目...${NC}"

# 创建测试项目
PROJECT_DATA=$(cat <<EOF
{
  "projectName": "测试项目-$(date +%Y%m%d)",
  "projectStatus": "进行中"
}
EOF
)

CREATE_RESPONSE=$(curl -s -X POST "${BASE_URL}/ccdi/project" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "$PROJECT_DATA")

PROJECT_ID=$(echo "$CREATE_RESPONSE" | grep -o '"projectId":[^,]*' | sed 's/.*:\([^"]*\).*/\1/')

if [ -z "$PROJECT_ID" ]; then
    echo -e "${RED}创建项目失败${NC}"
    exit 1
fi
echo -e "${GREEN}项目创建成功: ID=${PROJECT_ID}${NC}"

# 创建测试文件
TEST_FILE="/tmp/test_bank_statement_$(date +%s).xlsx"
echo "账号,日期,金额,摘要" > "$TEST_FILE"
echo "622xxx,2024-01-01,1000.00,测试交易1" >> "$TEST_FILE"
echo "623xxx,2024-01-02,2000.00,测试交易2" >> "$TEST_FILE"
echo "622xxx,2024-01-03,3000.00,测试交易3" >> "$TEST_FILE"

# 测试文件上传
echo -e "${YELLOW}测试文件上传...${NC}"
UPLOAD_RESPONSE=$(curl -s -X POST "${BASE_URL}/ccdi/file-upload/batch" \
  -H "Authorization: Bearer ${TOKEN}" \
  -F "projectId=${PROJECT_ID}" \
  -F "files[]=@${TEST_FILE};type=text/plain")

BATCH_ID=$(echo "$UPLOAD_RESPONSE" | grep -o '"data":"[^"]*' | sed 's/.*:\([^"]*\).*/\1/')

if [ -z "$BATCH_ID" ]; then
    echo -e "${RED}文件上传失败${NC}"
    exit 1
fi
echo -e "${GREEN}文件上传成功: Batch ID=${BATCH_ID}${NC}"

# 等待处理完成
echo -e "${YELLOW}等待文件处理...${NC}"
sleep 10

# 查询上传记录
RECORDS_RESPONSE=$(curl -s -X GET "${BASE_URL}/ccdi/file-upload/list?projectId=${PROJECT_ID}" \
  -H "Authorization: Bearer ${TOKEN}")

RECORDS=$(echo "$RECORDS_RESPONSE" | grep -o '"rows"' | sed 's/.*:\(\[.*\]\).*/\1/')

if [ -z "$RECORDS" ] || [ "$RECORDS" = "[]" ]; then
    echo -e "${RED}未找到上传记录${NC}"
    exit 1
fi

echo -e "${GREEN}查询到 ${#RECORDS[@]} 条记录${NC}"

# 验证记录状态
for RECORD in $RECORDS; do
    STATUS=$(echo "$RECORD" | grep -o '"fileStatus"' | sed 's/.*:\([^"]*\).*/\1/')

    if [ "$STATUS" = "\"parsed_success\"" ]; then
        echo -e "${GREEN}文件解析成功${NC}"
    elif [ "$STATUS" = "\"parsed_failed\"" ]; then
        ERROR=$(echo "$RECORD" | grep -o '"errorMessage"' | sed 's/.*:\([^"]*\).*/\1/')
        echo -e "${RED}文件解析失败: ${ERROR}${NC}"
    else
        echo -e "${YELLOW}文件状态: ${STATUS}${NC}"
    fi
done

# 清理测试数据
echo -e "${YELLOW}清理测试数据...${NC}"
curl -s -X DELETE "${BASE_URL}/ccdi/project/${PROJECT_ID}" \
  -H "Authorization: Bearer ${TOKEN}"

rm -f "$TEST_FILE"

echo -e "${GREEN}测试完成${NC}"
