#!/bin/bash
################################################################################
# 中介黑名单管理API测试脚本
#
# 功能：测试DpcIntermediaryBlacklistController中的所有接口
# 作者：Claude
# 日期：2026-01-29
################################################################################

# ============================================================================
# 配置项
# ============================================================================
BASE_URL="http://localhost:8080"
USERNAME="admin"
PASSWORD="admin123"
TOKEN=""
OUTPUT_DIR="test_output"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
REPORT_FILE="${OUTPUT_DIR}/test_report_${TIMESTAMP}.txt"

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

# ============================================================================
# 工具函数
# ============================================================================

# 打印带颜色的消息
print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

# 打印分隔线
print_separator() {
    echo -e "${BLUE}================================================================================${NC}"
}

# 初始化输出目录
init_output_dir() {
    if [ ! -d "$OUTPUT_DIR" ]; then
        mkdir -p "$OUTPUT_DIR"
        print_info "创建输出目录: $OUTPUT_DIR"
    fi
}

# 记录到报告文件
log_to_report() {
    echo "$1" >> "$REPORT_FILE"
}

# ============================================================================
# API请求函数
# ============================================================================

# 登录获取token
login() {
    print_separator
    print_info "正在登录..."
    print_separator

    local response=$(curl -s -X POST "${BASE_URL}/login/test" \
        -H "Content-Type: application/json" \
        -d "{\"username\":\"${USERNAME}\",\"password\":\"${PASSWORD}\"}")

    TOKEN=$(echo "$response" | grep -o '"token":"[^"]*"' | cut -d'"' -f4)

    if [ -n "$TOKEN" ]; then
        print_success "登录成功，获取token: ${TOKEN:0:20}..."
        log_to_report "========== 登录测试 =========="
        log_to_report "请求: POST ${BASE_URL}/login/test"
        log_to_report "响应: $response"
        log_to_report "结果: 成功"
        log_to_report ""
        return 0
    else
        print_error "登录失败"
        log_to_report "========== 登录测试 =========="
        log_to_report "请求: POST ${BASE_URL}/login/test"
        log_to_report "响应: $response"
        log_to_report "结果: 失败"
        log_to_report ""
        return 1
    fi
}

# 获取请求头
get_headers() {
    echo "-H \"Authorization: Bearer $TOKEN\" -H \"Content-Type: application/json\""
}

# ============================================================================
# 测试函数
# ============================================================================

# 测试1: 查询中介黑名单列表
test_list() {
    print_separator
    print_info "测试1: 查询中介黑名单列表"
    print_separator

    local url="${BASE_URL}/dpc/intermediary/list?pageNum=1&pageSize=10"
    local response=$(curl -s -X GET "$url" \
        -H "Authorization: Bearer $TOKEN")

    echo "$response" | jq '.' > "${OUTPUT_DIR}/test1_list_response.json" 2>/dev/null || echo "$response" > "${OUTPUT_DIR}/test1_list_response.json"

    local code=$(echo "$response" | grep -o '"code":[0-9]*' | cut -d':' -f2)

    if [ "$code" == "200" ]; then
        print_success "查询列表成功"
        log_to_report "========== 测试1: 查询中介黑名单列表 =========="
        log_to_report "请求: GET $url"
        log_to_report "响应已保存至: ${OUTPUT_DIR}/test1_list_response.json"
        log_to_report "结果: 成功"
        log_to_report ""
        return 0
    else
        print_error "查询列表失败: $response"
        log_to_report "========== 测试1: 查询中介黑名单列表 =========="
        log_to_report "请求: GET $url"
        log_to_report "响应: $response"
        log_to_report "结果: 失败"
        log_to_report ""
        return 1
    fi
}

