#!/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/implementation/scripts/test_output/test_staff_enterprise_relation_$(date +%Y%m%d_%H%M%S).txt"
mkdir -p doc/implementation/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"
        log_error "响应: $response"
        exit 1
    fi

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

# 测试1: 查询列表
test_list() {
    local token=$1

    log_test "测试1: 查询员工企业关系列表..."

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

    echo "$response" | tee -a "$REPORT_FILE"

    if echo "$response" | grep -q '"code":200'; then
        record_pass "查询列表成功"
        return 0
    else
        record_fail "查询列表失败"
        return 1
    fi
}

# 测试2: 新增员工企业关系
test_add() {
    local token=$1

    log_test "测试2: 新增员工企业关系..."

    local add_data=$(cat <<EOF
{
    "personId": "110101199001011234",
    "personName": "张三",
    "socialCreditCode": "91110000123456789X",
    "enterpriseName": "测试技术有限公司",
    "relationPersonPost": "技术总监",
    "isEmployee": 0,
    "isEmpFamily": 1,
    "isCustomer": 0,
    "isCustFamily": 0,
    "status": 1,
    "dataSource": "MANUAL",
    "remark": "测试新增"
}
EOF
)

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

    echo "$response" | tee -a "$REPORT_FILE"

    if echo "$response" | grep -q '"code":200'; then
        record_pass "新增员工企业关系成功"

        # 获取新增记录的ID
        sleep 1
        local list_response=$(curl -s -X GET "$BASE_URL/ccdi/staffEnterpriseRelation/list?personName=张三&pageNum=1&pageSize=1" \
            -H "Authorization: Bearer $token")

        local new_id=$(echo $list_response | grep -o '"id":[0-9]*' | head -1 | sed 's/"id"://')

        if [ -n "$new_id" ]; then
            log_info "获取到新增的记录ID: $new_id"
            echo "$new_id"
        else
            log_error "未能获取新增的记录ID"
            echo ""
        fi
    else
        record_fail "新增员工企业关系失败"
        echo ""
    fi
}

# 测试3: 查询详情
test_get_info() {
    local token=$1
    local id=$2

    if [ -z "$id" ]; then
        log_warning "跳过查询详情测试（没有有效的ID）"
        return
    fi

    log_test "测试3: 查询员工企业关系详情 (ID: $id)..."

    local response=$(curl -s -X GET "$BASE_URL/ccdi/staffEnterpriseRelation/$id" \
        -H "Authorization: Bearer $token")

    echo "$response" | tee -a "$REPORT_FILE"

    if echo "$response" | grep -q '"code":200'; then
        record_pass "查询详情成功"
    else
        record_fail "查询详情失败"
    fi
}

# 测试4: 修改员工企业关系
test_edit() {
    local token=$1
    local id=$2

    if [ -z "$id" ]; then
        log_warning "跳过修改测试（没有有效的ID）"
        return
    fi

    log_test "测试4: 修改员工企业关系 (ID: $id)..."

    local edit_data=$(cat <<EOF
{
    "id": $id,
    "personId": "110101199001011234",
    "personName": "张三",
    "socialCreditCode": "91110000123456789X",
    "enterpriseName": "测试技术有限公司",
    "relationPersonPost": "总经理",
    "isEmployee": 0,
    "isEmpFamily": 1,
    "isCustomer": 0,
    "isCustFamily": 0,
    "status": 1,
    "dataSource": "MANUAL",
    "remark": "测试修改"
}
EOF
)

    local response=$(curl -s -X PUT "$BASE_URL/ccdi/staffEnterpriseRelation" \
        -H "Authorization: Bearer $token" \
        -H "Content-Type: application/json" \
        -d "$edit_data")

    echo "$response" | tee -a "$REPORT_FILE"

    if echo "$response" | grep -q '"code":200'; then
        record_pass "修改员工企业关系成功"
    else
        record_fail "修改员工企业关系失败"
    fi
}

