import { CloudUser, CloudObject, CloudQuery } from './ncloud';

// 测试数据导入函数
export async function importTestData() {
  try {
    // 第一个测试账号（原有）
    const user1 = await createTestUser(
      '123123', 
      '123123',
      {
        firstName: '张',
        lastName: '三',
        email: '123123@example.com',
        birthDate: new Date('1970-05-15'),
        gender: 'male',
        medicalHistory: ['高血压', '2型糖尿病'],
        currentMedications: ['二甲双胍', '阿司匹林'],
        nickname: '张三'
      }
    );
    
    // 为第一个账号创建测试数据
    await createHealthData(user1, [
      { glucoseValue: 5.2, measurementType: '空腹', measurementTime: new Date('2025-05-29T08:00:00') },
      { glucoseValue: 7.8, measurementType: '餐后', measurementTime: new Date('2025-05-29T14:30:00') },
      { glucoseValue: 6.5, measurementType: '随机', measurementTime: new Date('2025-05-29T10:15:00') }
    ], [
      { systolic: 120, diastolic: 80, pulse: 72, measurementTime: new Date('2025-05-29T09:00:00'), measurementPosition: '坐姿' },
      { systolic: 135, diastolic: 85, pulse: 76, measurementTime: new Date('2025-05-29T09:00:00'), measurementPosition: '坐姿' },
      { systolic: 128, diastolic: 82, pulse: 74, measurementTime: new Date('2025-05-29T09:00:00'), measurementPosition: '坐姿' }
    ], [
      { heartRate: 72, measurementTime: new Date('2025-05-29T08:30:00'), measurementMethod: '设备', rhythm: '规律' },
      { heartRate: 68, measurementTime: new Date('2025-05-29T08:30:00'), measurementMethod: '设备', rhythm: '规律' },
      { heartRate: 75, measurementTime: new Date('2025-05-29T08:30:00'), measurementMethod: '手动', rhythm: '规律' }
    ]);
    
    // 第二个测试账号（新增）
    const user2 = await createTestUser(
      '456456',
      '456456',
      {
        firstName: '李',
        lastName: '四',
        email: '456456@example.com',
        birthDate: new Date('1985-08-22'),
        gender: 'female',
        medicalHistory: ['高胆固醇', '甲状腺功能减退'],
        currentMedications: ['左甲状腺素', '阿托伐他汀'],
        nickname: '李四'
      }
    );
    
    // 为第二个账号创建测试数据
    await createHealthData(user2, [
      { glucoseValue: 4.8, measurementType: '空腹', measurementTime: new Date('2025-05-29T07:30:00') },
      { glucoseValue: 6.2, measurementType: '餐后', measurementTime: new Date('2025-05-29T13:45:00') }
    ], [
      { systolic: 118, diastolic: 77, pulse: 68, measurementTime: new Date('2025-05-29T08:15:00') },
      { systolic: 122, diastolic: 79, pulse: 70, measurementTime: new Date('2025-05-29T20:30:00') }
    ], [
      { heartRate: 65, measurementTime: new Date('2025-05-29T07:45:00') },
      { heartRate: 72, measurementTime: new Date('2025-05-29T18:20:00') }
    ]);

    console.log('所有测试数据和账号创建完成！');
  } catch (error) {
    console.error('导入测试数据时出错:', error);
  }
}

// 提取的创建用户函数
async function createTestUser(username: string, password: string, userInfo: any) {
  const user = new CloudUser();
  let loggedInUser = await user.login(username, password);
  
  if (!loggedInUser) {
    loggedInUser = await user.signUp(username, password, userInfo);
    console.log(`新用户 ${username} 注册成功:`, loggedInUser);
  } else {
    console.log(`用户 ${username} 登录成功:`, loggedInUser);
  }
  
  if (!loggedInUser) {
    throw new Error(`无法创建或登录用户 ${username}`);
  }
  
  await deleteUserHealthData(loggedInUser);
  return loggedInUser;
}

// 提取的创建健康数据函数
async function createHealthData(
  user: CloudUser,
  glucoseData: any[],
  pressureData: any[],
  heartRateData: any[]
) {
  // 创建血糖数据
  for (const data of glucoseData) {
    const glucose = new CloudObject('BloodGlucose');
    glucose.set({
      patient: user.toPointer(),
      ...data,
      notes: '常规测量',
      tags: ['日常']
    });
    await glucose.save();
    console.log(`血糖数据创建成功 (用户 ${user.data['username']}):`, glucose.id);
  }

  // 创建血压数据
  for (const data of pressureData) {
    const pressure = new CloudObject('BloodPressure');
    pressure.set({
      patient: user.toPointer(),
      ...data,
      notes: '日常监测',
      tags: ['常规']
    });
    await pressure.save();
    console.log(`血压数据创建成功 (用户 ${user.data['username']}):`, pressure.id);
  }

  // 创建心率数据
  for (const data of heartRateData) {
    const heartRate = new CloudObject('HeartRate');
    heartRate.set({
      patient: user.toPointer(),
      ...data,
      notes: '静息心率',
      tags: ['静息']
    });
    await heartRate.save();
    console.log(`心率数据创建成功 (用户 ${user.data['username']}):`, heartRate.id);
  }
}

// 删除用户健康数据函数
async function deleteUserHealthData(user: CloudUser) {
  try {
    const classes = ['BloodGlucose', 'BloodPressure', 'HeartRate'];
    
    for (const className of classes) {
      const query = new CloudQuery(className);
      query.equalTo('patient', user.toPointer());
      const results = await query.find();
      
      if (results.length > 0) {
        for (const record of results) {
          await record.destroy();
        }
        console.log(`已删除 ${results.length} 条 ${className} 记录 (用户 ${user.data['username']})`);
      }
    }
    return true;
  } catch (error) {
    console.error('删除用户数据时出错:', error);
    throw error;
  }
}

// 执行导入
importTestData();