const axios = require('axios');

// 配置API基础URL
const API_BASE_URL = 'http://localhost:3000/api';

// 创建axios实例
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000
});

// 测试数据
const timestamp = Date.now();
let testInsuranceTypeId = null;
let testCustomerId = null;
let testApplicationId = null;

const testPolicyData = {
  coverage_amount: 100000,
  premium_amount: 2000,
  start_date: new Date(),
  end_date: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000), // 一年后
  policy_status: 'active',
  payment_status: 'unpaid'
};

let authToken = '';
let createdPolicyId = null;

// 管理员登录
async function adminLogin() {
  try {
    console.log('🔐 管理员登录...');
    const response = await api.post('/auth/login', {
      username: 'admin',
      password: '123456'
    });
    
    if (response.data.code === 200 && response.data.data && response.data.data.token) {
      authToken = response.data.data.token;
      api.defaults.headers.common['Authorization'] = `Bearer ${authToken}`;
      console.log('✓ 管理员登录成功');
      return true;
    } else {
      console.log('✗ 管理员登录失败:', response.data.message);
      return false;
    }
  } catch (error) {
    console.log('✗ 管理员登录失败:', error.response?.data?.message || error.message);
    return false;
  }
}

// 创建测试用户
async function createTestUser() {
  try {
    const response = await api.post('/auth/register', {
      username: `test_customer_${timestamp}`,
      password: '123456',
      real_name: `测试客户_${timestamp}`,
      email: `test${timestamp}@test.com`,
      phone: `138${timestamp.toString().slice(-8)}`,
      role_id: 3 // customer角色ID
    });
    
    if (response.data.code === 200 || response.data.code === 201) {
      testCustomerId = response.data.data.id;
      console.log('✓ 测试用户创建成功, ID:', testCustomerId);
      return true;
    }
    return false;
  } catch (error) {
    console.log('✗ 创建测试用户失败:', error.response?.data?.message || error.message);
    return false;
  }
}

// 获取保险类型
async function getInsuranceType() {
  try {
    const response = await api.get('/insurance-types');
    if (response.data.code === 200 && response.data.data.list && response.data.data.list.length > 0) {
      testInsuranceTypeId = response.data.data.list[0].id;
      console.log('✓ 获取保险类型成功, ID:', testInsuranceTypeId);
      return true;
    }
    return false;
  } catch (error) {
    console.log('✗ 获取保险类型失败:', error.response?.data?.message || error.message);
    return false;
  }
}

// 创建保险申请
async function createTestApplication() {
  try {
    const response = await api.post('/insurance/applications', {
      insurance_type_id: testInsuranceTypeId,
      customer_name: `测试客户_${timestamp}`,
      customer_phone: `138${timestamp.toString().slice(-8)}`,
      customer_id_card: `11010119900101${timestamp.toString().slice(-4)}`,
      customer_address: `测试地址_${timestamp}`,
      insurance_category: '养殖',
      application_quantity: 1,
      application_amount: 100000,
      remarks: '测试保险申请'
    });
    
    if (response.data.code === 200 || response.data.code === 201) {
      testApplicationId = response.data.data.id;
      console.log('✓ 测试保险申请创建成功, ID:', testApplicationId);
      return true;
    }
    return false;
  } catch (error) {
    console.log('✗ 创建测试保险申请失败:', error.response?.data?.message || error.message);
    return false;
  }
}

// 测试获取保单列表
async function testGetPolicies() {
  try {
    console.log('\n=== 测试获取保单列表 ===');
    const response = await api.get('/policies?page=1&limit=10');
    
    if (response.data.code === 200) {
      console.log('✓ 获取保单列表成功');
      console.log('保单数量:', response.data.data?.list?.length || response.data.data?.length || 'undefined');
      return true;
    } else {
      console.log('✗ 获取保单列表失败:', response.data.message);
      return false;
    }
  } catch (error) {
    console.log('✗ 获取保单列表失败:', error.response?.data?.message || error.message);
    return false;
  }
}

// 测试创建保单
async function testCreatePolicy() {
  try {
    console.log('\n=== 测试创建保单 ===');
    
    // 使用关联的测试数据
    const policyData = {
      customer_id: testCustomerId,
      insurance_type_id: testInsuranceTypeId,
      application_id: testApplicationId,
      premium_amount: 2000,
      coverage_amount: 100000,
      start_date: new Date().toISOString().split('T')[0],
      end_date: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      policy_status: 'active',
      payment_status: 'paid'
    };
    
    const response = await api.post('/policies', policyData);
    
    if (response.data.code === 201 || response.data.code === 200) {
      createdPolicyId = response.data.data.id;
      console.log('✓ 创建保单成功');
      console.log('创建的保单ID:', createdPolicyId);
      console.log('保单号:', response.data.data.policy_no);
      return true;
    } else {
      console.log('✗ 创建保单失败:', response.data.message);
      return false;
    }
  } catch (error) {
    console.log('✗ 创建保单失败:', error.response?.data?.message || error.message);
    return false;
  }
}

