import { AggregateRoot } from './aggregate-root.base'
import { AssessmentId, AuthorizationId, UserId, AdminUserId, RegionCode, Month } from '@/domain/value-objects'
import { RoleType, AssessmentResult } from '@/domain/enums'
import { DomainError } from '@/shared/exceptions'
import {
  MonthlyAssessmentPassedEvent,
  MonthlyAssessmentFailedEvent,
  MonthlyBypassGrantedEvent,
  FirstPlaceAchievedEvent,
} from '@/domain/events'

export interface MonthlyAssessmentProps {
  assessmentId: AssessmentId
  authorizationId: AuthorizationId
  userId: UserId
  roleType: RoleType
  regionCode: RegionCode
  assessmentMonth: Month
  monthIndex: number
  monthlyTarget: number
  cumulativeTarget: number
  monthlyCompleted: number
  cumulativeCompleted: number
  completedAt: Date | null
  localTeamCount: number
  totalTeamCount: number
  localPercentage: number
  localPercentagePass: boolean
  exceedRatio: number
  result: AssessmentResult
  rankingInRegion: number | null
  isFirstPlace: boolean
  isBypassed: boolean
  bypassedBy: AdminUserId | null
  bypassedAt: Date | null
  assessedAt: Date | null
  createdAt: Date
  updatedAt: Date
}

export class MonthlyAssessment extends AggregateRoot {
  private _assessmentId: AssessmentId
  private _authorizationId: AuthorizationId
  private _userId: UserId
  private _roleType: RoleType
  private _regionCode: RegionCode

  // 考核月份
  private _assessmentMonth: Month
  private _monthIndex: number

  // 考核目标
  private _monthlyTarget: number
  private _cumulativeTarget: number

  // 完成情况
  private _monthlyCompleted: number
  private _cumulativeCompleted: number
  private _completedAt: Date | null

  // 自有团队占比
  private _localTeamCount: number
  private _totalTeamCount: number
  private _localPercentage: number
  private _localPercentagePass: boolean

  // 超越目标占比
  private _exceedRatio: number

  // 考核结果
  private _result: AssessmentResult

  // 排名
  private _rankingInRegion: number | null
  private _isFirstPlace: boolean

  // 豁免
  private _isBypassed: boolean
  private _bypassedBy: AdminUserId | null
  private _bypassedAt: Date | null

  private _assessedAt: Date | null
  private _createdAt: Date
  private _updatedAt: Date

  // Getters
  get assessmentId(): AssessmentId {
    return this._assessmentId
  }
  get authorizationId(): AuthorizationId {
    return this._authorizationId
  }
  get userId(): UserId {
    return this._userId
  }
  get roleType(): RoleType {
    return this._roleType
  }
  get regionCode(): RegionCode {
    return this._regionCode
  }
  get assessmentMonth(): Month {
    return this._assessmentMonth
  }
  get monthIndex(): number {
    return this._monthIndex
  }
  get monthlyTarget(): number {
    return this._monthlyTarget
  }
  get cumulativeTarget(): number {
    return this._cumulativeTarget
  }
  get monthlyCompleted(): number {
    return this._monthlyCompleted
  }
  get cumulativeCompleted(): number {
    return this._cumulativeCompleted
  }
  get completedAt(): Date | null {
    return this._completedAt
  }
  get localTeamCount(): number {
    return this._localTeamCount
  }
  get totalTeamCount(): number {
    return this._totalTeamCount
  }
  get localPercentage(): number {
    return this._localPercentage
  }
  get localPercentagePass(): boolean {
    return this._localPercentagePass
  }
  get exceedRatio(): number {
    return this._exceedRatio
  }
  get result(): AssessmentResult {
    return this._result
  }
  get rankingInRegion(): number | null {
    return this._rankingInRegion
  }
  get isFirstPlace(): boolean {
    return this._isFirstPlace
  }
  get isBypassed(): boolean {
    return this._isBypassed
  }
  get bypassedBy(): AdminUserId | null {
    return this._bypassedBy
  }
  get bypassedAt(): Date | null {
    return this._bypassedAt
  }
  get assessedAt(): Date | null {
    return this._assessedAt
  }
  get createdAt(): Date {
    return this._createdAt
  }
  get updatedAt(): Date {
    return this._updatedAt
  }

