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 testData = {
  username: 'admin',
  password: '123456'
};

let authToken = '';

// 测试函数
async function testLogin() {
  console.log('\n=== 测试1: 用户登录 ===');
  try {
    const response = await api.post('/auth/login', testData);
    console.log('✅ 登录成功');
    console.log('响应数据:', JSON.stringify(response.data, null, 2));
    
    if (response.data.code === 200 && response.data.data.token) {
      authToken = response.data.data.token;
      // 设置后续请求的认证头
      api.defaults.headers.common['Authorization'] = `Bearer ${authToken}`;
      return true;
    }
    return false;
  } catch (error) {
    console.log('❌ 登录失败:', error.response?.data || error.message);
    return false;
  }
}

async function testLivestockPolicyList() {
  console.log('\n=== 测试2: 获取生资保单列表 ===');
  try {
    const response = await api.get('/livestock-policies');
    console.log('✅ 获取生资保单列表成功');
    console.log('响应数据:', JSON.stringify(response.data, null, 2));
    return response.data.data?.list || [];
  } catch (error) {
    console.log('❌ 获取生资保单列表失败:', error.response?.data || error.message);
    return [];
  }
}

async function testLivestockTypes() {
  console.log('\n=== 测试3: 获取牲畜类型列表 ===');
  try {
    const response = await api.get('/livestock-types?status=active');
    console.log('✅ 获取牲畜类型列表成功');
    console.log('响应数据:', JSON.stringify(response.data, null, 2));
    
    // 根据实际的响应格式解析数据
    const list = response.data.data || [];
    // console.log('🔍 解析出的牲畜类型数组长度:', list.length);
    // if (list.length > 0) {
    //   console.log('🔍 第一个牲畜类型:', list[0]);
    // }
    return list;
  } catch (error) {
    console.log('❌ 获取牲畜类型列表失败:', error.response?.data || error.message);
    return [];
  }
}

async function testCreateLivestockPolicy(livestockTypes) {
  console.log('\n=== 测试4: 创建生资保单 ===');
  // console.log('🔍 接收到的牲畜类型参数:', livestockTypes);
  // console.log('🔍 牲畜类型数组长度:', livestockTypes ? livestockTypes.length : 'undefined');
  
  if (!livestockTypes || livestockTypes.length === 0) {
    console.log('❌ 无法创建保单：没有可用的牲畜类型');
    return null;
  }
  
  const livestockType = livestockTypes[0];
  const livestockCount = 10;
  const unitValue = 5000;
  const totalValue = livestockCount * unitValue;
  const premiumAmount = totalValue * parseFloat(livestockType.premium_rate);
  
  const newPolicy = {
    policy_no: `LP${Date.now()}${Math.random().toString(36).substr(2, 9).toUpperCase()}`,
    livestock_type_id: livestockType.id,
    policyholder_name: '测试农户',
    policyholder_id_card: '110101199001011234',
    policyholder_phone: '13800138000',
    policyholder_address: '北京市朝阳区测试街道123号',
    farm_address: '北京市朝阳区测试街道123号',
    livestock_count: livestockCount,
    unit_value: unitValue,
    total_value: totalValue,
    premium_amount: premiumAmount,
    start_date: '2024-01-01 08:00:00',
    end_date: '2024-12-31 08:00:00',
    policy_status: 'active',
    payment_status: 'unpaid',
    created_by: 1
  };
  
  try {
    const response = await api.post('/livestock-policies', newPolicy);
    console.log('✅ 创建生资保单成功');
    console.log('响应数据:', JSON.stringify(response.data, null, 2));
    return response.data.data;
  } catch (error) {
    console.log('❌ 创建生资保单失败:', error.response?.data || error.message);
    return null;
  }
}

async function testUpdateLivestockPolicy(policyId) {
  console.log('\n=== 测试5: 更新生资保单 ===');
  
  const updateData = {
    farmer_name: '测试农户（已更新）',
    livestock_count: 15,
    total_value: 75000,
    premium_amount: 750
  };
  
  try {
    const response = await api.put(`/livestock-policies/${policyId}`, updateData);
    console.log('✅ 更新生资保单成功');
    console.log('响应数据:', JSON.stringify(response.data, null, 2));
    return response.data.data;
  } catch (error) {
    console.log('❌ 更新生资保单失败:', error.response?.data || error.message);
    return null;
  }
}

