import { Component, Input, Output, EventEmitter } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

// NG-ZORRO 组件
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { NzInputNumberModule } from 'ng-zorro-antd/input-number';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzSpinModule } from 'ng-zorro-antd/spin';
import { NzTagModule } from 'ng-zorro-antd/tag';

// 类型
import {
  FilterCondition,
  FieldConfig,
  OperatorOption,
} from '../services/message.service';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-filter-panel',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    NzCardModule,
    NzFormModule,
    NzSelectModule,
    NzInputNumberModule,
    NzButtonModule,
    NzIconModule,
    NzSpinModule,
    NzTagModule,
  ],
  template: `
    <nz-card nzTitle="目标用户筛选" style="margin-top: 16px;">
      @for (condition of filterConditions; track $index) {
      <div class="filter-row">
        <!-- 字段选择 -->
        <nz-form-item>
          <nz-select
            [(ngModel)]="condition.field"
            (ngModelChange)="onFieldChange(condition)"
          >
            @for (field of filterFields; track field.value) {
            <nz-option
              [nzValue]="field.value"
              [nzLabel]="field.label"
            ></nz-option>
            }
          </nz-select>
        </nz-form-item>

        <!-- 运算符选择 -->
        <nz-form-item>
          <nz-select
            [(ngModel)]="condition.operator"
            (ngModelChange)="onOperatorChange(condition)"
          >
            @for (op of getOperatorsForField(condition.field); track op.value) {
            <nz-option [nzValue]="op.value" [nzLabel]="op.label"></nz-option>
            }
          </nz-select>
        </nz-form-item>

        <!-- 值输入 -->
        <nz-form-item>
          <!-- 国家多选 -->
          @if (condition.field === 'cc') {
          <nz-select
            [(ngModel)]="condition.value"
            nzMode="multiple"
            (ngModelChange)="onConditionChange(condition)"
          >
            @for (country of countries; track country.code) {
            <nz-option
              [nzValue]="country.code"
              [nzLabel]="country.name"
            ></nz-option>
            }
          </nz-select>
          }

          <!-- 日期天数输入 - 单值 -->
          @if ((condition.field === 'firstLoginAt' || condition.field ===
          'lastActiveAt') && (condition.operator === '$gt' || condition.operator
          === '$lt' || condition.operator === '$gte' || condition.operator ===
          '$lte')) {
          <nz-input-number
            [(ngModel)]="condition.value"
            [nzMin]="1"
            [nzStep]="1"
            [nzPlaceHolder]="'输入天数'"
            (ngModelChange)="onConditionChange(condition)"
          ></nz-input-number>
          <span class="unit-text">天前</span>
          }

          <!-- 日期天数输入 - 范围值 -->
          @if ((condition.field === 'firstLoginAt' || condition.field ===
          'lastActiveAt') && condition.operator === '$in') {
          <div class="range-input-group">
            <nz-input-number
              [(ngModel)]="condition.value[0]"
              [nzMin]="1"
              [nzStep]="1"
              [nzPlaceHolder]="'最小天数'"
              (ngModelChange)="onConditionChange(condition)"
            ></nz-input-number>
            <span class="range-separator">到</span>
            <nz-input-number
              [(ngModel)]="condition.value[1]"
              [nzMin]="1"
              [nzStep]="1"
              [nzPlaceHolder]="'最大天数'"
              (ngModelChange)="onConditionChange(condition)"
            ></nz-input-number>
            <span class="unit-text">天前</span>
          </div>
          }
        </nz-form-item>

        <!-- 删除按钮 -->
        <button
          nz-button
          nzType="text"
          nzDanger
          (click)="removeCondition($index)"
        >
          <span nz-icon nzType="delete"></span>
        </button>
      </div>
      }

      <!-- 添加条件和用户数量统计 -->
      <div class="filter-footer">
        <button nz-button nzType="dashed" (click)="addCondition()">
          <span nz-icon nzType="plus"></span>添加条件
        </button>

        @if (estimatedUserCount !== null) {
        <div class="user-count">
          @if (isCountingUsers) {
          <nz-spin></nz-spin>
          } @else {
          <span>
            预计影响用户: <strong>{{ estimatedUserCount }}</strong>
          </span>
          }
        </div>
        }
      </div>
    </nz-card>
  `,
  styles: [
    `
      nz-select {
        width: 100%;
      }

      .filter-row {
        display: flex;
        gap: 8px;
        margin-bottom: 16px;
        align-items: center;
      }

      .filter-row nz-form-item {
        flex: 1;
        margin-bottom: 0;
      }

      .filter-row button {
        flex: 0 0 auto;
      }

      .filter-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 16px;
      }

      .user-count {
        padding: 0 16px;
        color: #666;
      }

      .unit-text {
        margin-left: 8px;
        color: #666;
      }

      .range-input-group {
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .range-separator {
        padding: 0 8px;
        color: #666;
      }

      @media (max-width: 768px) {
        .filter-row {
          flex-wrap: wrap;
        }

        .filter-row nz-form-item {
          flex: 1 1 100%;
        }

        .range-input-group {
          flex-wrap: wrap;
        }
      }
    `,
  ],
})
export class FilterPanelComponent {
  @Input() filterConditions: FilterCondition[] = [];
  @Input() filterFields: FieldConfig[] = [];
  @Input() operatorsMap: { [key: string]: OperatorOption[] } = {};
  @Input() countries: { code: string; name: string }[] = [];
  @Input() estimatedUserCount: number | null = null;
  @Input() isCountingUsers = false;

