#!/bin/bash
BASE_URL="http://localhost:8080/api"
TOKEN=""
PROJECT_ID=""
PASS_COUNT=0
FAIL_COUNT=0
TOTAL_COUNT=0

assert_eq() {
  local actual="$1"
  local expected="$2"
  local name="$3"
  TOTAL_COUNT=$((TOTAL_COUNT + 1))
  if [ "$actual" = "$expected" ]; then
    echo "  PASS: $name"
    PASS_COUNT=$((PASS_COUNT + 1))
  else
    echo "  FAIL: $name (expected=$expected, actual=$actual)"
    FAIL_COUNT=$((FAIL_COUNT + 1))
  fi
}

assert_contains() {
  local haystack="$1"
  local needle="$2"
  local name="$3"
  TOTAL_COUNT=$((TOTAL_COUNT + 1))
  if echo "$haystack" | grep -q "$needle"; then
    echo "  PASS: $name"
    PASS_COUNT=$((PASS_COUNT + 1))
  else
    echo "  FAIL: $name (expected to contain: $needle)"
    FAIL_COUNT=$((FAIL_COUNT + 1))
  fi
}

login() {
  echo "=== 登录获取Token ==="
  local response=$(curl -s -X POST "$BASE_URL/auth/login" \
    -H "Content-Type: application/json" \
    -d '{"username":"admin","password":"admin123"}')
  TOKEN=$(echo "$response" | grep -o '"token":"[^"]*"' | cut -d'"' -f4)
  if [ -z "$TOKEN" ]; then
    echo "FATAL: 登录失败，无法获取Token"
    exit 1
  fi
  echo "Token获取成功"
}

setup_project() {
  echo "=== 创建测试项目 ==="
  local response=$(curl -s -X POST "$BASE_URL/mdm/projects" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: " \
    -d "{\"code\":\"TEST-ASSET-$$\",\"name\":\"ASSET测试项目\",\"projectType\":\"RESIDENTIAL\"}")
  PROJECT_ID=$(echo "$response" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
  if [ -z "$PROJECT_ID" ]; then
    echo "FATAL: 创建测试项目失败"
    exit 1
  fi
  echo "测试项目创建成功: $PROJECT_ID"
}

test_create_equipment() {
  echo "--- TC-ASSET-001: 创建设备 ---"
  local response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/asset/equipment" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID" \
    -d "{\"equipmentCode\":\"TEST-EQ-$$_$RANDOM\",\"equipmentName\":\"测试电梯设备\",\"equipmentType\":\"ELEVATOR\",\"systemType\":\"ELEVATOR\",\"ownershipType\":\"PROJECT\"}")
  local status=$(echo "$response" | tail -n 1)
  local body=$(echo "$response" | head -n -1)
  assert_eq "$status" "201" "TC-ASSET-001: 创建设备返回201"
  EQUIPMENT_ID=$(echo "$body" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
}

test_query_equipment_by_project() {
  echo "--- TC-ASSET-002: 按项目查询设备 ---"
  local response=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/asset/equipment/by-project/$PROJECT_ID" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID")
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "200" "TC-ASSET-002: 按项目查询设备返回200"
}

test_query_equipment_by_space() {
  echo "--- TC-ASSET-003: 按空间查询设备 ---"
  local response=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/asset/equipment/by-space/00000000-0000-0000-0000-000000000000" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID")
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "200" "TC-ASSET-003: 按空间查询设备返回200"
}

