import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn, OneToMany, CreateDateColumn, UpdateDateColumn } from 'typeorm';
import { DeleteStatus, DisabledStatus } from '@/share/types';

export enum AreaLevel {
  PROVINCE = 1, // 省/直辖市
  CITY = 2,     // 市
  DISTRICT = 3  // 区/县
}

@Entity({ name: 'areas' })
export class AreaEntity {
  @PrimaryGeneratedColumn({ unsigned: true, comment: '区域ID' })
  id!: number;

  @Column({ name: 'parent_id', type: 'int', unsigned: true, nullable: true, default: null, comment: '父级区域ID，null表示顶级（省/直辖市）' })
  parentId!: number | null;

  @Column({ name: 'name', type: 'varchar', length: 100, comment: '区域名称' })
  name!: string;

  @Column({
    name: 'level',
    type: 'enum',
    enum: AreaLevel,
    comment: '层级: 1:省/直辖市, 2:市, 3:区/县'
  })
  level!: AreaLevel;

  @Column({ name: 'code', type: 'varchar', length: 20, unique: true, comment: '行政区划代码' })
  code!: string;

  // 自关联关系 - 父级区域
  @ManyToOne(() => AreaEntity, (area) => area.children)
  @JoinColumn({ name: 'parent_id', referencedColumnName: 'id' })
  parent!: AreaEntity | null;

  // 自关联关系 - 子级区域
  @OneToMany(() => AreaEntity, (area) => area.parent)
  children!: AreaEntity[];

  @Column({ name: 'is_disabled', type: 'int', default: DisabledStatus.ENABLED, comment: '是否禁用(0:启用,1:禁用)' })
  isDisabled!: DisabledStatus;

  @Column({ name: 'is_deleted', type: 'int', default: DeleteStatus.NOT_DELETED, comment: '是否删除(0:未删除,1:已删除)' })
  isDeleted!: DeleteStatus;

  @Column({ name: 'created_by', type: 'int', nullable: true, comment: '创建人ID' })
  createdBy!: number | null;

  @Column({ name: 'updated_by', type: 'int', nullable: true, comment: '更新人ID' })
  updatedBy!: number | null;

  @CreateDateColumn({ name: 'created_at', type: 'timestamp' })
  createdAt!: Date;

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamp' })
  updatedAt!: Date;

  constructor(partial?: Partial<AreaEntity>) {
    Object.assign(this, partial);
  }
}