  // 私有构造函数
  private constructor(props: MonthlyAssessmentProps) {
    super()
    this._assessmentId = props.assessmentId
    this._authorizationId = props.authorizationId
    this._userId = props.userId
    this._roleType = props.roleType
    this._regionCode = props.regionCode
    this._assessmentMonth = props.assessmentMonth
    this._monthIndex = props.monthIndex
    this._monthlyTarget = props.monthlyTarget
    this._cumulativeTarget = props.cumulativeTarget
    this._monthlyCompleted = props.monthlyCompleted
    this._cumulativeCompleted = props.cumulativeCompleted
    this._completedAt = props.completedAt
    this._localTeamCount = props.localTeamCount
    this._totalTeamCount = props.totalTeamCount
    this._localPercentage = props.localPercentage
    this._localPercentagePass = props.localPercentagePass
    this._exceedRatio = props.exceedRatio
    this._result = props.result
    this._rankingInRegion = props.rankingInRegion
    this._isFirstPlace = props.isFirstPlace
    this._isBypassed = props.isBypassed
    this._bypassedBy = props.bypassedBy
    this._bypassedAt = props.bypassedAt
    this._assessedAt = props.assessedAt
    this._createdAt = props.createdAt
    this._updatedAt = props.updatedAt
  }

  // 工厂方法 - 从数据库重建
  static fromPersistence(props: MonthlyAssessmentProps): MonthlyAssessment {
    return new MonthlyAssessment(props)
  }

  // 工厂方法 - 创建新考核
  static create(params: {
    authorizationId: AuthorizationId
    userId: UserId
    roleType: RoleType
    regionCode: RegionCode
    assessmentMonth: Month
    monthIndex: number
    monthlyTarget: number
    cumulativeTarget: number
  }): MonthlyAssessment {
    return new MonthlyAssessment({
      assessmentId: AssessmentId.generate(),
      authorizationId: params.authorizationId,
      userId: params.userId,
      roleType: params.roleType,
      regionCode: params.regionCode,
      assessmentMonth: params.assessmentMonth,
      monthIndex: params.monthIndex,
      monthlyTarget: params.monthlyTarget,
      cumulativeTarget: params.cumulativeTarget,
      monthlyCompleted: 0,
      cumulativeCompleted: 0,
      completedAt: null,
      localTeamCount: 0,
      totalTeamCount: 0,
      localPercentage: 0,
      localPercentagePass: false,
      exceedRatio: 0,
      result: AssessmentResult.NOT_ASSESSED,
      rankingInRegion: null,
      isFirstPlace: false,
      isBypassed: false,
      bypassedBy: null,
      bypassedAt: null,
      assessedAt: null,
      createdAt: new Date(),
      updatedAt: new Date(),
    })
  }

  /**
   * 执行考核评估
   */
  assess(params: {
    cumulativeCompleted: number
    localTeamCount: number
    totalTeamCount: number
    requireLocalPercentage: number
    exemptFromPercentageCheck: boolean
  }): void {
    this._cumulativeCompleted = params.cumulativeCompleted
    this._localTeamCount = params.localTeamCount
    this._totalTeamCount = params.totalTeamCount

    // 计算本地占比
    if (params.totalTeamCount > 0) {
      this._localPercentage = (params.localTeamCount / params.totalTeamCount) * 100
    } else {
      this._localPercentage = 0
    }

    // 判断占比是否达标
    this._localPercentagePass =
      params.exemptFromPercentageCheck || this._localPercentage >= params.requireLocalPercentage

    // 计算超越比例
    if (this._cumulativeTarget > 0) {
      this._exceedRatio = params.cumulativeCompleted / this._cumulativeTarget
    } else {
      this._exceedRatio = 0
    }

    // 记录达标时间（用于同比例时的排名）
    const cumulativePass = params.cumulativeCompleted >= this._cumulativeTarget
    if (cumulativePass && !this._completedAt) {
      this._completedAt = new Date()
    }

    // 判断考核结果
    if (this._isBypassed) {
      this._result = AssessmentResult.BYPASSED
    } else if (cumulativePass && this._localPercentagePass) {
      this._result = AssessmentResult.PASS
      this.addDomainEvent(
        new MonthlyAssessmentPassedEvent({
          assessmentId: this._assessmentId.value,
          userId: this._userId.value,
          roleType: this._roleType,
          month: this._assessmentMonth.value,
          cumulativeCompleted: params.cumulativeCompleted,
          cumulativeTarget: this._cumulativeTarget,
        }),
      )
    } else {
      this._result = AssessmentResult.FAIL
      this.addDomainEvent(
        new MonthlyAssessmentFailedEvent({
          assessmentId: this._assessmentId.value,
          userId: this._userId.value,
          roleType: this._roleType,
          month: this._assessmentMonth.value,
          cumulativeCompleted: params.cumulativeCompleted,
          cumulativeTarget: this._cumulativeTarget,
          reason: !cumulativePass ? '累计目标未达成' : '本地占比不足',
        }),
      )
    }

    this._assessedAt = new Date()
    this._updatedAt = new Date()
  }

