import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule, DatePipe } from '@angular/common';
import {
  FormsModule,
  ReactiveFormsModule,
  FormBuilder,
  FormGroup,
  FormControl,
  Validators,
} from '@angular/forms';
import { Subject } from 'rxjs';
import { takeUntil, debounceTime, distinctUntilChanged } from 'rxjs/operators';

// NG-ZORRO 组件
import { NzTableModule } from 'ng-zorro-antd/table';
import { NzDividerModule } from 'ng-zorro-antd/divider';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzModalModule, NzModalService } from 'ng-zorro-antd/modal';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { NzPageHeaderModule } from 'ng-zorro-antd/page-header';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzPopconfirmModule } from 'ng-zorro-antd/popconfirm';
import { NzTagModule } from 'ng-zorro-antd/tag';
import { NzTabsModule } from 'ng-zorro-antd/tabs';
import { NzDescriptionsModule } from 'ng-zorro-antd/descriptions';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzEmptyModule } from 'ng-zorro-antd/empty';
import { NzSpinModule } from 'ng-zorro-antd/spin';
import { NzDatePickerModule } from 'ng-zorro-antd/date-picker';
import { NzSwitchModule } from 'ng-zorro-antd/switch';

// 自定义组件
import { FilterPanelComponent } from './filter-panel.component';
import { ActivityDetailComponent } from './message-activity-detail.component';

// 服务
import {
  MessageService,
  IMessageActivity,
  IMessageTemplate,
  FilterCondition,
  FieldConfig,
  OperatorOption,
  ActionType,
  ACTION_TYPE_MAP,
  ACTION_PARAM_PLACEHOLDERS,
} from '../services/message.service';
import { RouterModule } from '@angular/router';

@Component({
  selector: 'app-message-activity',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    NzTableModule,
    NzDividerModule,
    NzButtonModule,
    NzIconModule,
    NzFormModule,
    NzInputModule,
    NzModalModule,
    NzSelectModule,
    NzPageHeaderModule,
    NzCardModule,
    NzPopconfirmModule,
    NzTagModule,
    NzTabsModule,
    NzDescriptionsModule,
    NzEmptyModule,
    NzSpinModule,
    NzDatePickerModule,
    NzSwitchModule,
    FilterPanelComponent,
    ActivityDetailComponent,
    DatePipe,
    RouterModule,
  ],
  templateUrl: './message-activity.component.html',
  styleUrls: ['./message-activity.component.css'],
})
export class MessageActivityComponent implements OnInit, OnDestroy {
  activities: IMessageActivity[] = [];
  templates: IMessageTemplate[] = [];
  isLoading = false;
  isModalVisible = false;
  isDetailModalVisible = false;
  isEditMode = false;
  isSubmitting = false;
  selectedActivity: IMessageActivity | null = null;
  activityForm: FormGroup;

  // 筛选条件相关
  filterConditions: FilterCondition[] = [];
  estimatedUserCount: number | null = null;
  isCountingUsers = false;

  // 支持的筛选字段配置
  filterFields: FieldConfig[] = [
    { value: 'cc', label: '国家', type: 'country' },
    { value: 'firstLoginAt', label: '首次登录时间', type: 'date' },
    { value: 'lastActiveAt', label: '最后活跃时间', type: 'date' },
  ];

  // 运算符配置
  operatorsMap: { [key: string]: OperatorOption[] } = {
    country: [
      { value: '$in', label: '包含', valueType: 'multiple' },
      { value: '$nin', label: '不包含', valueType: 'multiple' },
    ],
    date: [
      { value: '$lt', label: '超过', valueType: 'single' },
      { value: '$gt', label: '小于', valueType: 'single' },
      // { value: '$gte', label: '晚于或等于', valueType: 'single' },
      // { value: '$lte', label: '早于或等于', valueType: 'single' },
      { value: '$in', label: '介于', valueType: 'range' },
    ],
  };

  // 国家选项
  countries = [
    { code: 'US', name: '美国' },
    { code: 'BR', name: '巴西' },
    { code: 'CN', name: '中国' },
    { code: 'JP', name: '日本' },
    { code: 'GB', name: '英国' },
    { code: 'FR', name: '法国' },
    { code: 'DE', name: '德国' },
    { code: 'RU', name: '俄罗斯' },
    { code: 'IN', name: '印度' },
  ];

  private destroy$ = new Subject<void>();

  constructor(
    private messageService: MessageService,
    private fb: FormBuilder,
    private message: NzMessageService,
    private modal: NzModalService
  ) {
    this.activityForm = this.fb.group({
      name: ['', [Validators.required, Validators.pattern(/^[a-zA-Z0-9_-]+$/)]],
      templateId: ['', [Validators.required]],
      image: [''],
      bigger: [false],
      action: [''],
      param: [''],
      extend: [''],
      strategy: [0],
      filter: [[]],
      scheduleAt: [null],
      everyday: [false],
      description: [''],
    });
  }

