#!/bin/bash

# 中介新增和修改功能完整测试脚本
# 测试个人和机构中介的新增和修改功能

BASE_URL="http://localhost:8080"
USERNAME="admin"
PASSWORD="admin123"

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

# 测试结果统计
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# 测试报告文件
REPORT_FILE="doc/scripts/test_output/test_report_$(date +%Y%m%d_%H%M%S).txt"
mkdir -p doc/scripts/test_output

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1" | tee -a "$REPORT_FILE"
}

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

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1" | tee -a "$REPORT_FILE"
}

log_test() {
    echo -e "${YELLOW}[TEST]${NC} $1" | tee -a "$REPORT_FILE"
}

# 测试结果记录
record_pass() {
    ((PASSED_TESTS++))
    ((TOTAL_TESTS++))
    log_info "✓ 测试通过: $1"
}

record_fail() {
    ((FAILED_TESTS++))
    ((TOTAL_TESTS++))
    log_error "✗ 测试失败: $1"
}

# 登录获取token
login() {
    log_test "登录获取Token..."
    local response=$(curl -s -X POST "$BASE_URL/login/test" \
        -H "Content-Type: application/json" \
        -d "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\"}")

    local token=$(echo $response | grep -o '"token":"[^"]*' | sed 's/"token":"//')

    if [ -z "$token" ]; then
        log_error "登录失败，无法获取Token"
        exit 1
    fi

    log_info "登录成功，Token: ${token:0:20}..."
    echo "$token"
}

# 测试新增个人中介
test_add_person_intermediary() {
    local token=$1

    log_test "测试新增个人中介..."

    local add_data=$(cat <<EOF
{
    "name": "测试个人新增",
    "certificateNo": "110101199001019999",
    "indivType": "中介",
    "indivSubType": "本人",
    "indivGender": "M",
    "indivCertType": "身份证",
    "indivPhone": "13900139000",
    "indivCompany": "测试公司新增",
    "indivPosition": "经纪人",
    "status": "0",
    "remark": "新增测试"
}
EOF
)

    local response=$(curl -s -X POST "$BASE_URL/dpc/intermediary/person" \
        -H "Authorization: Bearer $token" \
        -H "Content-Type: application/json" \
        -d "$add_data")

    echo "$response"
}

# 测试新增机构中介
test_add_entity_intermediary() {
    local token=$1

    log_test "测试新增机构中介..."

    local add_data=$(cat <<EOF
{
    "name": "测试机构新增",
    "corpCreditCode": "91110000YYYYYYYYYY",
    "corpType": "有限责任公司",
    "corpNature": "民企",
    "corpIndustry": "测试行业",
    "corpAddress": "北京市测试区",
    "corpLegalRep": "测试法人",
    "status": "0",
    "remark": "新增测试"
}
EOF
)

    local response=$(curl -s -X POST "$BASE_URL/dpc/intermediary/entity" \
        -H "Authorization: Bearer $token" \
        -H "Content-Type: application/json" \
        -d "$add_data")

    echo "$response"
}

# 测试修改个人中介
test_update_person_intermediary() {
    local token=$1
    local intermediary_id=$2

    log_test "测试修改个人中介 (ID: $intermediary_id)..."

    local update_data=$(cat <<EOF
{
    "intermediaryId": $intermediary_id,
    "name": "测试个人修改",
    "certificateNo": "110101199001019999",
    "indivType": "中介",
    "indivSubType": "本人",
    "indivGender": "M",
    "indivCertType": "身份证",
    "indivPhone": "13900139000",
    "indivCompany": "测试公司修改",
    "indivPosition": "高级经纪人",
    "status": "0",
    "remark": "修改测试"
}
EOF
)

    local response=$(curl -s -X PUT "$BASE_URL/dpc/intermediary/person" \
        -H "Authorization: Bearer $token" \
        -H "Content-Type: application/json" \
        -d "$update_data")

    echo "$response"
}

# 测试修改机构中介
test_update_entity_intermediary() {
    local token=$1
    local intermediary_id=$2

    log_test "测试修改机构中介 (ID: $intermediary_id)..."

    local update_data=$(cat <<EOF
{
    "intermediaryId": $intermediary_id,
    "name": "测试机构修改",
    "certificateNo": "91110000YYYYYYYYYY",
    "corpCreditCode": "91110000YYYYYYYYYY",
    "corpType": "股份有限公司",
    "corpNature": "国企",
    "corpIndustry": "修改行业",
    "corpAddress": "上海市修改区",
    "corpLegalRep": "修改法人",
    "status": "0",
    "remark": "修改测试"
}
EOF
)

    local response=$(curl -s -X PUT "$BASE_URL/dpc/intermediary/entity" \
        -H "Authorization: Bearer $token" \
        -H "Content-Type: application/json" \
        -d "$update_data")

    echo "$response"
}

# 验证修改结果
verify_update() {
    local token=$1
    local intermediary_id=$2
    local expected_name=$3

    local response=$(curl -s -X GET "$BASE_URL/dpc/intermediary/$intermediary_id" \
        -H "Authorization: Bearer $token")

    local actual_name=$(echo $response | grep -o '"name":"[^"]*' | head -1 | sed 's/"name":"//')

    if [ "$actual_name" = "$expected_name" ]; then
        return 0
    else
        return 1
    fi
}

