/**
 * 监管任务测试数据种子文件
 * @file seed-supervision-tasks.js
 * @description 为监管任务表添加测试数据
 */
const { sequelize, SupervisionTask, User } = require('../models');

async function seedSupervisionTasks() {
  try {
    console.log('🌱 开始添加监管任务测试数据...');

    // 检查是否已有数据
    const existingCount = await SupervisionTask.count();
    if (existingCount > 0) {
      console.log(`⚠️  监管任务表已有 ${existingCount} 条数据，跳过种子数据添加`);
      return;
    }

    // 获取管理员用户ID
    const adminUser = await User.findOne({ where: { username: 'admin' } });
    if (!adminUser) {
      console.log('❌ 未找到管理员用户，请先运行用户种子数据');
      return;
    }

    const adminId = adminUser.id;

    // 监管任务测试数据
    const supervisionTasks = [
      {
        applicationNumber: 'APP001',
        contractNumber: 'CONTRACT001',
        productName: '农业贷款产品A',
        customerName: '张三',
        idType: 'id_card',
        idNumber: '110101199001011234',
        assetType: 'cattle',
        assetQuantity: 10,
        supervisionStatus: 'supervising',
        importTime: new Date('2024-01-15 10:30:00'),
        startTime: '2024-01-15',
        endTime: '2024-12-15',
        loanAmount: 500000.00,
        interestRate: 0.0650,
        loanTerm: 12,
        supervisorName: '李监管员',
        supervisorPhone: '13800138001',
        farmAddress: '北京市朝阳区某某养殖场',
        remarks: '重点监管项目，需要定期检查',
        createdBy: adminId,
        updatedBy: adminId
      },
      {
        applicationNumber: 'APP002',
        contractNumber: 'CONTRACT002',
        productName: '农业贷款产品B',
        customerName: '李四',
        idType: 'id_card',
        idNumber: '110101199002021234',
        assetType: 'sheep',
        assetQuantity: 20,
        supervisionStatus: 'pending',
        importTime: new Date('2024-01-16 14:20:00'),
        startTime: '2024-01-16',
        endTime: '2024-12-16',
        loanAmount: 300000.00,
        interestRate: 0.0600,
        loanTerm: 12,
        supervisorName: '王监管员',
        supervisorPhone: '13800138002',
        farmAddress: '北京市海淀区某某农场',
        remarks: '新申请项目，待开始监管',
        createdBy: adminId,
        updatedBy: adminId
      },
      {
        applicationNumber: 'APP003',
        contractNumber: 'CONTRACT003',
        productName: '农业贷款产品C',
        customerName: '王五',
        idType: 'id_card',
        idNumber: '110101199003031234',
        assetType: 'pig',
        assetQuantity: 15,
        supervisionStatus: 'completed',
        importTime: new Date('2024-01-10 09:15:00'),
        startTime: '2024-01-10',
        endTime: '2024-01-20',
        loanAmount: 200000.00,
        interestRate: 0.0550,
        loanTerm: 6,
        supervisorName: '赵监管员',
        supervisorPhone: '13800138003',
        farmAddress: '北京市丰台区某某猪场',
        remarks: '监管任务已完成，客户还款正常',
        createdBy: adminId,
        updatedBy: adminId
      },
      {
        applicationNumber: 'APP004',
        contractNumber: 'CONTRACT004',
        productName: '农业贷款产品D',
        customerName: '赵六',
        idType: 'id_card',
        idNumber: '110101199004041234',
        assetType: 'poultry',
        assetQuantity: 50,
        supervisionStatus: 'supervising',
        importTime: new Date('2024-01-20 11:45:00'),
        startTime: '2024-01-20',
        endTime: '2024-06-20',
        loanAmount: 150000.00,
        interestRate: 0.0700,
        loanTerm: 6,
        supervisorName: '孙监管员',
        supervisorPhone: '13800138004',
        farmAddress: '北京市通州区某某鸡场',
        remarks: '家禽养殖项目，需要特别关注防疫情况',
        createdBy: adminId,
        updatedBy: adminId
      },
      {
        applicationNumber: 'APP005',
        contractNumber: 'CONTRACT005',
        productName: '农业贷款产品E',
        customerName: '孙七',
        idType: 'id_card',
        idNumber: '110101199005051234',
        assetType: 'cattle',
        assetQuantity: 25,
        supervisionStatus: 'suspended',
        importTime: new Date('2024-01-25 16:30:00'),
        startTime: '2024-01-25',
        endTime: '2024-12-25',
        loanAmount: 800000.00,
        interestRate: 0.0625,
        loanTerm: 18,
        supervisorName: '周监管员',
        supervisorPhone: '13800138005',
        farmAddress: '北京市昌平区某某牧场',
        remarks: '因客户原因暂停监管，等待进一步通知',
        createdBy: adminId,
        updatedBy: adminId
      },
      {
        applicationNumber: 'APP006',
        contractNumber: 'CONTRACT006',
        productName: '农业贷款产品F',
        customerName: '周八',
        idType: 'passport',
        idNumber: 'P123456789',
        assetType: 'other',
        assetQuantity: 30,
        supervisionStatus: 'supervising',
        importTime: new Date('2024-02-01 08:20:00'),
        startTime: '2024-02-01',
        endTime: '2024-08-01',
        loanAmount: 400000.00,
        interestRate: 0.0680,
        loanTerm: 6,
        supervisorName: '吴监管员',
        supervisorPhone: '13800138006',
        farmAddress: '北京市顺义区某某特种养殖场',
        remarks: '特种养殖项目，需要专业监管',
        createdBy: adminId,
        updatedBy: adminId
      },
      {
        applicationNumber: 'APP007',
        contractNumber: 'CONTRACT007',
        productName: '农业贷款产品G',
        customerName: '吴九',
        idType: 'id_card',
        idNumber: '110101199007071234',
        assetType: 'sheep',
        assetQuantity: 40,
        supervisionStatus: 'pending',
        importTime: new Date('2024-02-05 13:10:00'),
        startTime: '2024-02-05',
        endTime: '2024-12-05',
        loanAmount: 600000.00,
        interestRate: 0.0590,
        loanTerm: 12,
        supervisorName: '郑监管员',
        supervisorPhone: '13800138007',
        farmAddress: '北京市房山区某某羊场',
        remarks: '大规模羊群养殖，需要加强监管',
        createdBy: adminId,
        updatedBy: adminId
      },
      {
        applicationNumber: 'APP008',
        contractNumber: 'CONTRACT008',
        productName: '农业贷款产品H',
        customerName: '郑十',
        idType: 'id_card',
        idNumber: '110101199008081234',
        assetType: 'pig',
        assetQuantity: 35,
        supervisionStatus: 'completed',
        importTime: new Date('2024-01-05 15:45:00'),
        startTime: '2024-01-05',
        endTime: '2024-03-05',
        loanAmount: 350000.00,
        interestRate: 0.0575,
        loanTerm: 3,
        supervisorName: '冯监管员',
        supervisorPhone: '13800138008',
        farmAddress: '北京市大兴区某某养猪场',
        remarks: '短期养殖项目，已顺利完成监管',
        createdBy: adminId,
        updatedBy: adminId
      }
    ];

    // 批量创建监管任务
    await SupervisionTask.bulkCreate(supervisionTasks);

    console.log(`✅ 成功添加 ${supervisionTasks.length} 条监管任务测试数据`);

    // 显示统计信息
    const stats = await SupervisionTask.findAll({
      attributes: [
        'supervisionStatus',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      group: ['supervisionStatus'],
      raw: true
    });

    console.log('📊 监管任务状态统计:');
    stats.forEach(stat => {
      const statusNames = {
        'pending': '待监管',
        'supervising': '监管中',
        'completed': '已完成',
        'suspended': '已暂停'
      };
      console.log(`   ${statusNames[stat.supervisionStatus] || stat.supervisionStatus}: ${stat.count} 条`);
    });

  } catch (error) {
    console.error('❌ 添加监管任务测试数据失败:', error);
    throw error;
  }
}

// 如果直接运行此文件
if (require.main === module) {
  seedSupervisionTasks()
    .then(() => {
      console.log('🎉 监管任务种子数据添加完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('💥 监管任务种子数据添加失败:', error);
      process.exit(1);
    });
}

module.exports = seedSupervisionTasks;
