const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

const Project = sequelize.define('Project', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: DataTypes.STRING(100),
    allowNull: false,
    comment: '项目名称'
  },
  status: {
    type: DataTypes.ENUM('supervision', 'completed'),
    allowNull: false,
    defaultValue: 'supervision',
    comment: '项目状态：supervision-监管中，completed-已结项'
  },
  farmName: {
    type: DataTypes.STRING(200),
    allowNull: false,
    field: 'farmName',
    comment: '养殖场名称'
  },
  supervisionObject: {
    type: DataTypes.STRING(50),
    allowNull: false,
    field: 'supervisionObject',
    comment: '监管对象'
  },
  supervisionQuantity: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    field: 'supervisionQuantity',
    comment: '监管数量'
  },
  supervisionPeriod: {
    type: DataTypes.STRING(50),
    allowNull: false,
    field: 'supervisionPeriod',
    comment: '监管周期'
  },
  supervisionAmount: {
    type: DataTypes.DECIMAL(15, 2),
    allowNull: false,
    defaultValue: 0.00,
    field: 'supervisionAmount',
    comment: '监管金额'
  },
  startTime: {
    type: DataTypes.DATEONLY,
    allowNull: false,
    field: 'startTime',
    comment: '起始时间'
  },
  endTime: {
    type: DataTypes.DATEONLY,
    allowNull: false,
    field: 'endTime',
    comment: '结束时间'
  },
  earTag: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    field: 'earTag',
    comment: '耳标数量'
  },
  collar: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    field: 'collar',
    comment: '项圈数量'
  },
  host: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    field: 'host',
    comment: '主机数量'
  },
  loanOfficer: {
    type: DataTypes.STRING(100),
    allowNull: true,
    field: 'loanOfficer',
    comment: '贷款专员'
  },
  description: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '项目描述'
  },
  createdBy: {
    type: DataTypes.INTEGER,
    allowNull: true,
    field: 'createdBy',
    comment: '创建人ID'
  },
  updatedBy: {
    type: DataTypes.INTEGER,
    allowNull: true,
    field: 'updatedBy',
    comment: '更新人ID'
  }
}, {
  tableName: 'projects',
  timestamps: true,
  underscored: false,
  createdAt: 'createdAt',
  updatedAt: 'updatedAt',
  comment: '项目清单表'
});

// 定义关联关系
Project.associate = (models) => {
  // 项目与用户关联（创建人）
  Project.belongsTo(models.User, {
    foreignKey: { name: 'createdBy', field: 'createdBy' },
    targetKey: 'id',
    as: 'creator'
  });
  
  // 项目与用户关联（更新人）
  Project.belongsTo(models.User, {
    foreignKey: { name: 'updatedBy', field: 'updatedBy' },
    targetKey: 'id',
    as: 'updater'
  });
};

module.exports = Project;