# 测试2: 新增个人中介黑名单
test_add_person() {
    print_separator
    print_info "测试2: 新增个人中介黑名单"
    print_separator

    local test_name="测试个人中介_${TIMESTAMP}"
    local data='{
        "name": "'${test_name}'",
        "certificateNo": "TESTCERT'${TIMESTAMP}'",
        "intermediaryType": "1",
        "remark": "自动化测试数据"
    }'

    local response=$(curl -s -X POST "${BASE_URL}/dpc/intermediary" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d "$data")

    echo "$response" | jq '.' > "${OUTPUT_DIR}/test2_add_person_response.json" 2>/dev/null || echo "$response" > "${OUTPUT_DIR}/test2_add_person_response.json"

    local code=$(echo "$response" | grep -o '"code":[0-9]*' | cut -d':' -f2)

    if [ "$code" == "200" ]; then
        print_success "新增个人中介成功"
        log_to_report "========== 测试2: 新增个人中介黑名单 =========="
        log_to_report "请求: POST ${BASE_URL}/dpc/intermediary"
        log_to_report "请求体: $data"
        log_to_report "响应已保存至: ${OUTPUT_DIR}/test2_add_person_response.json"
        log_to_report "结果: 成功"
        log_to_report ""

        # 通过查询列表获取最新创建的ID（按创建时间倒序）
        sleep 1
        local list_response=$(curl -s -X GET "${BASE_URL}/dpc/intermediary/list?pageNum=1&pageSize=1" \
            -H "Authorization: Bearer $TOKEN")

        # 从rows数组中提取第一个intermediaryId
        PERSON_INTERMEDIARY_ID=$(echo "$list_response" | jq -r '.rows[0].intermediaryId' 2>/dev/null)

        if [ -n "$PERSON_INTERMEDIARY_ID" ] && [ "$PERSON_INTERMEDIARY_ID" != "null" ]; then
            print_info "获取到中介ID: $PERSON_INTERMEDIARY_ID"
        else
            print_warning "无法获取中介ID，将使用备用方法"
        fi
        return 0
    else
        print_error "新增个人中介失败: $response"
        log_to_report "========== 测试2: 新增个人中介黑名单 =========="
        log_to_report "请求: POST ${BASE_URL}/dpc/intermediary"
        log_to_report "请求体: $data"
        log_to_report "响应: $response"
        log_to_report "结果: 失败"
        log_to_report ""
        return 1
    fi
}

# 测试3: 新增机构中介黑名单
test_add_entity() {
    print_separator
    print_info "测试3: 新增机构中介黑名单"
    print_separator

    local test_name="测试机构中介_${TIMESTAMP}"
    local data='{
        "name": "'${test_name}'",
        "certificateNo": "TESTORG'${TIMESTAMP}'",
        "intermediaryType": "2",
        "remark": "自动化测试机构数据"
    }'

    local response=$(curl -s -X POST "${BASE_URL}/dpc/intermediary" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d "$data")

    echo "$response" | jq '.' > "${OUTPUT_DIR}/test3_add_entity_response.json" 2>/dev/null || echo "$response" > "${OUTPUT_DIR}/test3_add_entity_response.json"

    local code=$(echo "$response" | grep -o '"code":[0-9]*' | cut -d':' -f2)

    if [ "$code" == "200" ]; then
        print_success "新增机构中介成功"
        log_to_report "========== 测试3: 新增机构中介黑名单 =========="
        log_to_report "请求: POST ${BASE_URL}/dpc/intermediary"
        log_to_report "请求体: $data"
        log_to_report "响应已保存至: ${OUTPUT_DIR}/test3_add_entity_response.json"
        log_to_report "结果: 成功"
        log_to_report ""

        # 通过查询列表获取最新创建的ID（按创建时间倒序）
        sleep 1
        local list_response=$(curl -s -X GET "${BASE_URL}/dpc/intermediary/list?pageNum=1&pageSize=1" \
            -H "Authorization: Bearer $TOKEN")

        # 从rows数组中提取第一个intermediaryId
        ENTITY_INTERMEDIARY_ID=$(echo "$list_response" | jq -r '.rows[0].intermediaryId' 2>/dev/null)

        if [ -n "$ENTITY_INTERMEDIARY_ID" ] && [ "$ENTITY_INTERMEDIARY_ID" != "null" ]; then
            print_info "获取到中介ID: $ENTITY_INTERMEDIARY_ID"
        else
            print_warning "无法获取中介ID，将使用备用方法"
        fi
        return 0
    else
        print_error "新增机构中介失败: $response"
        log_to_report "========== 测试3: 新增机构中介黑名单 =========="
        log_to_report "请求: POST ${BASE_URL}/dpc/intermediary"
        log_to_report "请求体: $data"
        log_to_report "响应: $response"
        log_to_report "结果: 失败"
        log_to_report ""
        return 1
    fi
}

