/**
 * 模型索引文件
 * @file index.js
 * @description 导出所有模型并建立关联关系
 */
const { sequelize } = require('../config/database-simple');
const BaseModel = require('./BaseModel');
const Farm = require('./Farm');
const Animal = require('./Animal');
const Device = require('./Device');
const Alert = require('./Alert');
const User = require('./User');
const Role = require('./Role');
const UserRole = require('./UserRole');
const Product = require('./Product');
const Order = require('./Order');
const OrderItem = require('./OrderItem');
const SensorData = require('./SensorData');
const SystemConfig = require('./SystemConfig');
const MenuPermission = require('./MenuPermission');
const RoleMenuPermission = require('./RoleMenuPermission');
const Permission = require('./Permission');
const IotXqClient = require('./IotXqClient');
const IotJbqServer = require('./IotJbqServer');
const IotJbqClient = require('./IotJbqClient');
const ElectronicFence = require('./ElectronicFence');
const ElectronicFencePoint = require('./ElectronicFencePoint');
const Pen = require('./Pen');
const CattlePen = require('./CattlePen');
const CattleBatch = require('./CattleBatch');
const CattleBatchAnimal = require('./CattleBatchAnimal');
const CattleTransferRecord = require('./CattleTransferRecord');
const CattleExitRecord = require('./CattleExitRecord');
const IotCattle = require('./IotCattle');
const CattleType = require('./CattleType');
const CattleUser = require('./CattleUser');
const FormLog = require('./FormLog');
const OperationLog = require('./OperationLog');

// 注意：模型初始化在各自的模型文件中完成

// 建立模型之间的关联关系