  @Output() conditionsChange = new EventEmitter<FilterCondition[]>();
  @Output() addConditionEvent = new EventEmitter<void>();
  @Output() removeConditionEvent = new EventEmitter<number>();
  @Output() estimateUserCountEvent = new EventEmitter<void>();

  constructor(private message: NzMessageService) {}

  addCondition(): void {
    this.addConditionEvent.emit();
  }

  removeCondition(index: number): void {
    this.removeConditionEvent.emit(index);
  }

  onFieldChange(condition: FilterCondition): void {
    const operators = this.getOperatorsForField(condition.field);
    condition.operator = operators[0].value;

    // 根据字段类型和运算符初始化值
    if (
      condition.field === 'firstLoginAt' ||
      condition.field === 'lastActiveAt'
    ) {
      if (condition.operator === '$in') {
        condition.value = [1, 7]; // 默认1-7天前
      } else {
        condition.value = 3; // 默认3天前
      }
    } else if (condition.field === 'cc') {
      condition.value = [];
    }

    this.onConditionChange(condition);
  }

  onOperatorChange(condition: FilterCondition): void {
    // 根据字段类型和运算符初始化值
    if (
      condition.field === 'firstLoginAt' ||
      condition.field === 'lastActiveAt'
    ) {
      if (condition.operator === '$in') {
        condition.value = [1, 7]; // 默认1-7天前
      } else {
        condition.value = 3; // 默认3天前
      }
    }

    this.onConditionChange(condition);
  }

  onConditionChange(condition: FilterCondition): void {
    if (this.validateCondition(condition)) {
      this.estimateUserCountEvent.emit();
    }
  }

  /**
   * 验证所有筛选条件是否合法
   * @returns 如果所有条件都合法返回true，否则返回false
   */
  validateAllConditions(): boolean {
    if (this.filterConditions.length === 0) {
      return true; // 允许无筛选条件
    }

    const invalidConditions = this.filterConditions.filter(
      (condition) => !this.validateCondition(condition)
    );

    if (invalidConditions.length > 0) {
      this.message.error('请完善所有筛选条件的值');
      return false;
    }

    return true;
  }

  /**
   * 验证单个筛选条件是否合法
   */
  private validateCondition(condition: FilterCondition): boolean {
    // 检查基本字段和运算符是否存在
    if (!condition.field || !condition.operator) {
      return false;
    }

    // 检查值是否存在
    if (condition.value == null) {
      return false;
    }

    // 特殊处理日期范围字段
    if (
      condition.field === 'firstLoginAt' ||
      condition.field === 'lastActiveAt'
    ) {
      return this.validateDateCondition(condition);
    }

    // 检查国家代码字段
    if (condition.field === 'cc') {
      return Array.isArray(condition.value) && condition.value.length > 0;
    }

    return true;
  }

  /**
   * 验证日期类型筛选条件
   */
  private validateDateCondition(condition: FilterCondition): boolean {
    if (condition.operator === '$in') {
      // 范围运算符需要有两个有效数字
      return (
        Array.isArray(condition.value) &&
        condition.value.length === 2 &&
        typeof condition.value[0] === 'number' &&
        typeof condition.value[1] === 'number' &&
        condition.value[0] >= 0 &&
        condition.value[1] >= 0 &&
        condition.value[0] <= condition.value[1]
      );
    } else {
      // 其他运算符只需要一个有效数字
      return typeof condition.value === 'number' && condition.value >= 0;
    }
  }

  getOperatorsForField(fieldValue: string): OperatorOption[] {
    const field = this.filterFields.find((f) => f.value === fieldValue);
    if (!field) return [];
    return this.operatorsMap[field.type] || [];
  }
}