# 测试4: 获取中介详情
test_get_info() {
    print_separator
    print_info "测试4: 获取中介详情"
    print_separator

    if [ -z "$PERSON_INTERMEDIARY_ID" ]; then
        print_warning "没有可用的中介ID，跳过此测试"
        return 1
    fi

    local url="${BASE_URL}/dpc/intermediary/${PERSON_INTERMEDIARY_ID}"
    local response=$(curl -s -X GET "$url" \
        -H "Authorization: Bearer $TOKEN")

    echo "$response" | jq '.' > "${OUTPUT_DIR}/test4_get_info_response.json" 2>/dev/null || echo "$response" > "${OUTPUT_DIR}/test4_get_info_response.json"

    local code=$(echo "$response" | grep -o '"code":[0-9]*' | cut -d':' -f2)

    if [ "$code" == "200" ]; then
        print_success "获取中介详情成功"
        log_to_report "========== 测试4: 获取中介详情 =========="
        log_to_report "请求: GET $url"
        log_to_report "响应已保存至: ${OUTPUT_DIR}/test4_get_info_response.json"
        log_to_report "结果: 成功"
        log_to_report ""
        return 0
    else
        print_error "获取中介详情失败: $response"
        log_to_report "========== 测试4: 获取中介详情 =========="
        log_to_report "请求: GET $url"
        log_to_report "响应: $response"
        log_to_report "结果: 失败"
        log_to_report ""
        return 1
    fi
}

# 测试5: 修改中介黑名单
test_edit() {
    print_separator
    print_info "测试5: 修改中介黑名单"
    print_separator

    if [ -z "$PERSON_INTERMEDIARY_ID" ]; then
        print_warning "没有可用的中介ID，跳过此测试"
        return 1
    fi

    local data='{
        "intermediaryId": '$PERSON_INTERMEDIARY_ID',
        "name": "测试个人中介_修改",
        "certificateNo": "TESTCERT'${TIMESTAMP}'",
        "intermediaryType": "1",
        "status": "1",
        "remark": "修改后的自动化测试数据"
    }'

    local response=$(curl -s -X PUT "${BASE_URL}/dpc/intermediary" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d "$data")

    echo "$response" | jq '.' > "${OUTPUT_DIR}/test5_edit_response.json" 2>/dev/null || echo "$response" > "${OUTPUT_DIR}/test5_edit_response.json"

    local code=$(echo "$response" | grep -o '"code":[0-9]*' | cut -d':' -f2)

    if [ "$code" == "200" ]; then
        print_success "修改中介成功"
        log_to_report "========== 测试5: 修改中介黑名单 =========="
        log_to_report "请求: PUT ${BASE_URL}/dpc/intermediary"
        log_to_report "请求体: $data"
        log_to_report "响应已保存至: ${OUTPUT_DIR}/test5_edit_response.json"
        log_to_report "结果: 成功"
        log_to_report ""
        return 0
    else
        print_error "修改中介失败: $response"
        log_to_report "========== 测试5: 修改中介黑名单 =========="
        log_to_report "请求: PUT ${BASE_URL}/dpc/intermediary"
        log_to_report "请求体: $data"
        log_to_report "响应: $response"
        log_to_report "结果: 失败"
        log_to_report ""
        return 1
    fi
}