// 养殖场与动物的一对多关系
Farm.hasMany(Animal, { 
  foreignKey: 'farm_id',
  as: 'animals',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
Animal.belongsTo(Farm, { 
  foreignKey: 'farm_id',
  as: 'farm'
});

// 养殖场与牛只的一对多关系
Farm.hasMany(IotCattle, { 
  foreignKey: 'orgId',
  as: 'cattle',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
IotCattle.belongsTo(Farm, { 
  foreignKey: 'orgId',
  as: 'farm'
});

// 牛只品种与牛只的一对多关系（在模型初始化后定义）

// 养殖场与设备的一对多关系
Farm.hasMany(Device, { 
  foreignKey: 'farm_id',
  as: 'devices',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
Device.belongsTo(Farm, { 
  foreignKey: 'farm_id',
  as: 'farm'
});

// 养殖场与预警的一对多关系
Farm.hasMany(Alert, { 
  foreignKey: 'farm_id',
  as: 'alerts',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
Alert.belongsTo(Farm, { 
  foreignKey: 'farm_id',
  as: 'farm'
});

// 设备与预警的一对多关系
Device.hasMany(Alert, { 
  foreignKey: 'device_id',
  as: 'alerts',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
Alert.belongsTo(Device, { 
  foreignKey: 'device_id',
  as: 'device'
});

// 设备与传感器数据的一对多关系
Device.hasMany(SensorData, { 
  foreignKey: 'device_id',
  as: 'sensorData',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
SensorData.belongsTo(Device, { 
  foreignKey: 'device_id',
  as: 'device'
});

// 养殖场与传感器数据的一对多关系
Farm.hasMany(SensorData, { 
  foreignKey: 'farm_id',
  as: 'sensorData',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
SensorData.belongsTo(Farm, { 
  foreignKey: 'farm_id',
  as: 'farm'
});

// 用户与角色的直接关联关系（通过roles字段）
User.belongsTo(Role, {
  foreignKey: 'roles',
  as: 'role'
});
Role.hasMany(User, {
  foreignKey: 'roles',
  as: 'users'
});

// 用户与角色的多对多关系（暂时注释掉，当前使用直接关联）
// User.belongsToMany(Role, { 
//   through: UserRole, 
//   foreignKey: 'user_id', 
//   otherKey: 'role_id', 
//   as: 'userRoles'
// });
// Role.belongsToMany(User, { 
//   through: UserRole, 
//   foreignKey: 'role_id',
//   otherKey: 'user_id', 
//   as: 'roleUsers'
// });

// 用户与订单的一对多关系
User.hasMany(Order, { 
  foreignKey: 'user_id',
  as: 'orders',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
Order.belongsTo(User, { 
  foreignKey: 'user_id',
  as: 'user'
});

// 订单与订单项的一对多关系
Order.hasMany(OrderItem, { 
  foreignKey: 'order_id',
  as: 'orderItems',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
OrderItem.belongsTo(Order, { 
  foreignKey: 'order_id',
  as: 'order'
});

// 产品与订单项的一对多关系
Product.hasMany(OrderItem, { 
  foreignKey: 'product_id',
  as: 'orderItems',
  onDelete: 'RESTRICT',
  onUpdate: 'CASCADE'
});
OrderItem.belongsTo(Product, { 
  foreignKey: 'product_id',
  as: 'product'
});

// 菜单权限的自关联关系（已在associate方法中定义）

// 角色与菜单权限的多对多关系
Role.belongsToMany(MenuPermission, {
  through: RoleMenuPermission,
  foreignKey: 'role_id',
  otherKey: 'menu_permission_id',
  as: 'menuPermissions'
});

MenuPermission.belongsToMany(Role, {
  through: RoleMenuPermission,
  foreignKey: 'menu_permission_id',
  otherKey: 'role_id',
  as: 'roles'
});

// 角色与权限的多对多关系
Role.belongsToMany(Permission, {
  through: 'role_permissions',
  as: 'permissions',
  foreignKey: 'role_id',
  otherKey: 'permission_id'
});

Permission.belongsToMany(Role, {
  through: 'role_permissions',
  as: 'roles',
  foreignKey: 'permission_id',
  otherKey: 'role_id'
});

// 农场与栏舍的一对多关系
Farm.hasMany(Pen, { 
  foreignKey: 'farm_id',
  as: 'pens',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
Pen.belongsTo(Farm, { 
  foreignKey: 'farm_id',
  as: 'farm'
});

// 农场与电子围栏的一对多关系
Farm.hasMany(ElectronicFence, { 
  foreignKey: 'farm_id',
  as: 'electronicFences',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
ElectronicFence.belongsTo(Farm, { 
  foreignKey: 'farm_id',
  as: 'farm'
});

// 电子围栏与坐标点的一对多关系
ElectronicFence.hasMany(ElectronicFencePoint, {
  foreignKey: 'fence_id',
  as: 'points',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
ElectronicFencePoint.belongsTo(ElectronicFence, {
  foreignKey: 'fence_id',
  as: 'fence'
});

// 用户与坐标点的关联关系
User.hasMany(ElectronicFencePoint, {
  foreignKey: 'created_by',
  as: 'createdFencePoints',
  onDelete: 'SET NULL',
  onUpdate: 'CASCADE'
});
ElectronicFencePoint.belongsTo(User, {
  foreignKey: 'created_by',
  as: 'creator'
});

User.hasMany(ElectronicFencePoint, {
  foreignKey: 'updated_by',
  as: 'updatedFencePoints',
  onDelete: 'SET NULL',
  onUpdate: 'CASCADE'
});
ElectronicFencePoint.belongsTo(User, {
  foreignKey: 'updated_by',
  as: 'updater'
});

// 农场与栏舍设置的一对多关系
Farm.hasMany(CattlePen, { 
  foreignKey: 'farm_id',
  as: 'cattlePens',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
CattlePen.belongsTo(Farm, { 
  foreignKey: 'farm_id',
  as: 'farm'
});

// 栏舍设置与动物的一对多关系
CattlePen.hasMany(Animal, { 
  foreignKey: 'pen_id',
  as: 'animals',
  onDelete: 'SET NULL',
  onUpdate: 'CASCADE'
});
Animal.belongsTo(CattlePen, { 
  foreignKey: 'pen_id',
  as: 'pen'
});

// 农场与批次设置的一对多关系
Farm.hasMany(CattleBatch, { 
  foreignKey: 'farm_id',
  as: 'cattleBatches',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
CattleBatch.belongsTo(Farm, { 
  foreignKey: 'farm_id',
  as: 'farm'
});

// 栏舍设置与牛只的一对多关系
CattlePen.hasMany(IotCattle, {
  foreignKey: 'penId',
  as: 'cattle',
  onDelete: 'SET NULL',
  onUpdate: 'CASCADE'
});
IotCattle.belongsTo(CattlePen, {
  foreignKey: 'penId',
  as: 'pen'
});

// 批次设置与牛只的一对多关系
CattleBatch.hasMany(IotCattle, {
  foreignKey: 'batchId',
  as: 'cattle',
  onDelete: 'SET NULL',
  onUpdate: 'CASCADE'
});
IotCattle.belongsTo(CattleBatch, {
  foreignKey: 'batchId',
  as: 'batch'
});

// 牛只与转栏记录的一对多关系
IotCattle.hasMany(CattleTransferRecord, {
  foreignKey: 'animalId',
  as: 'transferRecords',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
CattleTransferRecord.belongsTo(IotCattle, {
  foreignKey: 'animalId',
  as: 'cattle'
});

// 栏舍设置与转栏记录的一对多关系（转出）
CattlePen.hasMany(CattleTransferRecord, {
  foreignKey: 'fromPenId',
  as: 'fromTransferRecords',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
CattleTransferRecord.belongsTo(CattlePen, {
  foreignKey: 'fromPenId',
  as: 'fromPen'
});

// 栏舍设置与转栏记录的一对多关系（转入）
CattlePen.hasMany(CattleTransferRecord, {
  foreignKey: 'toPenId',
  as: 'toTransferRecords',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
CattleTransferRecord.belongsTo(CattlePen, {
  foreignKey: 'toPenId',
  as: 'toPen'
});

// 农场与转栏记录的一对多关系
Farm.hasMany(CattleTransferRecord, {
  foreignKey: 'farmId',
  as: 'transferRecords',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
CattleTransferRecord.belongsTo(Farm, {
  foreignKey: 'farmId',
  as: 'farm'
});

// 牛只与离栏记录的一对多关系
IotCattle.hasMany(CattleExitRecord, {
  foreignKey: 'animalId',
  as: 'exitRecords',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
CattleExitRecord.belongsTo(IotCattle, {
  foreignKey: 'animalId',
  as: 'cattle'
});

// 栏舍设置与离栏记录的一对多关系
CattlePen.hasMany(CattleExitRecord, {
  foreignKey: 'originalPenId',
  as: 'exitRecords',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
CattleExitRecord.belongsTo(CattlePen, {
  foreignKey: 'originalPenId',
  as: 'originalPen'
});

// 农场与离栏记录的一对多关系
Farm.hasMany(CattleExitRecord, {
  foreignKey: 'farmId',
  as: 'exitRecords',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
CattleExitRecord.belongsTo(Farm, {
  foreignKey: 'farmId',
  as: 'farm'
});

// 初始化所有模型
const initModels = () => {
  // 初始化CattleType模型
  CattleType.init(sequelize);
  // 初始化CattleUser模型
  CattleUser.init(sequelize);
  // 初始化FormLog模型
  FormLog.init(sequelize);
  // 初始化OperationLog模型
  OperationLog.init(sequelize);
};

// 初始化模型
initModels();

// 在模型初始化后定义CattleType的关联关系
CattleType.hasMany(IotCattle, { 
  foreignKey: 'varieties',
  as: 'cattle',
  onDelete: 'RESTRICT',
  onUpdate: 'CASCADE'
});
IotCattle.belongsTo(CattleType, { 
  foreignKey: 'varieties',
  as: 'cattleType'
});

// 在模型初始化后定义CattleUser的关联关系
CattleUser.hasMany(IotCattle, { 
  foreignKey: 'strain',
  as: 'cattle',
  onDelete: 'RESTRICT',
  onUpdate: 'CASCADE'
});
IotCattle.belongsTo(CattleUser, { 
  foreignKey: 'strain',
  as: 'cattleUser'
});

// 用户与操作日志的一对多关系
User.hasMany(OperationLog, {
  foreignKey: 'user_id',
  as: 'operationLogs',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});
OperationLog.belongsTo(User, {
  foreignKey: 'user_id',
  as: 'user'
});

// 同步所有模型
const syncModels = async (options = {}) => {
  try {
    await sequelize.sync(options);
    console.log('所有模型已同步到数据库');
    return true;
  } catch (error) {
    console.error('模型同步失败:', error);
    return false;
  }
};

module.exports = {
  sequelize,
  BaseModel,
  Farm,
  Animal,
  Device,
  Alert,
  User,
  Role,
  UserRole,
  Product,
  Order,
  OrderItem,
  SensorData,
  SystemConfig,
  MenuPermission,
  RoleMenuPermission,
  Permission,
  IotXqClient,
  IotJbqServer,
  IotJbqClient,
  ElectronicFence,
  ElectronicFencePoint,
  Pen,
  CattlePen,
  CattleBatch,
  CattleBatchAnimal,
  CattleTransferRecord,
  CattleExitRecord,
  IotCattle,
  CattleType,
  CattleUser,
  FormLog,
  OperationLog,
  syncModels
};

// 调用模型的associate方法建立关联关系
const models = {
  Farm,
  Animal,
  Device,
  Alert,
  User,
  Role,
  UserRole,
  Product,
  Order,
  OrderItem,
  SensorData,
  SystemConfig,
  MenuPermission,
  RoleMenuPermission,
  Permission,
  IotXqClient,
  IotJbqServer,
  IotJbqClient,
  ElectronicFence,
  ElectronicFencePoint,
  Pen,
  CattlePen,
  CattleBatch,
  CattleBatchAnimal,
  CattleTransferRecord,
  CattleExitRecord,
  IotCattle,
  CattleType,
  CattleUser,
  FormLog,
  OperationLog
};

// 建立关联关系
Object.keys(models).forEach(modelName => {
  if (models[modelName].associate) {
    models[modelName].associate(models);
  }
});