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

const CompletedSupervision = sequelize.define('CompletedSupervision', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    comment: '主键ID'
  },
  applicationNumber: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true,
    comment: '申请单号'
  },
  contractNumber: {
    type: DataTypes.STRING(50),
    allowNull: false,
    comment: '放款合同编号'
  },
  productName: {
    type: DataTypes.STRING(100),
    allowNull: false,
    comment: '产品名称'
  },
  customerName: {
    type: DataTypes.STRING(50),
    allowNull: false,
    comment: '客户姓名'
  },
  idType: {
    type: DataTypes.ENUM('ID_CARD', 'PASSPORT', 'OTHER'),
    allowNull: false,
    defaultValue: 'ID_CARD',
    comment: '证件类型'
  },
  idNumber: {
    type: DataTypes.STRING(50),
    allowNull: false,
    comment: '证件号码'
  },
  assetType: {
    type: DataTypes.STRING(50),
    allowNull: false,
    comment: '养殖生资种类'
  },
  assetQuantity: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '监管生资数量'
  },
  totalRepaymentPeriods: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '总还款期数'
  },
  settlementStatus: {
    type: DataTypes.ENUM('settled', 'unsettled', 'partial'),
    allowNull: false,
    defaultValue: 'unsettled',
    comment: '结清状态'
  },
  settlementDate: {
    type: DataTypes.DATEONLY,
    allowNull: true,
    comment: '结清日期'
  },
  importTime: {
    type: DataTypes.DATE,
    allowNull: false,
    comment: '结清任务导入时间'
  },
  settlementAmount: {
    type: DataTypes.DECIMAL(15, 2),
    allowNull: true,
    comment: '结清金额'
  },
  remainingAmount: {
    type: DataTypes.DECIMAL(15, 2),
    allowNull: true,
    comment: '剩余金额'
  },
  settlementNotes: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '结清备注'
  },
  createdBy: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '创建人ID'
  },
  updatedBy: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '更新人ID'
  }
}, {
  tableName: 'completed_supervisions',
  timestamps: true,
  underscored: false,
  createdAt: 'createdAt',
  updatedAt: 'updatedAt',
  comment: '监管任务已结项表'
});

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

module.exports = CompletedSupervision;