# 测试6: 导出中介黑名单列表
test_export() {
    print_separator
    print_info "测试6: 导出中介黑名单列表"
    print_separator

    local url="${BASE_URL}/dpc/intermediary/export"
    local response=$(curl -s -X POST "$url" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d '{}' \
        -o "${OUTPUT_DIR}/test6_export.xlsx" \
        -w "%{http_code}")

    if [ "$response" == "200" ]; then
        print_success "导出中介列表成功，文件已保存至: ${OUTPUT_DIR}/test6_export.xlsx"
        log_to_report "========== 测试6: 导出中介黑名单列表 =========="
        log_to_report "请求: POST $url"
        log_to_report "文件已保存至: ${OUTPUT_DIR}/test6_export.xlsx"
        log_to_report "结果: 成功"
        log_to_report ""
        return 0
    else
        print_error "导出中介列表失败，HTTP状态码: $response"
        log_to_report "========== 测试6: 导出中介黑名单列表 =========="
        log_to_report "请求: POST $url"
        log_to_report "HTTP状态码: $response"
        log_to_report "结果: 失败"
        log_to_report ""
        return 1
    fi
}

# 测试7: 下载个人中介导入模板
test_import_person_template() {
    print_separator
    print_info "测试7: 下载个人中介导入模板"
    print_separator

    local url="${BASE_URL}/dpc/intermediary/importPersonTemplate"
    local response=$(curl -s -X POST "$url" \
        -H "Authorization: Bearer $TOKEN" \
        -o "${OUTPUT_DIR}/test7_person_template.xlsx" \
        -w "%{http_code}")

    if [ "$response" == "200" ]; then
        print_success "下载个人中介导入模板成功，文件已保存至: ${OUTPUT_DIR}/test7_person_template.xlsx"
        log_to_report "========== 测试7: 下载个人中介导入模板 =========="
        log_to_report "请求: POST $url"
        log_to_report "文件已保存至: ${OUTPUT_DIR}/test7_person_template.xlsx"
        log_to_report "结果: 成功"
        log_to_report ""
        return 0
    else
        print_error "下载个人中介导入模板失败，HTTP状态码: $response"
        log_to_report "========== 测试7: 下载个人中介导入模板 =========="
        log_to_report "请求: POST $url"
        log_to_report "HTTP状态码: $response"
        log_to_report "结果: 失败"
        log_to_report ""
        return 1
    fi
}

# 测试8: 下载机构中介导入模板
test_import_entity_template() {
    print_separator
    print_info "测试8: 下载机构中介导入模板"
    print_separator

    local url="${BASE_URL}/dpc/intermediary/importEntityTemplate"
    local response=$(curl -s -X POST "$url" \
        -H "Authorization: Bearer $TOKEN" \
        -o "${OUTPUT_DIR}/test8_entity_template.xlsx" \
        -w "%{http_code}")

    if [ "$response" == "200" ]; then
        print_success "下载机构中介导入模板成功，文件已保存至: ${OUTPUT_DIR}/test8_entity_template.xlsx"
        log_to_report "========== 测试8: 下载机构中介导入模板 =========="
        log_to_report "请求: POST $url"
        log_to_report "文件已保存至: ${OUTPUT_DIR}/test8_entity_template.xlsx"
        log_to_report "结果: 成功"
        log_to_report ""
        return 0
    else
        print_error "下载机构中介导入模板失败，HTTP状态码: $response"
        log_to_report "========== 测试8: 下载机构中介导入模板 =========="
        log_to_report "请求: POST $url"
        log_to_report "HTTP状态码: $response"
        log_to_report "结果: 失败"
        log_to_report ""
        return 1
    fi
}