  ngOnInit(): void {
    this.loadActivities();
    this.loadTemplates();

    // 监听模板选择变化
    this.activityForm
      .get('templateId')
      ?.valueChanges.pipe(takeUntil(this.destroy$), distinctUntilChanged())
      .subscribe((templateId) => {
        this.onTemplateSelected(templateId);
      });
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  /**
   * 当选择模板时自动填充相关字段
   */
  private onTemplateSelected(templateId: string): void {
    if (!templateId) return;

    const selectedTemplate = this.templates.find((t) => t._id === templateId);
    if (!selectedTemplate) return;

    // 自动填充模板相关字段
    this.activityForm.patchValue(
      {
        image: selectedTemplate.image || '',
        bigger: selectedTemplate.bigger || false,
        action: selectedTemplate.action || '',
        param: selectedTemplate.param || '',
        extend: selectedTemplate.extend || '',
      },
      { emitEvent: false }
    );
  }

  loadActivities(): void {
    this.isLoading = true;
    this.messageService
      .getAllActivities()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (activities) => {
          this.activities = activities || [];
          this.isLoading = false;
        },
        error: (err) => {
          this.message.error('加载活动列表失败: ' + err.message);
          this.isLoading = false;
        },
      });
  }

  loadTemplates(): void {
    this.messageService
      .getAllTemplates()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (templates) => {
          this.templates = templates || [];
        },
        error: (err) => {
          this.message.error('加载模板列表失败: ' + err.message);
        },
      });
  }

  showCreateModal(): void {
    this.isEditMode = false;
    this.selectedActivity = null;
    this.filterConditions = [];
    this.estimatedUserCount = null;
    this.activityForm.reset({
      strategy: 0,
      bigger: false,
      everyday: false,
    });
    this.isModalVisible = true;
  }

  showEditModal(activity: IMessageActivity): void {
    this.isEditMode = true;
    this.selectedActivity = activity;
    this.filterConditions = activity.filter || [];
    this.estimateUserCount();
    this.activityForm.reset({
      ...activity,
      scheduleAt: activity.scheduleAt ? new Date(activity.scheduleAt) : null,
    });
    this.isModalVisible = true;
  }

  showDetailModal(activity: IMessageActivity): void {
    this.selectedActivity = activity;
    this.isDetailModalVisible = true;
  }

  handleOk(): void {
    if (this.activityForm.invalid) {
      this.markFormControlsAsDirty();
      return;
    }

    // 先验证筛选条件
    if (!this.validateAllConditions()) {
      return;
    }

    this.isSubmitting = true;
    const formValue = {
      ...this.activityForm.value,
      filter: this.filterConditions,
    };

    if (this.isEditMode && this.selectedActivity) {
      this.updateActivity(formValue);
    } else {
      this.createActivity(formValue);
    }
  }

  createActivity(activityData: any): void {
    this.messageService
      .createActivity(activityData)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: () => {
          this.message.success('活动创建成功');
          this.loadActivities();
          this.isModalVisible = false;
          this.isSubmitting = false;
        },
        error: (err) => {
          this.handleApiError(err, '创建');
          this.isSubmitting = false;
        },
      });
  }

  updateActivity(activityData: any): void {
    if (!this.selectedActivity) return;

    this.messageService
      .updateActivity(this.selectedActivity._id, activityData)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: () => {
          this.message.success('活动更新成功');
          this.loadActivities();
          this.isModalVisible = false;
          this.isSubmitting = false;
        },
        error: (err) => {
          this.handleApiError(err, '更新');
          this.isSubmitting = false;
        },
      });
  }

  // 发布活动
  publishActivity(id: string): void {
    this.isLoading = true;
    this.messageService.updateActivityStatus(id, 1).subscribe({
      next: () => {
        this.message.success('活动已发布');
        this.loadActivities();
      },
      error: (err) => {
        this.message.error('发布活动失败: ' + err.message);
        this.isLoading = false;
      },
    });
  }

  // 中止活动
  abortActivity(id: string): void {
    this.isLoading = true;
    this.messageService.updateActivityStatus(id, 3).subscribe({
      next: () => {
        this.message.success('活动已中止');
        this.loadActivities();
      },
      error: (err) => {
        this.message.error('中止活动失败: ' + err.message);
        this.isLoading = false;
      },
    });
  }

  // 删除活动
  deleteActivity(id: string): void {
    this.isLoading = true;
    this.messageService.deleteActivity(id).subscribe({
      next: () => {
        this.message.success('活动删除成功');
        this.loadActivities();
      },
      error: (err) => {
        this.message.error('删除活动失败: ' + err.message);
        this.isLoading = false;
      },
    });
  }

  handleCancel(): void {
    this.isModalVisible = false;
  }

  // 策略相关方法
  getStrategyName(strategy: number): string {
    const strategies = {
      0: '自定义策略',
      1: '活跃用户推送',
      2: '新用户推送',
      3: '沉默用户唤醒',
    };
    return strategies[strategy as keyof typeof strategies] || '未知策略';
  }

  getStrategyColor(strategy: number): string {
    const colors = {
      0: 'blue',
      1: 'green',
      2: 'orange',
      3: 'purple',
    };
    return colors[strategy as keyof typeof colors] || 'default';
  }

  // 状态显示相关方法
  getStatusName(status: number): string {
    const statuses = {
      0: '未发布',
      1: '进行中',
      2: '已完成',
      3: '已中止',
    };
    return statuses[status as keyof typeof statuses] || '未知状态';
  }

  getStatusColor(status: number): string {
    const colors = {
      0: 'default', // 未发布 - 默认灰色
      1: 'processing', // 进行中 - 蓝色
      2: 'success', // 已完成 - 绿色
      3: 'error', // 已中止 - 红色
    };
    return colors[status as keyof typeof colors] || 'default';
  }

  // 模板名称
  getTemplateName(templateId: string | undefined): string {
    if (!templateId) return '-';
    const template = this.templates.find((t) => t._id === templateId);
    return template ? template.templateName : '-';
  }

  // 客户端行为相关方法
  onActionChange(action: string): void {
    this.activityForm.patchValue({
      param: '',
      extend: '',
    });

    // 根据行为类型设置默认参数
    if (action === ActionType.GAIN_HINT) {
      this.activityForm.patchValue({
        param: '3', // 默认3个提示
      });
    }
  }

  showParamField(): boolean {
    const action = this.activityForm.get('action')?.value as ActionType;
    return [
      ActionType.GO_ART,
      ActionType.GO_ALBUM,
      ActionType.GAIN_HINT,
      ActionType.KEEP_GOING,
    ].includes(action);
  }

  // 替换原来的方法
  getActionOptions(): { value: string; label: string }[] {
    return this.messageService.getActionOptions();
  }

  // 替换原来的方法
  getParamPlaceholder(): string {
    const action = this.activityForm.get('action')?.value as ActionType;
    return this.messageService.getActionParamPlaceholder(action);
  }

  // 筛选条件相关方法
  addCondition(): void {
    this.filterConditions.push({
      field: this.filterFields[0].value,
      operator: this.getOperatorsForField(this.filterFields[0].value)[0].value,
      value: null,
    });
    this.onConditionChange();
  }

  removeCondition(index: number): void {
    this.filterConditions.splice(index, 1);
    this.onConditionChange();
  }

  onConditionChange(): void {
    this.activityForm.patchValue({
      filter: this.filterConditions,
    });
    this.estimateUserCount();
  }

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

  estimateUserCount(): void {
    if (this.filterConditions.length === 0) {
      this.estimatedUserCount = null;
      return;
    }

    // 过滤掉无效条件
    const validConditions = this.filterConditions.filter((condition) =>
      this.isConditionValid(condition)
    );

    // 如果没有有效条件，则重置估算结果
    if (validConditions.length === 0) {
      this.estimatedUserCount = null;
      return;
    }

    this.isCountingUsers = true;
    this.messageService
      .countTargetUsers(validConditions)
      .pipe(takeUntil(this.destroy$), debounceTime(500))
      .subscribe({
        next: (count) => {
          this.estimatedUserCount = count;
          this.isCountingUsers = false;
        },
        error: (err) => {
          this.message.error('估算用户数量失败: ' + err.message);
          this.isCountingUsers = false;
        },
      });
  }

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

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

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

    return true;
  }

  /**
   * 检查单个筛选条件是否有效
   */
  private isConditionValid(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.isDateConditionValid(condition);
    }

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

    // 默认情况下，只要值存在就认为是有效的
    return true;
  }

  /**
   * 检查日期类型筛选条件是否有效
   */
  private isDateConditionValid(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;
    }
  }

  private markFormControlsAsDirty(): void {
    Object.values(this.activityForm.controls).forEach((control) => {
      if (control instanceof FormControl) {
        control.markAsDirty();
        control.updateValueAndValidity();
      }
    });
    this.message.error('请填写所有必填字段');
  }

  private handleApiError(err: any, action: string): void {
    if (err.status === 409) {
      this.message.error('活动名称已存在');
    } else if (err.status === 404) {
      this.message.error('未找到指定的活动');
    } else if (err.status === 400) {
      this.message.error(
        '验证错误: ' + (err.error?.message || '请检查输入数据')
      );
    } else {
      this.message.error(`${action}活动失败: ${err.message}`);
    }
  }
}