  /**
   * 授予单月豁免
   */
  grantBypass(adminId: AdminUserId): void {
    if (this._isBypassed) {
      throw new DomainError('已授予豁免')
    }

    this._isBypassed = true
    this._bypassedBy = adminId
    this._bypassedAt = new Date()
    this._result = AssessmentResult.BYPASSED
    this._updatedAt = new Date()

    this.addDomainEvent(
      new MonthlyBypassGrantedEvent({
        assessmentId: this._assessmentId.value,
        userId: this._userId.value,
        roleType: this._roleType,
        month: this._assessmentMonth.value,
        grantedBy: adminId.value,
      }),
    )
  }

  /**
   * 设置排名
   */
  setRanking(rank: number, isFirst: boolean): void {
    this._rankingInRegion = rank
    this._isFirstPlace = isFirst
    this._updatedAt = new Date()

    if (isFirst) {
      this.addDomainEvent(
        new FirstPlaceAchievedEvent({
          assessmentId: this._assessmentId.value,
          userId: this._userId.value,
          roleType: this._roleType,
          regionCode: this._regionCode.value,
          month: this._assessmentMonth.value,
        }),
      )
    }
  }

  /**
   * 更新完成数量
   */
  updateProgress(monthlyCompleted: number, cumulativeCompleted: number): void {
    this._monthlyCompleted = monthlyCompleted
    this._cumulativeCompleted = cumulativeCompleted
    this._updatedAt = new Date()

    // 计算超越比例
    if (this._cumulativeTarget > 0) {
      this._exceedRatio = cumulativeCompleted / this._cumulativeTarget
    }

    // 记录达标时间
    if (cumulativeCompleted >= this._cumulativeTarget && !this._completedAt) {
      this._completedAt = new Date()
    }
  }

  /**
   * 是否达标
   */
  isPassed(): boolean {
    return this._result === AssessmentResult.PASS || this._result === AssessmentResult.BYPASSED
  }

  /**
   * 是否未达标
   */
  isFailed(): boolean {
    return this._result === AssessmentResult.FAIL
  }

  /**
   * 转换为持久化数据
   */
  toPersistence(): Record<string, any> {
    return {
      id: this._assessmentId.value,
      authorizationId: this._authorizationId.value,
      userId: this._userId.accountSequence,
      accountSequence: this._userId.accountSequence,
      roleType: this._roleType,
      regionCode: this._regionCode.value,
      assessmentMonth: this._assessmentMonth.value,
      monthIndex: this._monthIndex,
      monthlyTarget: this._monthlyTarget,
      cumulativeTarget: this._cumulativeTarget,
      monthlyCompleted: this._monthlyCompleted,
      cumulativeCompleted: this._cumulativeCompleted,
      completedAt: this._completedAt,
      localTeamCount: this._localTeamCount,
      totalTeamCount: this._totalTeamCount,
      localPercentage: this._localPercentage,
      localPercentagePass: this._localPercentagePass,
      exceedRatio: this._exceedRatio,
      result: this._result,
      rankingInRegion: this._rankingInRegion,
      isFirstPlace: this._isFirstPlace,
      isBypassed: this._isBypassed,
      bypassedBy: this._bypassedBy?.accountSequence || null,
      bypassedAt: this._bypassedAt,
      assessedAt: this._assessedAt,
      createdAt: this._createdAt,
      updatedAt: this._updatedAt,
    }
  }
}