# 测试9: 删除中介黑名单
test_remove() {
    print_separator
    print_info "测试9: 删除中介黑名单"
    print_separator

    if [ -z "$PERSON_INTERMEDIARY_ID" ] && [ -z "$ENTITY_INTERMEDIARY_ID" ]; then
        print_warning "没有可用的中介ID，跳过此测试"
        return 1
    fi

    local ids=""
    if [ -n "$PERSON_INTERMEDIARY_ID" ]; then
        ids="$PERSON_INTERMEDIARY_ID"
    fi
    if [ -n "$ENTITY_INTERMEDIARY_ID" ]; then
        if [ -n "$ids" ]; then
            ids="${ids},${ENTITY_INTERMEDIARY_ID}"
        else
            ids="$ENTITY_INTERMEDIARY_ID"
        fi
    fi

    local url="${BASE_URL}/dpc/intermediary/${ids}"
    local response=$(curl -s -X DELETE "$url" \
        -H "Authorization: Bearer $TOKEN")

    echo "$response" | jq '.' > "${OUTPUT_DIR}/test9_remove_response.json" 2>/dev/null || echo "$response" > "${OUTPUT_DIR}/test9_remove_response.json"

    local code=$(echo "$response" | grep -o '"code":[0-9]*' | cut -d':' -f2)

    if [ "$code" == "200" ]; then
        print_success "删除中介成功"
        log_to_report "========== 测试9: 删除中介黑名单 =========="
        log_to_report "请求: DELETE $url"
        log_to_report "响应已保存至: ${OUTPUT_DIR}/test9_remove_response.json"
        log_to_report "结果: 成功"
        log_to_report ""
        return 0
    else
        print_error "删除中介失败: $response"
        log_to_report "========== 测试9: 删除中介黑名单 =========="
        log_to_report "请求: DELETE $url"
        log_to_report "响应: $response"
        log_to_report "结果: 失败"
        log_to_report ""
        return 1
    fi
}

# 测试10: 条件查询（按中介类型）
test_query_by_type() {
    print_separator
    print_info "测试10: 条件查询（按中介类型）"
    print_separator

    local url="${BASE_URL}/dpc/intermediary/list?pageNum=1&pageSize=10&intermediaryType=1"
    local response=$(curl -s -X GET "$url" \
        -H "Authorization: Bearer $TOKEN")

    echo "$response" | jq '.' > "${OUTPUT_DIR}/test10_query_by_type_response.json" 2>/dev/null || echo "$response" > "${OUTPUT_DIR}/test10_query_by_type_response.json"

    local code=$(echo "$response" | grep -o '"code":[0-9]*' | cut -d':' -f2)

    if [ "$code" == "200" ]; then
        print_success "条件查询成功"
        log_to_report "========== 测试10: 条件查询（按中介类型） =========="
        log_to_report "请求: GET $url"
        log_to_report "响应已保存至: ${OUTPUT_DIR}/test10_query_by_type_response.json"
        log_to_report "结果: 成功"
        log_to_report ""
        return 0
    else
        print_error "条件查询失败: $response"
        log_to_report "========== 测试10: 条件查询（按中介类型） =========="
        log_to_report "请求: GET $url"
        log_to_report "响应: $response"
        log_to_report "结果: 失败"
        log_to_report ""
        return 1
    fi
}

# 测试11: 条件查询（按状态）
test_query_by_status() {
    print_separator
    print_info "测试11: 条件查询（按状态）"
    print_separator

    local url="${BASE_URL}/dpc/intermediary/list?pageNum=1&pageSize=10&status=1"
    local response=$(curl -s -X GET "$url" \
        -H "Authorization: Bearer $TOKEN")

    echo "$response" | jq '.' > "${OUTPUT_DIR}/test11_query_by_status_response.json" 2>/dev/null || echo "$response" > "${OUTPUT_DIR}/test11_query_by_status_response.json"

    local code=$(echo "$response" | grep -o '"code":[0-9]*' | cut -d':' -f2)

    if [ "$code" == "200" ]; then
        print_success "条件查询成功"
        log_to_report "========== 测试11: 条件查询（按状态） =========="
        log_to_report "请求: GET $url"
        log_to_report "响应已保存至: ${OUTPUT_DIR}/test11_query_by_status_response.json"
        log_to_report "结果: 成功"
        log_to_report ""
        return 0
    else
        print_error "条件查询失败: $response"
        log_to_report "========== 测试11: 条件查询（按状态） =========="
        log_to_report "请求: GET $url"
        log_to_report "响应: $response"
        log_to_report "结果: 失败"
        log_to_report ""
        return 1
    fi
}

