const { sequelize } = require('../config/database');
const { DataTypes } = require('sequelize');
const { User, Role, InsuranceType, InsuranceApplication, Policy, Claim } = require('../models');

// 创建随机数据的辅助函数
const randomString = (length = 10, chars = 'abcdefghijklmnopqrstuvwxyz0123456789') => {
  let result = '';
  const charsLength = chars.length;
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * charsLength));
  }
  return result;
};

const randomDate = (start, end) => {
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
};

const randomNumber = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

const randomDecimal = (min, max, decimals = 2) => {
  return Number((Math.random() * (max - min) + min).toFixed(decimals));
};

const generateApplicationNo = () => {
  return `APP${Date.now()}${randomString(6).toUpperCase()}`;
};

const generatePolicyNo = () => {
  return `POL${Date.now()}${randomString(6).toUpperCase()}`;
};

const generateClaimNo = () => {
  return `CLAIM${Date.now()}${randomString(6).toUpperCase()}`;
};

// 生成随机身份证号
const generateIdCard = () => {
  // 简化版身份证号生成，真实场景需要更复杂的校验
  const areaCode = randomNumber(110000, 659004);
  const birthYear = randomNumber(1960, 2000);
  const birthMonth = String(randomNumber(1, 12)).padStart(2, '0');
  const birthDay = String(randomNumber(1, 28)).padStart(2, '0');
  const seq = String(randomNumber(100, 999)).padStart(3, '0');
  const checkDigit = Math.random() > 0.9 ? 'X' : randomNumber(0, 9);
  
  return `${areaCode}${birthYear}${birthMonth}${birthDay}${seq}${checkDigit}`;
};

// 生成随机手机号
const generatePhone = () => {
  return `1${randomNumber(3, 9)}${randomString(9, '0123456789')}`;
};

// 初始化测试数据
async function seedData() {
  try {
    // 确保数据库连接正常
    await sequelize.authenticate();
    console.log('数据库连接成功');

    // 1. 创建角色（如果不存在）
    let adminRole = await Role.findOne({ where: { name: 'admin' } });
    if (!adminRole) {
      adminRole = await Role.create({
        name: 'admin',
        description: '管理员角色'
      });
    }

    // 2. 创建用户（如果不存在）
    let adminUser = await User.findOne({ where: { username: 'admin' } });
    if (!adminUser) {
      adminUser = await User.create({
        username: 'admin',
        password: 'admin123', // 实际应用中应该使用bcrypt加密
        email: 'admin@example.com',
        phone: '13800138000',
        role_id: adminRole.id,
        status: 1
      });
    }

    // 3. 创建保险类型
    const insuranceTypes = [
      {
        name: '健康保险',
        description: '提供医疗费用报销和健康保障',
        coverage_amount_min: 10000.00,
        coverage_amount_max: 500000.00,
        premium_rate: 0.005,
        terms_years: 1,
        status: 1
      },
      {
        name: '人寿保险',
        description: '为家人提供经济保障',
        coverage_amount_min: 50000.00,
        coverage_amount_max: 1000000.00,
        premium_rate: 0.01,
        terms_years: 10,
        status: 1
      },
      {
        name: '财产保险',
        description: '保障个人财产安全',
        coverage_amount_min: 20000.00,
        coverage_amount_max: 200000.00,
        premium_rate: 0.003,
        terms_years: 1,
        status: 1
      },
      {
        name: '意外保险',
        description: '提供意外事故保障',
        coverage_amount_min: 50000.00,
        coverage_amount_max: 300000.00,
        premium_rate: 0.002,
        terms_years: 1,
        status: 1
      }
    ];

    // 清除现有保险类型并插入新数据
    await InsuranceType.destroy({ where: {} });
    const createdTypes = await InsuranceType.bulkCreate(insuranceTypes);
    console.log(`已创建 ${createdTypes.length} 种保险类型`);

    // 4. 创建保险申请、保单和理赔数据
    const applications = [];
    const policies = [];
    const claims = [];
    
    // 为每种保险类型创建多个申请
    for (let i = 0; i < 50; i++) {
      const type = createdTypes[randomNumber(0, createdTypes.length - 1)];
      const coverageAmount = randomDecimal(type.coverage_amount_min, type.coverage_amount_max);
      const premium = Number((coverageAmount * type.premium_rate).toFixed(2));
      
      const application = {
        application_no: generateApplicationNo(),
        customer_name: `客户${i + 1}`,
        customer_id_card: generateIdCard(),
        customer_phone: generatePhone(),
        customer_address: `测试地址${i + 1}号`,
        insurance_type_id: type.id,
        coverage_amount: coverageAmount,
        premium: premium,
        application_date: randomDate(new Date(2023, 0, 1), new Date()),
        status: randomNumber(0, 3), // 0: 待审核, 1: 已批准, 2: 已拒绝, 3: 已撤销
        reviewer_id: adminUser.id,
        review_date: randomDate(new Date(2023, 0, 1), new Date()),
        rejection_reason: randomNumber(0, 2) === 0 ? '资料不完整' : null
      };
      applications.push(application);
    }

    // 清除现有申请并插入新数据
    await InsuranceApplication.destroy({ where: {} });
    const createdApplications = await InsuranceApplication.bulkCreate(applications);
    console.log(`已创建 ${createdApplications.length} 个保险申请`);

    // 为已批准的申请创建保单
    for (const app of createdApplications) {
      if (app.status === 1) { // 只有已批准的申请才有保单
        const policy = {
          policy_no: generatePolicyNo(),
          application_id: app.id,
          insurance_type_id: app.insurance_type_id,
          customer_id: adminUser.id, // 简化处理，实际应该关联真实客户
          coverage_amount: app.coverage_amount,
          premium: app.premium,
          start_date: randomDate(app.review_date, new Date()),
          end_date: new Date(app.review_date.getTime() + 365 * 24 * 60 * 60 * 1000),
          status: 1, // 1: 有效
          created_by: adminUser.id,
          created_at: app.review_date
        };
        policies.push(policy);
      }
    }

    // 清除现有保单并插入新数据
    await Policy.destroy({ where: {} });
    const createdPolicies = await Policy.bulkCreate(policies);
    console.log(`已创建 ${createdPolicies.length} 个保单`);

    // 为部分保单创建理赔
    for (const policy of createdPolicies) {
      if (randomNumber(0, 3) === 0) { // 约25%的保单会有理赔
        const claimAmount = randomDecimal(policy.coverage_amount * 0.1, policy.coverage_amount * 0.8);
        
        const claim = {
          claim_no: generateClaimNo(),
          policy_id: policy.id,
          customer_id: policy.customer_id,
          claim_amount: claimAmount,
          claim_date: randomDate(policy.start_date, new Date()),
          status: randomNumber(0, 2), // 0: 待审核, 1: 已批准, 2: 已拒绝
          claim_reason: '意外事故',
          created_at: randomDate(policy.start_date, new Date()),
          updated_at: new Date()
        };
        claims.push(claim);
      }
    }

    // 清除现有理赔并插入新数据
    await Claim.destroy({ where: {} });
    const createdClaims = await Claim.bulkCreate(claims);
    console.log(`已创建 ${createdClaims.length} 个理赔记录`);

    console.log('数据览仓测试数据插入完成');
  } catch (error) {
    console.error('数据插入过程中发生错误:', error);
  } finally {
    // 关闭数据库连接
    await sequelize.close();
  }
}

// 执行数据初始化
seedData();