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

const InstallationTask = sequelize.define('InstallationTask', {
    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: '养殖生资种类'
    },
    equipmentToInstall: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: '待安装设备'
    },
    installationStatus: {
      type: DataTypes.ENUM('pending', 'in-progress', 'completed', 'failed'),
      allowNull: false,
      defaultValue: 'pending',
      comment: '安装状态'
    },
    taskGenerationTime: {
      type: DataTypes.DATE,
      allowNull: false,
      comment: '生成安装任务时间'
    },
    completionTime: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '安装完成生效时间'
    },
    installationNotes: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '安装备注'
    },
    installerName: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: '安装员姓名'
    },
    installerPhone: {
      type: DataTypes.STRING(20),
      allowNull: true,
      comment: '安装员电话'
    },
    installationAddress: {
      type: DataTypes.STRING(200),
      allowNull: true,
      comment: '安装地址'
    },
    createdBy: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '创建人ID'
    },
    updatedBy: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: '更新人ID'
    }
  }, {
    tableName: 'installation_tasks',
    timestamps: true,
    underscored: false,
    createdAt: 'createdAt',
    updatedAt: 'updatedAt',
    comment: '待安装任务表'
  });

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

module.exports = InstallationTask;