# 测试5: 删除员工企业关系
test_remove() {
    local token=$1
    local id=$2

    if [ -z "$id" ]; then
        log_warning "跳过删除测试（没有有效的ID）"
        return
    fi

    log_test "测试5: 删除员工企业关系 (ID: $id)..."

    local response=$(curl -s -X DELETE "$BASE_URL/ccdi/staffEnterpriseRelation/$id" \
        -H "Authorization: Bearer $token")

    echo "$response" | tee -a "$REPORT_FILE"

    if echo "$response" | grep -q '"code":200'; then
        record_pass "删除员工企业关系成功"
    else
        record_fail "删除员工企业关系失败"
    fi
}

# 测试6: 下载导入模板
test_download_template() {
    local token=$1

    log_test "测试6: 下载导入模板..."

    local response=$(curl -s -X POST "$BASE_URL/ccdi/staffEnterpriseRelation/importTemplate" \
        -H "Authorization: Bearer $token" \
        -o "doc/implementation/scripts/test_output/test6_import_template.xlsx" \
        -w "%{http_code}")

    if [ "$response" = "200" ]; then
        record_pass "下载导入模板成功"
        log_info "模板文件已保存到: doc/implementation/scripts/test_output/test6_import_template.xlsx"
    else
        record_fail "下载导入模板失败 (HTTP $response)"
    fi
}

# 测试7: 导入数据（需要准备Excel文件）
test_import() {
    local token=$1
    local excel_file=$2

    if [ ! -f "$excel_file" ]; then
        log_warning "跳过导入测试（Excel文件不存在: $excel_file）"
        echo ""
        return
    fi

    log_test "测试7: 导入员工企业关系数据..."

    local response=$(curl -s -X POST "$BASE_URL/ccdi/staffEnterpriseRelation/importData" \
        -H "Authorization: Bearer $token" \
        -F "file=@$excel_file")

    echo "$response" | tee -a "$REPORT_FILE"

    if echo "$response" | grep -q '"code":200'; then
        record_pass "导入数据提交成功"

        # 提取taskId
        local task_id=$(echo $response | grep -o '"taskId":"[^"]*' | sed 's/"taskId":"//')

        if [ -n "$task_id" ]; then
            log_info "导入任务ID: $task_id"
            echo "$task_id"
        else
            log_error "未能获取导入任务ID"
            echo ""
        fi
    else
        record_fail "导入数据提交失败"
        echo ""
    fi
}

# 测试8: 查询导入状态
test_import_status() {
    local token=$1
    local task_id=$2

    if [ -z "$task_id" ]; then
        log_warning "跳过导入状态查询测试（没有有效的taskId）"
        return
    fi

    log_test "测试8: 查询导入状态 (taskId: $task_id)..."

    local response=$(curl -s -X GET "$BASE_URL/ccdi/staffEnterpriseRelation/importStatus/$task_id" \
        -H "Authorization: Bearer $token")

    echo "$response" | tee -a "$REPORT_FILE"

    if echo "$response" | grep -q '"code":200'; then
        record_pass "查询导入状态成功"

        # 提取状态信息
        local status=$(echo $response | grep -o '"status":"[^"]*' | head -1 | sed 's/"status":"//')
        local total_count=$(echo $response | grep -o '"totalCount":[0-9]*' | head -1 | sed 's/"totalCount"://')
        local success_count=$(echo $response | grep -o '"successCount":[0-9]*' | head -1 | sed 's/"successCount"://')
        local failure_count=$(echo $response | grep -o '"failureCount":[0-9]*' | head -1 | sed 's/"failureCount"://')

        log_info "导入状态: $status"
        log_info "总数: $total_count, 成功: $success_count, 失败: $failure_count"
    else
        record_fail "查询导入状态失败"
    fi
}

