import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule, DatePipe } from '@angular/common';
import {
  FormsModule,
  ReactiveFormsModule,
  FormBuilder,
  FormGroup,
  FormControl,
  Validators,
} from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { of, Subject } from 'rxjs';
import {
  takeUntil,
  debounceTime,
  distinctUntilChanged,
  map,
  catchError,
} 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 {
  IMessageStrategy,
  MessageStrategyData,
  MessageService,
  IMessageTemplate,
  IMessageTemplateInfo,
} from '../services/message.service';

@Component({
  selector: 'app-message-strategy',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    NzTableModule,
    NzDividerModule,
    NzButtonModule,
    NzIconModule,
    NzFormModule,
    NzInputModule,
    NzModalModule,
    NzSelectModule,
    NzPageHeaderModule,
    NzCardModule,
    NzPopconfirmModule,
    NzTagModule,
    NzTabsModule,
    NzDescriptionsModule,
    NzEmptyModule,
    NzSpinModule,
    DatePipe,
  ],
  template: `
    <nz-page-header [nzGhost]="false">
      <nz-page-header-title>消息策略管理</nz-page-header-title>
      <nz-page-header-extra>
        <button nz-button nzType="primary" (click)="showCreateModal()">
          <span nz-icon nzType="plus"></span>新建策略
        </button>
      </nz-page-header-extra>
      <nz-page-header-content>
        管理消息推送策略，用于组合多个消息模板，方便统计评估策略优劣
      </nz-page-header-content>
    </nz-page-header>

    <nz-card>
      <nz-spin [nzSpinning]="isLoading">
        <nz-table
          #strategiesTable
          [nzData]="filteredStrategies"
          [nzLoading]="isLoading"
          [nzFrontPagination]="false"
          [nzBordered]="true"
          [nzSize]="'small'"
          [nzShowPagination]="false"
        >
          <thead>
            <tr>
              <th>策略名称</th>
              <th>描述</th>
              <th>关联模板</th>
              <th>创建时间</th>
              <th>更新时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            @for (strategy of strategiesTable.data; track strategy._id) {
            <tr>
              <td>{{ strategy.name }}</td>
              <td>{{ strategy.description || '-' }}</td>
              <td>
                @for (template of strategy.templates; track template._id) {
                <nz-tag>{{ template.templateName }}</nz-tag>
                }
              </td>
              <td>{{ strategy.createdAt | date : 'yyyy-MM-dd HH:mm' }}</td>
              <td>{{ strategy.updatedAt | date : 'yyyy-MM-dd HH:mm' }}</td>
              <td>
                <a (click)="showEditModal(strategy)">编辑</a>
                <nz-divider nzType="vertical"></nz-divider>
                <a (click)="showDetailModal(strategy)">详情</a>
                <nz-divider nzType="vertical"></nz-divider>
                <a
                  nz-popconfirm
                  nzPopconfirmTitle="确定要删除此策略吗？"
                  nzPopconfirmOkText="确定"
                  nzPopconfirmCancelText="取消"
                  (nzOnConfirm)="deleteStrategy(strategy._id)"
                  >删除
                </a>
              </td>
            </tr>
            }
          </tbody>
        </nz-table>

        @if (filteredStrategies.length === 0 && !isLoading) {
        <nz-empty nzNotFoundContent="暂无消息策略"></nz-empty>
        }
      </nz-spin>
    </nz-card>

    <!-- 创建/编辑策略模态框 -->
    <nz-modal
      [(nzVisible)]="isModalVisible"
      [nzTitle]="isEditMode ? '编辑消息策略' : '新建消息策略'"
      [nzOkText]="isEditMode ? '更新' : '创建'"
      [nzCancelText]="'取消'"
      (nzOnCancel)="handleCancel()"
      (nzOnOk)="handleOk()"
      [nzOkLoading]="isSubmitting"
      [nzWidth]="800"
    >
      <form nz-form [formGroup]="strategyForm" *nzModalContent>
        <nz-form-item>
          <nz-form-label nzRequired>策略名称</nz-form-label>
          <nz-form-control>
            <input
              nz-input
              formControlName="name"
              placeholder="输入策略名称（英文，不可重复）"
            />
          </nz-form-control>
        </nz-form-item>

        <nz-form-item>
          <nz-form-label>描述</nz-form-label>
          <nz-form-control>
            <textarea
              nz-input
              formControlName="description"
              placeholder="输入策略描述（可选）"
              rows="3"
            ></textarea>
          </nz-form-control>
        </nz-form-item>

        <nz-form-item>
          <nz-form-label nzRequired>关联模板</nz-form-label>
          <nz-form-control>
            <nz-select
              formControlName="templates"
              nzMode="multiple"
              nzPlaceHolder="选择关联的消息模板"
              nzShowSearch
              nzAllowClear
            >
              @for (template of getAllTemplates(); track template._id) {
              <nz-option
                [nzLabel]="template.templateName"
                [nzValue]="template._id"
              ></nz-option>
              }
            </nz-select>
          </nz-form-control>
        </nz-form-item>
      </form>
    </nz-modal>

    <!-- 策略详情模态框 -->
    <nz-modal
      [(nzVisible)]="isDetailModalVisible"
      [nzTitle]="'策略详情 - ' + (selectedStrategy?.name || '')"
      [nzFooter]="null"
      (nzOnCancel)="isDetailModalVisible = false"
      [nzWidth]="800"
    >
      <ng-container *nzModalContent>
        <nz-descriptions nzBordered [nzColumn]="1">
          <nz-descriptions-item nzTitle="策略名称">{{
            selectedStrategy?.name
          }}</nz-descriptions-item>
          <nz-descriptions-item nzTitle="描述">{{
            selectedStrategy?.description || '-'
          }}</nz-descriptions-item>
          <nz-descriptions-item nzTitle="创建时间">{{
            selectedStrategy?.createdAt | date : 'yyyy-MM-dd HH:mm:ss'
          }}</nz-descriptions-item>
          <nz-descriptions-item nzTitle="更新时间">{{
            selectedStrategy?.updatedAt | date : 'yyyy-MM-dd HH:mm:ss'
          }}</nz-descriptions-item>
        </nz-descriptions>

        <nz-card nzTitle="关联模板" style="margin-top: 16px">
          <nz-table
            #templatesTable
            [nzData]="selectedStrategy?.templates || []"
            [nzShowPagination]="false"
            [nzFrontPagination]="false"
            [nzSize]="'small'"
          >
            <thead>
              <tr>
                <th>模板名称</th>
                <th>描述</th>
              </tr>
            </thead>
            <tbody>
              @for (template of templatesTable.data; track template._id) {
              <tr>
                <td>{{ template.templateName }}</td>
                <td>{{ template.description || '-' }}</td>
              </tr>
              }
            </tbody>
          </nz-table>
        </nz-card>
      </ng-container>
    </nz-modal>
  `,
  styles: [
    `
      nz-card {
        margin-bottom: 16px;
      }

      .ant-tag {
        margin-bottom: 4px;
      }

      .ant-form-item {
        margin-bottom: 16px;
      }

      textarea.ant-input {
        resize: none;
      }

      .ant-empty {
        margin: 40px 0;
      }

      .ant-table {
        margin-top: 16px;
      }

      nz-tag {
        margin-right: 4px;
      }
    `,
  ],
})
export class MessageStrategyComponent implements OnInit, OnDestroy {
  strategies: IMessageStrategy[] = [];
  filteredStrategies: IMessageStrategy[] = [];
  allTemplates: IMessageTemplate[] = []; // 新增：存储所有模板
  isLoading = false;
  isModalVisible = false;
  isDetailModalVisible = false;
  isEditMode = false;
  isSubmitting = false;
  selectedStrategy: IMessageStrategy | null = null;