// 测试获取单个保单详情
async function testGetPolicy() {
  try {
    console.log('\n=== 测试获取单个保单详情 ===');
    if (!createdPolicyId) {
      console.log('✗ 获取单个保单详情失败: 没有可用的保单ID');
      return false;
    }
    
    const response = await api.get(`/policies/${createdPolicyId}`);
    
    if (response.data.code === 200) {
      console.log('✓ 获取单个保单详情成功');
      console.log('保单编号:', response.data.data.policy_no);
      console.log('保单状态:', response.data.data.policy_status);
      return true;
    } else {
      console.log('✗ 获取单个保单详情失败:', response.data.message);
      return false;
    }
  } catch (error) {
    console.log('✗ 获取单个保单详情失败:', error.response?.data?.message || error.message);
    return false;
  }
}

// 测试更新保单
async function testUpdatePolicy() {
  try {
    console.log('\n=== 测试更新保单 ===');
    if (!createdPolicyId) {
      console.log('✗ 更新保单失败: 没有可用的保单ID');
      return false;
    }
    
    const updateData = {
      ...testPolicyData,
      coverage_amount: 120000,
      premium_amount: 2400
    };
    
    const response = await api.put(`/policies/${createdPolicyId}`, updateData);
    
    if (response.data.code === 200) {
      console.log('✓ 更新保单成功');
      return true;
    } else {
      console.log('✗ 更新保单失败:', response.data.message);
      return false;
    }
  } catch (error) {
    console.log('✗ 更新保单失败:', error.response?.data?.message || error.message);
    return false;
  }
}

// 测试更新保单状态
async function testUpdatePolicyStatus() {
  try {
    console.log('\n=== 测试更新保单状态 ===');
    if (!createdPolicyId) {
      console.log('✗ 更新保单状态失败: 没有可用的保单ID');
      return false;
    }
    
    const response = await api.patch(`/policies/${createdPolicyId}/status`, {
      policy_status: 'suspended'
    });
    
    if (response.data.code === 200) {
      console.log('✓ 更新保单状态成功');
      return true;
    } else {
      console.log('✗ 更新保单状态失败:', response.data.message);
      return false;
    }
  } catch (error) {
    console.log('✗ 更新保单状态失败:', error.response?.data?.message || error.message);
    return false;
  }
}

// 测试获取保单统计
async function testGetPolicyStats() {
  try {
    console.log('\n=== 测试获取保单统计 ===');
    const response = await api.get('/policies/stats/overview');
    
    if (response.data.code === 200) {
      console.log('✓ 获取保单统计成功');
      console.log('统计数据:', JSON.stringify(response.data.data, null, 2));
      return true;
    } else {
      console.log('✗ 获取保单统计失败:', response.data.message);
      return false;
    }
  } catch (error) {
    console.log('✗ 获取保单统计失败:', error.response?.data?.message || error.message);
    return false;
  }
}

// 主测试函数
async function runPolicyTests() {
  console.log('🚀 开始保单管理API测试...\n');
  
  // 管理员登录
  const loginSuccess = await adminLogin();
  if (!loginSuccess) {
    console.log('\n❌ 测试终止：管理员登录失败');
    return;
  }
  
  console.log('\n🔧 准备测试数据...');
  
  // 创建测试用户
  const userCreated = await createTestUser();
  if (!userCreated) {
    console.log('\n❌ 测试终止：创建测试用户失败');
    return;
  }
  
  // 获取保险类型
  const typeFound = await getInsuranceType();
  if (!typeFound) {
    console.log('\n❌ 测试终止：获取保险类型失败');
    return;
  }
  
  // 创建保险申请
  const applicationCreated = await createTestApplication();
  if (!applicationCreated) {
    console.log('\n❌ 测试终止：创建保险申请失败');
    return;
  }
  
  console.log('\n📊 开始API测试...');
  
  const tests = [
    { name: '获取保单列表', func: testGetPolicies },
    { name: '创建保单', func: testCreatePolicy },
    { name: '获取单个保单详情', func: testGetPolicy },
    { name: '更新保单', func: testUpdatePolicy },
    { name: '更新保单状态', func: testUpdatePolicyStatus },
    { name: '获取保单统计', func: testGetPolicyStats }
  ];
  
  let passedTests = 0;
  let failedTests = 0;
  
  for (const test of tests) {
    const result = await test.func();
    if (result) {
      passedTests++;
    } else {
      failedTests++;
    }
  }
  
  console.log('\n📈 测试结果统计:');
  console.log(`✅ 通过: ${passedTests}/${tests.length}`);
  console.log(`❌ 失败: ${failedTests}/${tests.length}`);
  
  if (failedTests === 0) {
    console.log('\n🎉 所有测试通过！');
  } else {
    console.log('\n⚠️  部分测试失败，请检查相关功能');
  }
}

// 运行测试
runPolicyTests().catch(console.error);