test_batch_delete_equipment() {
  echo "--- TC-ASSET-004: 设备批量删除 ---"
  local eq1_response=$(curl -s -X POST "$BASE_URL/asset/equipment" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID" \
    -d "{\"equipmentCode\":\"BATCH-DEL-1-$$_$RANDOM\",\"equipmentName\":\"批量删除测试1\",\"equipmentType\":\"HVAC\",\"systemType\":\"HVAC\",\"ownershipType\":\"PROJECT\"}")
  local eq1_id=$(echo "$eq1_response" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
  local eq2_response=$(curl -s -X POST "$BASE_URL/asset/equipment" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID" \
    -d "{\"equipmentCode\":\"BATCH-DEL-2-$$_$RANDOM\",\"equipmentName\":\"批量删除测试2\",\"equipmentType\":\"HVAC\",\"systemType\":\"HVAC\",\"ownershipType\":\"PROJECT\"}")
  local eq2_id=$(echo "$eq2_response" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
  if [ -n "$eq1_id" ] && [ -n "$eq2_id" ]; then
    local response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/asset/equipment/batch-delete" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $TOKEN" \
      -H "X-Project-ID: $PROJECT_ID" \
      -d "{\"ids\":[\"$eq1_id\",\"$eq2_id\"]}")
    local status=$(echo "$response" | tail -n 1)
    assert_eq "$status" "200" "TC-ASSET-004: 批量删除返回200"
  else
    echo "  SKIP: TC-ASSET-004 (无法创建测试设备)"
  fi
}

test_elevator_extension() {
  echo "--- TC-ASSET-005: 电梯扩展表管理 ---"
  if [ -z "$EQUIPMENT_ID" ]; then
    echo "  SKIP: TC-ASSET-005 (无设备ID)"
    return
  fi
  local put_response=$(curl -s -w "\n%{http_code}" -X PUT "$BASE_URL/asset/equipment/$EQUIPMENT_ID/elevator" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID" \
    -d '{"elevatorType":"PASSENGER","model":"TEST-001","loadCapacity":1000,"speed":2.5,"floorCount":20}')
  local put_status=$(echo "$put_response" | tail -n 1)
  assert_eq "$put_status" "200" "TC-ASSET-005: 更新电梯扩展表返回200"
  local get_response=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/asset/equipment/$EQUIPMENT_ID/elevator" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID")
  local get_status=$(echo "$get_response" | tail -n 1)
  assert_eq "$get_status" "200" "TC-ASSET-005: 查询电梯扩展表返回200"
}

test_hvac_extension() {
  echo "--- TC-ASSET-006: 暖通扩展表管理 ---"
  local hvac_response=$(curl -s -X POST "$BASE_URL/asset/equipment" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID" \
    -d "{\"equipmentCode\":\"HVAC-TEST-$$_$RANDOM\",\"equipmentName\":\"测试暖通设备\",\"equipmentType\":\"HVAC\",\"systemType\":\"HVAC\",\"ownershipType\":\"PROJECT\"}")
  local hvac_id=$(echo "$hvac_response" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
  if [ -z "$hvac_id" ]; then
    echo "  SKIP: TC-ASSET-006 (无法创建暖通设备)"
    return
  fi
  local put_response=$(curl -s -w "\n%{http_code}" -X PUT "$BASE_URL/asset/equipment/$hvac_id/hvac" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID" \
    -d '{"hvacType":"CHILLER","coolingCapacity":500,"heatingCapacity":400}')
  local put_status=$(echo "$put_response" | tail -n 1)
  assert_eq "$put_status" "200" "TC-ASSET-006: 更新暖通扩展表返回200"
  HVAC_EQ_ID="$hvac_id"
}

test_fire_extension() {
  echo "--- TC-ASSET-007: 消防扩展表管理 ---"
  local fire_response=$(curl -s -X POST "$BASE_URL/asset/equipment" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID" \
    -d "{\"equipmentCode\":\"FIRE-TEST-$$_$RANDOM\",\"equipmentName\":\"测试消防设备\",\"equipmentType\":\"FIRE_PROTECTION\",\"systemType\":\"FIRE\",\"ownershipType\":\"PROJECT\"}")
  local fire_id=$(echo "$fire_response" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
  if [ -z "$fire_id" ]; then
    echo "  SKIP: TC-ASSET-007 (无法创建消防设备)"
    return
  fi
  local put_response=$(curl -s -w "\n%{http_code}" -X PUT "$BASE_URL/asset/equipment/$fire_id/fire" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID" \
    -d '{"fireEquipmentType":"SPRINKLER","installationArea":200}')
  local put_status=$(echo "$put_response" | tail -n 1)
  assert_eq "$put_status" "200" "TC-ASSET-007: 更新消防扩展表返回200"
  FIRE_EQ_ID="$fire_id"
}

test_energy_extension() {
  echo "--- TC-ASSET-008: 能源计量扩展表管理 ---"
  local energy_response=$(curl -s -X POST "$BASE_URL/asset/equipment" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID" \
    -d "{\"equipmentCode\":\"ENERGY-TEST-$$_$RANDOM\",\"equipmentName\":\"测试能源计量设备\",\"equipmentType\":\"ENERGY_METER\",\"systemType\":\"ELECTRICAL\",\"ownershipType\":\"PROJECT\"}")
  local energy_id=$(echo "$energy_response" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
  if [ -z "$energy_id" ]; then
    echo "  SKIP: TC-ASSET-008 (无法创建能源计量设备)"
    return
  fi
  local put_response=$(curl -s -w "\n%{http_code}" -X PUT "$BASE_URL/asset/equipment/$energy_id/energy" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID" \
    -d '{"meterType":"ELECTRICITY","energyType":"LIGHTING","accuracyClass":"1.0"}')
  local put_status=$(echo "$put_response" | tail -n 1)
  assert_eq "$put_status" "200" "TC-ASSET-008: 更新能源计量扩展表返回200"
  ENERGY_EQ_ID="$energy_id"
}

test_equipment_statistics() {
  echo "--- TC-ASSET-009: 设备统计 ---"
  local response=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/asset/equipment/statistics/by-type?projectId=$PROJECT_ID" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID")
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "200" "TC-ASSET-009: 设备统计返回200"
}

test_health_score() {
  echo "--- TC-ASSET-010: 健康评分查询 ---"
  if [ -z "$EQUIPMENT_ID" ]; then
    echo "  SKIP: TC-ASSET-010 (无设备ID)"
    return
  fi
  local response=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/asset/equipment/$EQUIPMENT_ID/health" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID")
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "200" "TC-ASSET-010: 健康评分查询返回200"
}

test_failure_record() {
  echo "--- TC-ASSET-011: 故障记录 ---"
  if [ -z "$EQUIPMENT_ID" ]; then
    echo "  SKIP: TC-ASSET-011 (无设备ID)"
    return
  fi
  local response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/asset/equipment/$EQUIPMENT_ID/failures" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID" \
    -d '{"failureType":"SUDDEN","failureLevel":"MEDIUM","description":"测试故障记录","failureTime":"2026-05-18T10:00:00"}')
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "201" "TC-ASSET-011: 故障记录返回201"
}

test_ownership_entity_crud() {
  echo "--- TC-ASSET-012: 归属主体CRUD ---"
  local create_response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/asset/ownership-entities" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-Project-ID: $PROJECT_ID" \
    -d "{\"entityName\":\"测试归属主体-$$_$RANDOM\",\"entityType\":\"COMPANY\",\"contactPerson\":\"张三\",\"contactPhone\":\"13800138000\"}")
  local create_status=$(echo "$create_response" | tail -n 1)
  local create_body=$(echo "$create_response" | head -n -1)
  assert_eq "$create_status" "201" "TC-ASSET-012: 创建归属主体返回201"
  OWNERSHIP_ID=$(echo "$create_body" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
  if [ -n "$OWNERSHIP_ID" ]; then
    local query_response=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/asset/ownership-entities/$OWNERSHIP_ID" \
      -H "Authorization: Bearer $TOKEN" \
      -H "X-Project-ID: $PROJECT_ID")
    local query_status=$(echo "$query_response" | tail -n 1)
    assert_eq "$query_status" "200" "TC-ASSET-012: 查询归属主体返回200"
  fi
}

cleanup() {
  echo "=== 清理测试数据 ==="
  if [ -n "$PROJECT_ID" ]; then
    curl -s -X DELETE "$BASE_URL/mdm/projects/$PROJECT_ID" \
      -H "Authorization: Bearer $TOKEN" > /dev/null 2>&1
  fi
}

print_summary() {
  echo ""
  echo "=========================================="
  echo "  Asset Domain API Test Summary"
  echo "=========================================="
  echo "  Total:  $TOTAL_COUNT"
  echo "  Passed: $PASS_COUNT"
  echo "  Failed: $FAIL_COUNT"
  if [ "$TOTAL_COUNT" -gt 0 ]; then
    local rate=$(echo "scale=1; $PASS_COUNT * 100 / $TOTAL_COUNT" | bc)
    echo "  Rate:   ${rate}%"
  fi
  echo "=========================================="
  if [ "$FAIL_COUNT" -gt 0 ]; then
    return 1
  fi
  return 0
}

EQUIPMENT_ID=""
HVAC_EQ_ID=""
FIRE_EQ_ID=""
ENERGY_EQ_ID=""
OWNERSHIP_ID=""

echo "=========================================="
echo "  Ether PMS - Asset Domain API Tests"
echo "=========================================="
echo ""

login
setup_project

test_create_equipment
test_query_equipment_by_project
test_query_equipment_by_space
test_batch_delete_equipment
test_elevator_extension
test_hvac_extension
test_fire_extension
test_energy_extension
test_equipment_statistics
test_health_score
test_failure_record
test_ownership_entity_crud

cleanup
print_summary
