/**
 * 贷款申请测试数据脚本
 * @file seed-loan-applications.js
 * @description 为银行系统添加贷款申请测试数据
 */
const { sequelize, LoanApplication, AuditRecord, User } = require('../models');

async function seedLoanApplications() {
  try {
    console.log('开始添加贷款申请测试数据...');

    // 获取admin用户（作为申请人和审核人）
    const adminUser = await User.findOne({ where: { username: 'admin' } });
    if (!adminUser) {
      console.log('❌ 未找到admin用户，请先创建用户');
      return;
    }

    // 清空现有数据
    await AuditRecord.destroy({ where: {} });
    await LoanApplication.destroy({ where: {} });
    console.log('✅ 清空现有贷款申请数据');

    // 创建贷款申请测试数据（参考前端页面的模拟数据）
    const applications = [
      {
        applicationNumber: '20240325123703784',
        productName: '惠农贷',
        farmerName: '刘超',
        borrowerName: '刘超',
        borrowerIdNumber: '511***********3017',
        assetType: '牛',
        applicationQuantity: '10头',
        amount: 100000.00,
        status: 'pending_review',
        type: 'personal',
        term: 12,
        interestRate: 3.90,
        phone: '13800138000',
        purpose: '养殖贷款',
        remark: '申请资金用于购买牛只扩大养殖规模',
        applicationTime: new Date('2024-03-25 12:37:03'),
        applicantId: adminUser.id
      },
      {
        applicationNumber: '20240229110801968',
        productName: '中国工商银行扎旗支行"畜禽活体抵押"',
        farmerName: '刘超',
        borrowerName: '刘超',
        borrowerIdNumber: '511***********3017',
        assetType: '牛',
        applicationQuantity: '10头',
        amount: 100000.00,
        status: 'verification_pending',
        type: 'mortgage',
        term: 24,
        interestRate: 4.20,
        phone: '13900139000',
        purpose: '养殖贷款',
        remark: '以畜禽活体作为抵押物申请贷款',
        applicationTime: new Date('2024-02-29 11:08:01'),
        applicantId: adminUser.id,
        approvedBy: adminUser.id,
        approvedTime: new Date('2024-03-01 10:15:00')
      },
      {
        applicationNumber: '20240229105806431',
        productName: '惠农贷',
        farmerName: '刘超',
        borrowerName: '刘超',
        borrowerIdNumber: '511***********3017',
        assetType: '牛',
        applicationQuantity: '10头',
        amount: 100000.00,
        status: 'pending_binding',
        type: 'personal',
        term: 18,
        interestRate: 3.75,
        phone: '13700137000',
        purpose: '养殖贷款',
        remark: '待绑定相关资产信息',
        applicationTime: new Date('2024-02-29 10:58:06'),
        applicantId: adminUser.id
      },
      {
        applicationNumber: '20240315085642123',
        productName: '农商银行养殖贷',
        farmerName: '张伟',
        borrowerName: '张伟',
        borrowerIdNumber: '621***********2156',
        assetType: '猪',
        applicationQuantity: '50头',
        amount: 250000.00,
        status: 'approved',
        type: 'business',
        term: 36,
        interestRate: 4.50,
        phone: '13600136000',
        purpose: '扩大养猪规模',
        remark: '已审核通过，准备放款',
        applicationTime: new Date('2024-03-15 08:56:42'),
        applicantId: adminUser.id,
        approvedBy: adminUser.id,
        approvedTime: new Date('2024-03-16 14:20:00')
      },
      {
        applicationNumber: '20240310142355789',
        productName: '建设银行农户小额贷款',
        farmerName: '李明',
        borrowerName: '李明',
        borrowerIdNumber: '371***********4578',
        assetType: '羊',
        applicationQuantity: '30只',
        amount: 80000.00,
        status: 'rejected',
        type: 'personal',
        term: 12,
        interestRate: 4.10,
        phone: '13500135000',
        purpose: '养羊创业',
        remark: '资质不符合要求，已拒绝',
        applicationTime: new Date('2024-03-10 14:23:55'),
        applicantId: adminUser.id,
        rejectedBy: adminUser.id,
        rejectedTime: new Date('2024-03-11 09:30:00'),
        rejectionReason: '申请人征信记录不良，不符合放款条件'
      }
    ];

    // 批量创建申请
    const createdApplications = await LoanApplication.bulkCreate(applications);
    console.log(`✅ 成功创建${createdApplications.length}个贷款申请`);

    // 为每个申请创建审核记录
    const auditRecords = [];

    // 第一个申请：只有提交记录
    auditRecords.push({
      applicationId: createdApplications[0].id,
      action: 'submit',
      auditor: '刘超',
      auditorId: adminUser.id,
      comment: '提交申请',
      auditTime: new Date('2024-03-25 12:37:03'),
      newStatus: 'pending_review'
    });

    // 第二个申请：提交 + 审核通过
    auditRecords.push(
      {
        applicationId: createdApplications[1].id,
        action: 'submit',
        auditor: '刘超',
        auditorId: adminUser.id,
        comment: '提交申请',
        auditTime: new Date('2024-02-29 11:08:01'),
        newStatus: 'pending_review'
      },
      {
        applicationId: createdApplications[1].id,
        action: 'approve',
        auditor: '王经理',
        auditorId: adminUser.id,
        comment: '资料齐全，符合条件，同意放款',
        auditTime: new Date('2024-03-01 10:15:00'),
        previousStatus: 'pending_review',
        newStatus: 'verification_pending'
      }
    );

    // 第三个申请：只有提交记录
    auditRecords.push({
      applicationId: createdApplications[2].id,
      action: 'submit',
      auditor: '刘超',
      auditorId: adminUser.id,
      comment: '提交申请',
      auditTime: new Date('2024-02-29 10:58:06'),
      newStatus: 'pending_review'
    });

    // 第四个申请：提交 + 审核通过
    auditRecords.push(
      {
        applicationId: createdApplications[3].id,
        action: 'submit',
        auditor: '张伟',
        auditorId: adminUser.id,
        comment: '提交申请',
        auditTime: new Date('2024-03-15 08:56:42'),
        newStatus: 'pending_review'
      },
      {
        applicationId: createdApplications[3].id,
        action: 'approve',
        auditor: '李总监',
        auditorId: adminUser.id,
        comment: '经营状况良好，养殖经验丰富，批准贷款',
        auditTime: new Date('2024-03-16 14:20:00'),
        previousStatus: 'pending_review',
        newStatus: 'approved'
      }
    );

    // 第五个申请：提交 + 审核拒绝
    auditRecords.push(
      {
        applicationId: createdApplications[4].id,
        action: 'submit',
        auditor: '李明',
        auditorId: adminUser.id,
        comment: '提交申请',
        auditTime: new Date('2024-03-10 14:23:55'),
        newStatus: 'pending_review'
      },
      {
        applicationId: createdApplications[4].id,
        action: 'reject',
        auditor: '风控部门',
        auditorId: adminUser.id,
        comment: '申请人征信记录不良，不符合放款条件',
        auditTime: new Date('2024-03-11 09:30:00'),
        previousStatus: 'pending_review',
        newStatus: 'rejected'
      }
    );

    // 批量创建审核记录
    await AuditRecord.bulkCreate(auditRecords);
    console.log(`✅ 成功创建${auditRecords.length}条审核记录`);

    console.log('\n📊 贷款申请数据统计：');
    console.log('- 待初审：1个申请');
    console.log('- 核验待放款：1个申请');
    console.log('- 待绑定：1个申请');
    console.log('- 已通过：1个申请');
    console.log('- 已拒绝：1个申请');
    console.log('- 总申请金额：630,000.00元');

    console.log('\n🎉 贷款申请测试数据添加完成！');
  } catch (error) {
    console.error('❌ 添加贷款申请测试数据失败:', error);
    throw error;
  }
}

// 如果直接运行此文件
if (require.main === module) {
  seedLoanApplications()
    .then(() => {
      console.log('✅ 脚本执行完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('❌ 脚本执行失败:', error);
      process.exit(1);
    });
}

module.exports = seedLoanApplications;
