import { Component, Input } from '@angular/core';
import { CommonModule } from '@angular/common';

type ArtDoneRateData = {
  completionRate?: number;
  areaCountFloor?: number;
  totalStartCount?: number;
  totalDoneCount?: number;
};

@Component({
  selector: 'art-done-rate',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div class="done-rate" [ngStyle]="{ color: color }">
      <span class="rate">{{ format(absRatePercent) }}%</span>
      <span *ngIf="diff > 0" class="trend">↑ {{ format(diff) }}%</span>
      <span *ngIf="diff < 0" class="trend">↓ {{ format(diff) }}%</span>
      <span *ngIf="!simple" class="meta">({{ doneCount }}/{{ startCount }})</span>
    </div>
  `,
  styles: [
    `
      .done-rate {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        font-size: 12px;
      }

      .rate {
        font-weight: 700;
      }

      .trend {
        font-weight: 600;
      }

      .meta {
        color: #595959;
      }
    `,
  ],
})
export class ArtDoneRateComponent {
  @Input('data') item: ArtDoneRateData = {};
  @Input() simple = false;

  get startCount(): number {
    return Number(this.item?.totalStartCount || 0);
  }

  get doneCount(): number {
    return Number(this.item?.totalDoneCount || 0);
  }

  private get normalizedRatePercent(): number {
    const value = Number(this.item?.completionRate || 0);
    if (!Number.isFinite(value) || value <= 0) return 0;
    // 兼容 0~1 和 0~100 两种输入
    return value <= 1 ? value * 100 : value;
  }

  get absRatePercent(): number {
    return Math.max(0, this.normalizedRatePercent);
  }

  get diff(): number {
    const floor = Number(this.item?.areaCountFloor || 0);
    if (!Number.isFinite(floor) || floor < 0 || floor >= averageDoneRates.length) return 0;
    return this.absRatePercent - averageDoneRates[floor];
  }

  get color(): string {
    if (this.startCount < 1000) return '#8c8c8c';
    if (this.diff > 0) return '#cf1322';
    if (this.diff < 0) return '#389e0d';
    return '#262626';
  }

  format(num: number): string {
    if (!Number.isFinite(num)) return '0.00';
    return Math.abs(num).toFixed(2);
  }
}

const averageDoneRates: number[] = [87.78, 84.69, 77.44, 74.39, 73.31, 73.01, 71.45, 68.00, 66.75, 64.99, 63.64, 64.12, 63.93, 62.26, 57.40];

/*
Loading file: area_count_done_rate.js
区块数区间: 0-100, 完成率: 87.78%
区块数区间: 100-200, 完成率: 84.69%
区块数区间: 200-300, 完成率: 77.44%
区块数区间: 300-400, 完成率: 74.39%
区块数区间: 400-500, 完成率: 73.31%
区块数区间: 500-600, 完成率: 73.01%
区块数区间: 600-700, 完成率: 71.45%
区块数区间: 700-800, 完成率: 68.00%
区块数区间: 800-900, 完成率: 66.75%
区块数区间: 900-1000, 完成率: 64.99%
区块数区间: 1000-1100, 完成率: 63.64%
区块数区间: 1100-1200, 完成率: 64.12%
区块数区间: 1200-1300, 完成率: 63.93%
区块数区间: 1300-1400, 完成率: 62.26%
区块数区间: 1400-1500, 完成率: 57.40%
*/