# 获取中介列表（按名称筛选）
get_intermediary_by_name() {
    local token=$1
    local name=$2

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

    echo "$response"
}

# 主测试流程
main() {
    echo "========================================" | tee "$REPORT_FILE"
    echo "中介新增和修改功能完整测试" | tee -a "$REPORT_FILE"
    echo "测试时间: $(date '+%Y-%m-%d %H:%M:%S')" | tee -a "$REPORT_FILE"
    echo "========================================" | tee -a "$REPORT_FILE"
    echo "" | tee -a "$REPORT_FILE"

    # 登录
    TOKEN=$(login)
    echo "" | tee -a "$REPORT_FILE"

    # 测试1: 新增个人中介
    log_test "=== 测试1: 新增个人中介 ==="
    add_result=$(test_add_person_intermediary "$TOKEN")
    echo "$add_result" | tee -a "$REPORT_FILE"

    if echo "$add_result" | grep -q '"code":200'; then
        record_pass "个人中介新增成功"

        # 获取新增的个人中介ID
        sleep 1
        person_list=$(get_intermediary_by_name "$TOKEN" "测试个人新增")
        person_id=$(echo $person_list | grep -o '"intermediaryId":[0-9]*' | head -1 | sed 's/"intermediaryId"://')

        if [ -n "$person_id" ]; then
            log_info "获取到新增的个人中介ID: $person_id"
        else
            log_error "未能获取新增的个人中介ID"
        fi
    else
        record_fail "个人中介新增失败"
        person_id=""
    fi
    echo "" | tee -a "$REPORT_FILE"

    # 测试2: 新增机构中介
    log_test "=== 测试2: 新增机构中介 ==="
    add_result=$(test_add_entity_intermediary "$TOKEN")
    echo "$add_result" | tee -a "$REPORT_FILE"

    if echo "$add_result" | grep -q '"code":200'; then
        record_pass "机构中介新增成功"

        # 获取新增的机构中介ID
        sleep 1
        entity_list=$(get_intermediary_by_name "$TOKEN" "测试机构新增")
        entity_id=$(echo $entity_list | grep -o '"intermediaryId":[0-9]*' | head -1 | sed 's/"intermediaryId"://')

        if [ -n "$entity_id" ]; then
            log_info "获取到新增的机构中介ID: $entity_id"
        else
            log_error "未能获取新增的机构中介ID"
        fi
    else
        record_fail "机构中介新增失败"
        entity_id=""
    fi
    echo "" | tee -a "$REPORT_FILE"

    # 测试3: 修改个人中介
    if [ -n "$person_id" ]; then
        log_test "=== 测试3: 修改个人中介 ==="
        update_result=$(test_update_person_intermediary "$TOKEN" "$person_id")
        echo "$update_result" | tee -a "$REPORT_FILE"

        if echo "$update_result" | grep -q '"code":200'; then
            record_pass "个人中介修改接口调用成功"

            # 验证修改结果
            sleep 1
            if verify_update "$TOKEN" "$person_id" "测试个人修改"; then
                record_pass "个人中介修改结果验证成功"
            else
                record_fail "个人中介修改结果验证失败"
            fi
        else
            record_fail "个人中介修改接口调用失败"
        fi
        echo "" | tee -a "$REPORT_FILE"
    fi

    # 测试4: 修改机构中介
    if [ -n "$entity_id" ]; then
        log_test "=== 测试4: 修改机构中介 ==="
        update_result=$(test_update_entity_intermediary "$TOKEN" "$entity_id")
        echo "$update_result" | tee -a "$REPORT_FILE"

        if echo "$update_result" | grep -q '"code":200'; then
            record_pass "机构中介修改接口调用成功"

            # 验证修改结果
            sleep 1
            if verify_update "$TOKEN" "$entity_id" "测试机构修改"; then
                record_pass "机构中介修改结果验证成功"
            else
                record_fail "机构中介修改结果验证失败"
            fi
        else
            record_fail "机构中介修改接口调用失败"
        fi
        echo "" | tee -a "$REPORT_FILE"
    fi

    # 输出测试总结
    echo "========================================" | tee -a "$REPORT_FILE"
    echo "测试总结" | tee -a "$REPORT_FILE"
    echo "========================================" | tee -a "$REPORT_FILE"
    echo "总测试数: $TOTAL_TESTS" | tee -a "$REPORT_FILE"
    echo "通过: $PASSED_TESTS" | tee -a "$REPORT_FILE"
    echo "失败: $FAILED_TESTS" | tee -a "$REPORT_FILE"
    echo "成功率: $(awk "BEGIN {printf \"%.2f\", ($PASSED_TESTS/$TOTAL_TESTS)*100}")%" | tee -a "$REPORT_FILE"
    echo "========================================" | tee -a "$REPORT_FILE"
    echo "" | tee -a "$REPORT_FILE"

    if [ $FAILED_TESTS -eq 0 ]; then
        log_info "所有测试通过！"
        exit 0
    else
        log_error "部分测试失败，请查看详细日志"
        exit 1
    fi
}

# 执行测试
main
