const Department = require('../models/Department');
const Position = require('../models/Position');
const AdminStaff = require('../models/AdminStaff');
const sequelize = require('../config/database');

// 测试数据
const departmentsData = [
  {
    name: '防疫部门',
    description: '负责疫情防控和动物健康监测'
  },
  {
    name: '行政管理部门',
    description: '负责日常行政事务管理'
  },
  {
    name: '数据分析部门',
    description: '负责数据收集、分析和报告'
  },
  {
    name: '市场监管部门',
    description: '负责市场价格监管和交易监督'
  }
];

const positionsData = [
  { name: '部门主管', has_permission: true },
  { name: '防疫专员', has_permission: false },
  { name: '行政主管', has_permission: true },
  { name: '行政助理', has_permission: false },
  { name: '数据分析主管', has_permission: true },
  { name: '数据分析师', has_permission: false },
  { name: '市场监管主管', has_permission: true },
  { name: '市场监管员', has_permission: false }
];

const adminStaffData = [
  {
    name: '张三',
    phone: '13800138001',
    id_card: '110101199003070010',
    status: true
  },
  {
    name: '李四',
    phone: '13800138002',
    id_card: '110101199104150020',
    status: true
  },
  {
    name: '王五',
    phone: '13800138003',
    id_card: '110101199205200030',
    status: true
  },
  {
    name: '赵六',
    phone: '13800138004',
    id_card: '110101199306250040',
    status: true
  },
  {
    name: '孙七',
    phone: '13800138005',
    id_card: '110101199407300050',
    status: true
  },
  {
    name: '周八',
    phone: '13800138006',
    id_card: '110101199508310060',
    status: false
  },
  {
    name: '吴九',
    phone: '13800138007',
    id_card: '110101199609150070',
    status: true
  },
  {
    name: '郑十',
    phone: '13800138008',
    id_card: '110101199710200080',
    status: true
  }
];

// 添加测试数据到数据库
async function seedData() {
  try {
    console.log('开始添加测试数据...');
    
    // 先检查是否已有行政人员数据
    const existingStaffCount = await AdminStaff.count();
    if (existingStaffCount > 0) {
      console.log(`数据库中已有 ${existingStaffCount} 个行政人员数据，跳过所有数据添加`);
      process.exit(0);
    }
    
    // 开始事务
    await sequelize.transaction(async (transaction) => {
      // 先删除可能存在的软删除数据
      await AdminStaff.destroy({ where: {}, force: true, transaction });
      await Position.destroy({ where: {}, force: true, transaction });
      await Department.destroy({ where: {}, force: true, transaction });
      
      console.log('已清空所有表数据（包括软删除的数据）');
      
      // 添加部门数据
      console.log('添加部门数据...');
      const departments = await Department.bulkCreate(departmentsData, {
        transaction,
        ignoreDuplicates: true
      });
      console.log(`成功添加 ${departments.length} 个部门`);
      
      // 添加岗位数据，为每个部门添加相应的岗位
      console.log('添加岗位数据...');
      let positionId = 1;
      const createdPositions = [];
      
      for (let i = 0; i < departments.length; i++) {
        const deptId = departments[i].id;
        // 每个部门添加2个岗位
        for (let j = 0; j < 2; j++) {
          const posIndex = i * 2 + j;
          if (posIndex < positionsData.length) {
            const position = await Position.create({
              department_id: deptId,
              name: positionsData[posIndex].name,
              has_permission: positionsData[posIndex].has_permission
            }, {
              transaction
            });
            createdPositions.push(position);
            console.log(`  添加岗位: ${position.name} (ID: ${position.id}, 部门ID: ${deptId})`);
          }
        }
      }
      
      console.log(`总共添加了 ${createdPositions.length} 个岗位`);
      
      // 添加行政人员数据，关联到实际创建的部门和岗位
      console.log('添加行政人员数据...');
      const createdStaff = [];
      
      for (let i = 0; i < adminStaffData.length; i++) {
        const staffData = adminStaffData[i];
        // 根据索引分配部门和岗位
        const deptIndex = Math.floor(i / 2); // 每2个人员属于同一个部门
        const posIndex = i;
        
        if (deptIndex < departments.length && posIndex < createdPositions.length) {
          const staff = await AdminStaff.create({
            name: staffData.name,
            department_id: departments[deptIndex].id,
            position_id: createdPositions[posIndex].id,
            phone: staffData.phone,
            id_card: staffData.id_card,
            status: staffData.status
          }, {
            transaction
          });
          createdStaff.push(staff);
          console.log(`  添加行政人员: ${staff.name} (ID: ${staff.id}, 部门: ${departments[deptIndex].name})`);
        }
      }
      
      console.log(`总共添加了 ${createdStaff.length} 个行政人员`);
    });
    
    console.log('所有测试数据添加完成！');
    process.exit(0);
  } catch (error) {
    console.error('添加测试数据失败:', error);
    process.exit(1);
  }
}

// 执行数据添加
seedData();