# ============================================================================
# 主测试流程
# ============================================================================

main() {
    print_separator
    echo -e "${BLUE}              中介黑名单管理API测试脚本${NC}"
    print_separator
    echo "测试时间: $(date '+%Y-%m-%d %H:%M:%S')"
    echo "基础URL: $BASE_URL"
    echo "测试账号: $USERNAME"
    print_separator
    echo ""

    # 初始化输出目录
    init_output_dir

    # 初始化报告文件
    echo "====================================" > "$REPORT_FILE"
    echo "中介黑名单管理API测试报告" >> "$REPORT_FILE"
    echo "测试时间: $(date '+%Y-%m-%d %H:%M:%S')" >> "$REPORT_FILE"
    echo "====================================" >> "$REPORT_FILE"
    echo ""

    # 登录
    if ! login; then
        print_error "登录失败，测试终止"
        exit 1
    fi

    echo ""
    echo "===================================="
    echo "开始执行测试用例"
    echo "===================================="
    echo ""

    # 执行测试
    local tests=(
        "test_list"
        "test_add_person"
        "test_add_entity"
        "test_get_info"
        "test_edit"
        "test_export"
        "test_import_person_template"
        "test_import_entity_template"
        "test_query_by_type"
        "test_query_by_status"
        "test_remove"
    )

    local passed=0
    local failed=0
    local total=${#tests[@]}

    for test in "${tests[@]}"; do
        if $test; then
            ((passed++))
        else
            ((failed++))
        fi
        echo ""
        sleep 1  # 避免请求过快
    done

    # 输出测试报告汇总
    print_separator
    echo -e "${BLUE}              测试报告汇总${NC}"
    print_separator
    echo "测试场景总数: $total"
    echo -e "${GREEN}通过数量: $passed${NC}"
    echo -e "${RED}失败数量: $failed${NC}"
    print_separator

    # 将汇总信息写入报告
    echo "" >> "$REPORT_FILE"
    echo "====================================" >> "$REPORT_FILE"
    echo "测试汇总" >> "$REPORT_FILE"
    echo "====================================" >> "$REPORT_FILE"
    echo "测试场景总数: $total" >> "$REPORT_FILE"
    echo "通过数量: $passed" >> "$REPORT_FILE"
    echo "失败数量: $failed" >> "$REPORT_FILE"
    echo "通过率: $(awk "BEGIN {printf \"%.2f%%\", $passed/$total*100}")" >> "$REPORT_FILE"
    echo "" >> "$REPORT_FILE"
    echo "详细响应文件已保存至: ${OUTPUT_DIR}/" >> "$REPORT_FILE"
    echo "测试报告文件: $REPORT_FILE" >> "$REPORT_FILE"
    echo "====================================" >> "$REPORT_FILE"

    if [ $passed -eq $total ]; then
        print_success "所有测试通过！"
        echo ""
        print_info "详细报告已保存至: $REPORT_FILE"
        print_info "响应文件已保存至: ${OUTPUT_DIR}/"
        exit 0
    else
        print_error "部分测试失败，请查看详细日志"
        echo ""
        print_info "详细报告已保存至: $REPORT_FILE"
        print_info "响应文件已保存至: ${OUTPUT_DIR}/"
        exit 1
    fi
}

# 执行主函数
main