# 测试9: 查询导入失败记录
test_import_failures() {
    local token=$1
    local task_id=$2

    if [ -z "$task_id" ]; then
        log_warning "跳导入失败记录查询测试（没有有效的taskId）"
        return
    fi

    log_test "测试9: 查询导入失败记录 (taskId: $task_id)..."

    local response=$(curl -s -X GET "$BASE_URL/ccdi/staffEnterpriseRelation/importFailures/$task_id?pageNum=1&pageSize=10" \
        -H "Authorization: Bearer $token")

    echo "$response" | tee -a "$REPORT_FILE"

    if echo "$response" | grep -q '"code":200'; then
        record_pass "查询导入失败记录成功"

        # 提取失败记录数
        local total=$(echo $response | grep -o '"total":[0-9]*' | head -1 | sed 's/"total"://')
        log_info "失败记录数: $total"
    else
        record_fail "查询导入失败记录失败"
    fi
}

# 测试10: 导出数据
test_export() {
    local token=$1

    log_test "测试10: 导出员工企业关系数据..."

    local response=$(curl -s -X POST "$BASE_URL/ccdi/staffEnterpriseRelation/export" \
        -H "Authorization: Bearer $token" \
        -H "Content-Type: application/json" \
        -d "{}" \
        -o "doc/implementation/scripts/test_output/test10_export.xlsx" \
        -w "%{http_code}")

    if [ "$response" = "200" ]; then
        record_pass "导出数据成功"
        log_info "导出文件已保存到: doc/implementation/scripts/test_output/test10_export.xlsx"
    else
        record_fail "导出数据失败 (HTTP $response)"
    fi
}

# 主测试流程
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: 查询列表
    test_list "$TOKEN"
    echo "" | tee -a "$REPORT_FILE"

    # 测试2: 新增
    log_test "=== 测试2-5: CRUD操作 ==="
    NEW_ID=$(test_add "$TOKEN")
    echo "" | tee -a "$REPORT_FILE"

    # 测试3: 查询详情
    test_get_info "$TOKEN" "$NEW_ID"
    echo "" | tee -a "$REPORT_FILE"

    # 测试4: 修改
    test_edit "$TOKEN" "$NEW_ID"
    echo "" | tee -a "$REPORT_FILE"

    # 测试5: 删除（可选，保留数据用于后续测试）
    # test_remove "$TOKEN" "$NEW_ID"
    # echo "" | tee -a "$REPORT_FILE"

    # 测试6: 下载模板
    log_test "=== 测试6-9: 导入相关功能 ==="
    test_download_template "$TOKEN"
    echo "" | tee -a "$REPORT_FILE"

    # 测试7-9: 导入功能（需要Excel文件）
    # 如果有测试Excel文件，取消以下注释
    # EXCEL_FILE="doc/implementation/scripts/test_output/test_staff_enterprise_relation_import.xlsx"
    # TASK_ID=$(test_import "$TOKEN" "$EXCEL_FILE")
    # echo "" | tee -a "$REPORT_FILE"
    #
    # # 等待导入完成
    # sleep 5
    #
    # # 测试8: 查询导入状态
    # test_import_status "$TOKEN" "$TASK_ID"
    # echo "" | tee -a "$REPORT_FILE"
    #
    # # 测试9: 查询导入失败记录
    # test_import_failures "$TOKEN" "$TASK_ID"
    # echo "" | tee -a "$REPORT_FILE"

    # 测试10: 导出
    log_test "=== 测试10: 导出功能 ==="
    test_export "$TOKEN"
    echo "" | tee -a "$REPORT_FILE"

    # 输出测试总结
    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"

    if [ $TOTAL_TESTS -gt 0 ]; then
        echo "成功率: $(awk "BEGIN {printf \"%.2f\", ($PASSED_TESTS/$TOTAL_TESTS)*100}")%" | tee -a "$REPORT_FILE"
    fi
    echo "========================================" | tee -a "$REPORT_FILE"
    echo "" | tee -a "$REPORT_FILE"
    echo "详细日志已保存到: $REPORT_FILE" | tee -a "$REPORT_FILE"

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

# 执行测试
main