async function testGetLivestockPolicyDetail(policyId) {
  console.log('\n=== 测试6: 获取生资保单详情 ===');
  
  try {
    const response = await api.get(`/livestock-policies/${policyId}`);
    console.log('✅ 获取生资保单详情成功');
    console.log('响应数据:', JSON.stringify(response.data, null, 2));
    return response.data.data;
  } catch (error) {
    console.log('❌ 获取生资保单详情失败:', error.response?.data || error.message);
    return null;
  }
}

async function testUpdatePolicyStatus(policyId) {
  console.log('\n=== 测试7: 更新保单状态 ===');
  
  try {
    const response = await api.patch(`/livestock-policies/${policyId}/status`, {
      policy_status: 'active'
    });
    console.log('✅ 更新保单状态成功');
    console.log('响应数据:', JSON.stringify(response.data, null, 2));
    return response.data.data;
  } catch (error) {
    console.log('❌ 更新保单状态失败:', error.response?.data || error.message);
    return null;
  }
}

async function testSearchLivestockPolicies() {
  console.log('\n=== 测试8: 搜索生资保单 ===');
  
  try {
    const response = await api.get('/livestock-policies', {
      params: {
        farmer_name: '测试',
        policy_status: 'active',
        page: 1,
        limit: 10
      }
    });
    console.log('✅ 搜索生资保单成功');
    console.log('响应数据:', JSON.stringify(response.data, null, 2));
    return response.data.data?.list || [];
  } catch (error) {
    console.log('❌ 搜索生资保单失败:', error.response?.data || error.message);
    return [];
  }
}

async function testDeleteLivestockPolicy(policyId) {
  console.log('\n=== 测试9: 删除生资保单 ===');
  
  try {
    const response = await api.delete(`/livestock-policies/${policyId}`);
    console.log('✅ 删除生资保单成功');
    console.log('响应数据:', JSON.stringify(response.data, null, 2));
    return true;
  } catch (error) {
    console.log('❌ 删除生资保单失败:', error.response?.data || error.message);
    return false;
  }
}

// 主测试函数
async function runTests() {
  console.log('🚀 开始前端集成测试...');
  console.log('测试API基础URL:', API_BASE_URL);
  
  try {
    // 1. 测试登录
    const loginSuccess = await testLogin();
    if (!loginSuccess) {
      console.log('\n❌ 登录失败，终止测试');
      return;
    }
    
    // 2. 测试获取保单列表
    const initialList = await testLivestockPolicyList();
    console.log(`\n📊 当前保单数量: ${initialList.length}`);
    
    // 3. 测试获取牲畜类型
    const livestockTypes = await testLivestockTypes();
    
    // 4. 测试创建保单
    const newPolicy = await testCreateLivestockPolicy(livestockTypes);
    if (!newPolicy) {
      console.log('\n❌ 创建保单失败，跳过后续测试');
      return;
    }
    
    const policyId = newPolicy.id;
    console.log(`\n📝 创建的保单ID: ${policyId}`);
    
    // 5. 测试获取保单详情
    await testGetLivestockPolicyDetail(policyId);
    
    // 6. 测试更新保单
    await testUpdateLivestockPolicy(policyId);
    
    // 7. 测试更新保单状态
    await testUpdatePolicyStatus(policyId);
    
    // 8. 测试搜索保单
    await testSearchLivestockPolicies();
    
    // 9. 测试删除保单
    await testDeleteLivestockPolicy(policyId);
    
    // 10. 再次获取保单列表验证删除
    const finalList = await testLivestockPolicyList();
    console.log(`\n📊 删除后保单数量: ${finalList.length}`);
    
    console.log('\n🎉 所有测试完成！');
    
  } catch (error) {
    console.error('\n💥 测试过程中发生错误:', error);
  }
}

// 运行测试
runTests().then(() => {
  console.log('\n✨ 测试脚本执行完毕');
  process.exit(0);
}).catch(error => {
  console.error('\n💥 测试脚本执行失败:', error);
  process.exit(1);
});