import { Component, OnInit } from '@angular/core';
import { CommonModule, NgIf, NgFor, DatePipe } from '@angular/common';
import { debounceTime } from 'rxjs/operators';

// NG-ZORRO 组件
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzGridModule } from 'ng-zorro-antd/grid';
import { NzStatisticModule } from 'ng-zorro-antd/statistic';
import { NzSpinModule } from 'ng-zorro-antd/spin';
import { NzTableModule } from 'ng-zorro-antd/table';
import { NzDividerModule } from 'ng-zorro-antd/divider';
import { NzProgressModule } from 'ng-zorro-antd/progress';
import { NzPageHeaderModule } from 'ng-zorro-antd/page-header';
import { NzTagModule } from 'ng-zorro-antd/tag';
import { NzToolTipModule } from 'ng-zorro-antd/tooltip';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [
    CommonModule,
    NgIf,
    NgFor,
    DatePipe,
    // NG-ZORRO 模块
    NzCardModule,
    NzIconModule,
    NzGridModule,
    NzStatisticModule,
    NzSpinModule,
    NzTableModule,
    NzDividerModule,
    NzProgressModule,
    NzPageHeaderModule,
    NzTagModule,
    NzToolTipModule,
  ],
  providers: [NzModalService, NzMessageService],
  template: `
    <div class="dashboard-container">
      <nz-page-header [nzGhost]="false">
        <nz-page-header-title>数据看板</nz-page-header-title>
        <nz-page-header-extra>
          <span
            nz-icon
            nzType="sync"
            nzTheme="outline"
            (click)="refreshData()"
          ></span>
        </nz-page-header-extra>
        <nz-page-header-content>
          <p>
            最后更新时间：{{ lastUpdateTime | date : 'yyyy-MM-dd HH:mm:ss' }}
          </p>
        </nz-page-header-content>
      </nz-page-header>

      <nz-spin [nzSpinning]="isLoading" nzTip="数据加载中...">
        <!-- 核心指标卡片 -->
        <div class="metrics-container">
          <nz-row [nzGutter]="16">
            <!-- 总用户数 -->
            <nz-col [nzXs]="24" [nzSm]="12" [nzMd]="8" [nzLg]="6">
              <nz-card nzHoverable>
                <nz-statistic
                  [nzTitle]="'总用户数'"
                  [nzValue]="totalUsers"
                  [nzPrefix]="userIcon"
                  [nzSuffix]="'人'"
                  [nzValueStyle]="{ color: '#1890ff' }"
                ></nz-statistic>
                <ng-template #userIcon>
                  <span nz-icon nzType="user" nzTheme="outline"></span>
                </ng-template>
                <div class="compare">
                  <span
                    >较昨日
                    <nz-tag [nzColor]="userChange >= 0 ? 'green' : 'red'">
                      {{ userChange >= 0 ? '+' : '' }}{{ userChange }}%
                    </nz-tag></span
                  >
                </div>
              </nz-card>
            </nz-col>

            <!-- 今日活跃用户数 -->
            <nz-col [nzXs]="24" [nzSm]="12" [nzMd]="8" [nzLg]="6">
              <nz-card nzHoverable>
                <nz-statistic
                  [nzTitle]="'今日活跃用户'"
                  [nzValue]="activeUsersToday"
                  [nzPrefix]="activeIcon"
                  [nzSuffix]="'人'"
                  [nzValueStyle]="{ color: '#52c41a' }"
                ></nz-statistic>
                <ng-template #activeIcon>
                  <span nz-icon nzType="rise" nzTheme="outline"></span>
                </ng-template>
                <div class="compare">
                  <span
                    >较昨日
                    <nz-tag [nzColor]="activeChange >= 0 ? 'green' : 'red'">
                      {{ activeChange >= 0 ? '+' : '' }}{{ activeChange }}%
                    </nz-tag></span
                  >
                </div>
              </nz-card>
            </nz-col>

            <!-- 今日填色总数 -->
            <nz-col [nzXs]="24" [nzSm]="12" [nzMd]="8" [nzLg]="6">
              <nz-card nzHoverable>
                <nz-statistic
                  [nzTitle]="'今日填色总数'"
                  [nzValue]="totalColoringsToday"
                  [nzPrefix]="colorIcon"
                  [nzSuffix]="'次'"
                  [nzValueStyle]="{ color: '#722ed1' }"
                ></nz-statistic>
                <ng-template #colorIcon>
                  <span nz-icon nzType="highlight" nzTheme="outline"></span>
                </ng-template>
                <div class="compare">
                  <span
                    >较昨日
                    <nz-tag [nzColor]="coloringChange >= 0 ? 'green' : 'red'">
                      {{ coloringChange >= 0 ? '+' : '' }}{{ coloringChange }}%
                    </nz-tag></span
                  >
                </div>
              </nz-card>
            </nz-col>

            <!-- 今日填色完成数 -->
            <nz-col [nzXs]="24" [nzSm]="12" [nzMd]="8" [nzLg]="6">
              <nz-card nzHoverable>
                <nz-statistic
                  [nzTitle]="'今日填色完成数'"
                  [nzValue]="completedColoringsToday"
                  [nzPrefix]="completeIcon"
                  [nzSuffix]="'次'"
                  [nzValueStyle]="{ color: '#13c2c2' }"
                ></nz-statistic>
                <ng-template #completeIcon>
                  <span nz-icon nzType="check-circle" nzTheme="outline"></span>
                </ng-template>
                <div class="compare">
                  <span>完成率 {{ completionRate }}%</span>
                  <nz-progress
                    [nzPercent]="completionRate"
                    [nzStrokeColor]="
                      completionRate > 70
                        ? '#52c41a'
                        : completionRate > 30
                        ? '#faad14'
                        : '#f5222d'
                    "
                    [nzShowInfo]="false"
                    [nzStrokeWidth]="5"
                  ></nz-progress>
                </div>
              </nz-card>
            </nz-col>
          </nz-row>
        </div>

        <!-- 广告收益部分 -->
        <div class="section">
          <h3 class="section-title">今日广告收益</h3>
          <nz-row [nzGutter]="16">
            <nz-col [nzXs]="24" [nzSm]="12" [nzMd]="8">
              <nz-card nzHoverable>
                <nz-statistic
                  [nzTitle]="'Banner广告收益'"
                  [nzValue]="bannerRevenue"
                  [nzPrefix]="bannerIcon"
                  [nzSuffix]="'元'"
                  [nzValueStyle]="{ color: '#fa8c16' }"
                ></nz-statistic>
                <ng-template #bannerIcon>
                  <span nz-icon nzType="picture" nzTheme="outline"></span>
                </ng-template>
                <div class="compare">
                  <span>展示量 {{ bannerImpressions }} 次</span>
                </div>
              </nz-card>
            </nz-col>

            <nz-col [nzXs]="24" [nzSm]="12" [nzMd]="8">
              <nz-card nzHoverable>
                <nz-statistic
                  [nzTitle]="'插屏广告收益'"
                  [nzValue]="interstitialRevenue"
                  [nzPrefix]="interstitialIcon"
                  [nzSuffix]="'元'"
                  [nzValueStyle]="{ color: '#fa541c' }"
                ></nz-statistic>
                <ng-template #interstitialIcon>
                  <span nz-icon nzType="switcher" nzTheme="outline"></span>
                </ng-template>
                <div class="compare">
                  <span>展示量 {{ interstitialImpressions }} 次</span>
                </div>
              </nz-card>
            </nz-col>

            <nz-col [nzXs]="24" [nzSm]="12" [nzMd]="8">
              <nz-card nzHoverable>
                <nz-statistic
                  [nzTitle]="'激励广告收益'"
                  [nzValue]="rewardedRevenue"
                  [nzPrefix]="rewardedIcon"
                  [nzSuffix]="'元'"
                  [nzValueStyle]="{ color: '#eb2f96' }"
                ></nz-statistic>
                <ng-template #rewardedIcon>
                  <span nz-icon nzType="gift" nzTheme="outline"></span>
                </ng-template>
                <div class="compare">
                  <span>展示量 {{ rewardedImpressions }} 次</span>
                </div>
              </nz-card>
            </nz-col>
          </nz-row>
        </div>

        <!-- 今日上新作品 -->
        <div class="section">
          <h3 class="section-title">今日上新作品</h3>
          <nz-table
            #worksTable
            [nzData]="newWorksToday"
            [nzLoading]="isLoading"
            [nzFrontPagination]="false"
            [nzBordered]="true"
            [nzSize]="'small'"
          >
            <thead>
              <tr>
                <th>作品</th>
                <th>名称</th>
                <th>填色开始数</th>
                <th>填色完成数</th>
                <th>完成率</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr *ngFor="let work of worksTable.data">
                <td>
                  <div
                    class="work-thumbnail"
                    [style.backgroundImage]="'url(' + work.thumbnail + ')'"
                  ></div>
                </td>
                <td>{{ work.name }}</td>
                <td>{{ work.startedCount }}</td>
                <td>{{ work.completedCount }}</td>
                <td>
                  <nz-progress
                    [nzPercent]="work.completionRate"
                    [nzStrokeColor]="
                      work.completionRate > 70
                        ? '#52c41a'
                        : work.completionRate > 30
                        ? '#faad14'
                        : '#f5222d'
                    "
                    [nzShowInfo]="true"
                    [nzStrokeWidth]="5"
                  ></nz-progress>
                </td>
                <td>
                  <a (click)="showWorkDetails(work)">详情</a>
                </td>
              </tr>
            </tbody>
          </nz-table>
        </div>
      </nz-spin>
    </div>
  `,
  styles: [
    `
      .dashboard-container {
        padding: 24px;
        background: #f0f2f5;
        min-height: 100%;
      }

      .metrics-container {
        margin-bottom: 24px;
      }

      .section {
        background: #fff;
        padding: 16px 24px;
        border-radius: 8px;
        margin-bottom: 24px;
        box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
      }

      .section-title {
        margin-bottom: 16px;
        font-size: 18px;
        color: rgba(0, 0, 0, 0.85);
      }

      nz-card {
        margin-bottom: 16px;
        transition: all 0.3s;
      }

      nz-card:hover {
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        transform: translateY(-4px);
      }

      .compare {
        margin-top: 8px;
        font-size: 12px;
        color: rgba(0, 0, 0, 0.45);
      }

      .work-thumbnail {
        width: 60px;
        height: 60px;
        background-size: cover;
        background-position: center;
        border-radius: 4px;
      }

      .ant-statistic-content {
        display: flex;
        flex-direction: column;
        align-items: center;
      }

      .ant-statistic-title {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.65);
      }

      .ant-statistic-content-value {
        font-size: 28px;
      }

      .ant-statistic-content-suffix {
        font-size: 16px;
      }
    `,
  ],
})
export class DashboardComponent implements OnInit {
  isLoading = true;
  lastUpdateTime = new Date();