  // 表单
  strategyForm: FormGroup;

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

  constructor(
    private messageService: MessageService,
    private fb: FormBuilder,
    private message: NzMessageService,
    private modal: NzModalService,
    private router: Router,
    private route: ActivatedRoute
  ) {
    this.strategyForm = this.fb.group({
      name: ['', [Validators.required, Validators.pattern(/^[a-zA-Z0-9_-]+$/)]],
      description: [''],
      templates: [[], [Validators.required]],
    });
  }

  ngOnInit(): void {
    this.loadStrategies();
    this.loadAllTemplates(); // 新增：加载所有模板
  }

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

  // 新增：加载所有模板
  loadAllTemplates(): void {
    this.messageService
      .getAllTemplates()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (templates) => {
          this.allTemplates = templates || [];
        },
        error: (err) => {
          this.message.error('加载模板失败: ' + err.message);
          this.allTemplates = [];
        },
      });
  }

  loadStrategies(): void {
    this.isLoading = true;
    this.messageService
      .getAllStrategies()
      .pipe(
        takeUntil(this.destroy$),
        map((strategies) => (Array.isArray(strategies) ? strategies : [])),
        catchError((err) => {
          this.message.error('加载策略失败: ' + err.message);
          return of([]);
        })
      )
      .subscribe({
        next: (strategies) => {
          this.strategies = strategies;
          this.filteredStrategies = [...strategies];
          this.isLoading = false;
        },
        error: (err) => {
          this.message.error('加载策略失败: ' + err.message);
          this.isLoading = false;
          this.strategies = [];
          this.filteredStrategies = [];
        },
      });
  }

  // 修改：直接从 allTemplates 获取所有模板
  getAllTemplates(): IMessageTemplate[] {
    return this.allTemplates;
  }

  showCreateModal(): void {
    this.isEditMode = false;
    this.selectedStrategy = null;
    this.strategyForm.reset({
      templates: [],
    });
    this.isModalVisible = true;
  }

  showEditModal(strategy: IMessageStrategy): void {
    this.isEditMode = true;
    this.selectedStrategy = strategy;
    this.strategyForm.reset({
      name: strategy.name,
      description: strategy.description || '',
      templates: strategy.templates?.map((t) => t._id) || [],
    });
    this.isModalVisible = true;
  }

  showDetailModal(strategy: IMessageStrategy): void {
    this.selectedStrategy = strategy;
    this.isDetailModalVisible = true;
  }

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

    this.isSubmitting = true;
    const formValue = this.strategyForm.value;

    if (this.isEditMode && this.selectedStrategy) {
      this.updateStrategy(formValue);
    } else {
      this.createStrategy(formValue);
    }
  }

  createStrategy(strategyData: MessageStrategyData): void {
    this.messageService.createStrategy(strategyData).subscribe({
      next: () => {
        this.message.success('策略创建成功');
        this.loadStrategies();
        this.isModalVisible = false;
        this.isSubmitting = false;
      },
      error: (err) => {
        this.handleApiError(err, '创建');
        this.isSubmitting = false;
      },
    });
  }

  updateStrategy(strategyData: Partial<MessageStrategyData>): void {
    if (!this.selectedStrategy) return;

    this.messageService
      .updateStrategy(this.selectedStrategy._id, strategyData)
      .subscribe({
        next: () => {
          this.message.success('策略更新成功');
          this.loadStrategies();
          this.isModalVisible = false;
          this.isSubmitting = false;
        },
        error: (err) => {
          this.handleApiError(err, '更新');
          this.isSubmitting = false;
        },
      });
  }

  deleteStrategy(id: string): void {
    this.messageService.deleteStrategy(id).subscribe({
      next: () => {
        this.message.success('策略删除成功');
        this.loadStrategies();
      },
      error: (err) => {
        this.handleApiError(err, '删除');
      },
    });
  }

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

  private markFormControlsAsDirty(): void {
    Object.values(this.strategyForm.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}`);
    }
  }
}