  // 核心指标数据
  totalUsers = 0;
  activeUsersToday = 0;
  totalColoringsToday = 0;
  completedColoringsToday = 0;
  completionRate = 0;
  userChange = 0;
  activeChange = 0;
  coloringChange = 0;

  // 广告收益数据
  bannerRevenue = 0;
  interstitialRevenue = 0;
  rewardedRevenue = 0;
  bannerImpressions = 0;
  interstitialImpressions = 0;
  rewardedImpressions = 0;

  // 今日上新作品
  newWorksToday: any[] = [];

  constructor(
    private modalService: NzModalService,
    private message: NzMessageService
  ) {}

  ngOnInit(): void {
    this.loadDashboardData();
  }

  refreshData(): void {
    this.isLoading = true;
    this.loadDashboardData();
  }

  loadDashboardData(): void {
    // 模拟数据加载
    setTimeout(() => {
      // 核心指标数据
      this.totalUsers = 12458;
      this.activeUsersToday = 3842;
      this.totalColoringsToday = 8921;
      this.completedColoringsToday = 5236;
      this.completionRate = Math.round(
        (this.completedColoringsToday / this.totalColoringsToday) * 100
      );
      this.userChange = 5.2;
      this.activeChange = 8.7;
      this.coloringChange = 12.3;

      // 广告收益数据
      this.bannerRevenue = 856.42;
      this.interstitialRevenue = 1243.75;
      this.rewardedRevenue = 982.31;
      this.bannerImpressions = 24578;
      this.interstitialImpressions = 8765;
      this.rewardedImpressions = 6543;

      // 今日上新作品
      this.newWorksToday = [
        {
          id: 1,
          name: '可爱猫咪',
          thumbnail: 'https://example.com/cat.jpg',
          startedCount: 1245,
          completedCount: 876,
          completionRate: Math.round((876 / 1245) * 100),
        },
        {
          id: 2,
          name: '美丽风景',
          thumbnail: 'https://example.com/scenery.jpg',
          startedCount: 987,
          completedCount: 654,
          completionRate: Math.round((654 / 987) * 100),
        },
        {
          id: 3,
          name: '卡通人物',
          thumbnail: 'https://example.com/cartoon.jpg',
          startedCount: 765,
          completedCount: 432,
          completionRate: Math.round((432 / 765) * 100),
        },
      ];

      this.lastUpdateTime = new Date();
      this.isLoading = false;
    }, 1500);
  }

  showWorkDetails(work: any): void {
    this.modalService.create({
      nzTitle: '作品详情',
      nzContent: `
        <div style="padding: 16px;">
          <div style="text-align: center; margin-bottom: 16px;">
            <img src="${work.thumbnail}" style="max-width: 100%; max-height: 300px; border-radius: 4px;">
          </div>
          <p><strong>作品名称:</strong> ${work.name}</p>
          <p><strong>填色开始数:</strong> ${work.startedCount}</p>
          <p><strong>填色完成数:</strong> ${work.completedCount}</p>
          <p><strong>完成率:</strong> ${work.completionRate}%</p>
        </div>
      `,
      nzFooter: null,
    });
  }
}
