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

// NG-ZORRO 组件
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzTableModule } from 'ng-zorro-antd/table';
import { NzDividerModule } from 'ng-zorro-antd/divider';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { NzDatePickerModule } from 'ng-zorro-antd/date-picker';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzPopconfirmModule } from 'ng-zorro-antd/popconfirm';

import { UserService, User } from '../services/user.service';
import { NzPageHeaderModule } from 'ng-zorro-antd/page-header';
import { NzPaginationModule } from 'ng-zorro-antd/pagination';
import { SendMessageModalComponent } from './send-message-modal.component';
import { UserDetailModalComponent } from './user-detail-modal.component';
import { UserCreateModalComponent } from './user-create-modal.component';
import { UserEditModalComponent } from './user.edit.component';

@Component({
  selector: 'app-user',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    DatePipe,
    // NG-ZORRO 模块
    NzFormModule,
    NzInputModule,
    NzButtonModule,
    NzTableModule,
    NzDividerModule,
    NzIconModule,
    NzSelectModule,
    NzDatePickerModule,
    NzPageHeaderModule,
    NzPaginationModule,
    NzPopconfirmModule,
  ],
  providers: [NzModalService, NzMessageService],
  template: `
    <nz-page-header [nzGhost]="false">
      <nz-page-header-title>用户管理</nz-page-header-title>
      <nz-page-header-extra>
        <button nz-button nzType="primary" (click)="showCreateUserModal()">
          <span nz-icon nzType="plus"></span>
          新建用户
        </button>
      </nz-page-header-extra>
      <nz-page-header-content> </nz-page-header-content>
    </nz-page-header>

    <!-- 筛选表单 -->
    <form nz-form [formGroup]="filterForm">
      <div nz-row [nzGutter]="16">
        <div nz-col [nzSpan]="4">
          <nz-form-item>
            <nz-form-control>
              <nz-input-group nzPrefixIcon="user">
                <input
                  type="text"
                  nz-input
                  placeholder="UID"
                  formControlName="uid"
                  nzAllowClear="true"
                />
              </nz-input-group>
            </nz-form-control>
          </nz-form-item>
        </div>
        <div nz-col [nzSpan]="4">
          <nz-form-item>
            <nz-form-control>
              <nz-input-group nzPrefixIcon="global">
                <input
                  type="text"
                  nz-input
                  placeholder="Network"
                  formControlName="network"
                  nzAllowClear="true"
                />
              </nz-input-group>
            </nz-form-control>
          </nz-form-item>
        </div>
        <div nz-col [nzSpan]="4">
          <nz-form-item>
            <nz-form-control>
              <nz-input-group nzPrefixIcon="cluster">
                <input
                  type="text"
                  nz-input
                  placeholder="Campaign"
                  formControlName="campaign"
                  nzAllowClear="true"
                />
              </nz-input-group>
            </nz-form-control>
          </nz-form-item>
        </div>
        <div nz-col [nzSpan]="4">
          <nz-form-item>
            <nz-form-control>
              <nz-input-group nzPrefixIcon="tag">
                <input
                  type="text"
                  nz-input
                  placeholder="Adgroup"
                  formControlName="adgroup"
                  nzAllowClear="true"
                />
              </nz-input-group>
            </nz-form-control>
          </nz-form-item>
        </div>
        <div nz-col [nzSpan]="4">
          <nz-form-item>
            <nz-form-control>
              <nz-input-group nzPrefixIcon="picture">
                <input
                  type="text"
                  nz-input
                  placeholder="Creative"
                  formControlName="creative"
                  nzAllowClear="true"
                />
              </nz-input-group>
            </nz-form-control>
          </nz-form-item>
        </div>
        <div nz-col [nzSpan]="4">
          <nz-form-item>
            <nz-form-control>
              <nz-select
                nzPlaceHolder="国家代码"
                formControlName="cc"
                nzAllowClear="true"
              >
                <nz-option nzValue="US" nzLabel="美国"></nz-option>
                <nz-option nzValue="BR" nzLabel="巴西"></nz-option>
                <nz-option nzValue="RU" nzLabel="俄罗斯"></nz-option>
                <nz-option nzValue="ES" nzLabel="西班牙"></nz-option>
                <nz-option nzValue="FR" nzLabel="法国"></nz-option>
                <nz-option nzValue="PT" nzLabel="葡萄牙"></nz-option>
                <nz-option nzValue="IN" nzLabel="印度"></nz-option>
                <nz-option nzValue="JP" nzLabel="日本"></nz-option>
                <nz-option nzValue="KR" nzLabel="韩国"></nz-option>
                <nz-option nzValue="DE" nzLabel="德国"></nz-option>
                <nz-option nzValue="IT" nzLabel="意大利"></nz-option>
                <nz-option nzValue="GB" nzLabel="英国"></nz-option>
                <nz-option nzValue="TH" nzLabel="泰国"></nz-option>
                <nz-option nzValue="VN" nzLabel="越南"></nz-option>
                <nz-option nzValue="ID" nzLabel="印度尼西亚"></nz-option>
              </nz-select>
            </nz-form-control>
          </nz-form-item>
        </div>
        <div nz-col [nzSpan]="8">
          <nz-form-item>
            <nz-form-control>
              <nz-range-picker
                class="full-width-range-picker"
                nzPlaceHolder="首次登录"
                formControlName="firstLoginAt"
                nzAllowClear="true"
                (nzOnOpenChange)="onDatePickerChange()"
              ></nz-range-picker>
            </nz-form-control>
          </nz-form-item>
        </div>
        <div nz-col [nzSpan]="8">
          <nz-form-item>
            <nz-form-control>
              <nz-range-picker
                class="full-width-range-picker"
                nzPlaceHolder="最后活跃"
                formControlName="lastActiveAt"
                nzAllowClear="true"
                (nzOnOpenChange)="onDatePickerChange()"
              ></nz-range-picker>
            </nz-form-control>
          </nz-form-item>
        </div>
        <div nz-col [nzSpan]="8" class="button-col">
          <button nz-button (click)="resetForm()">重置</button>
        </div>
      </div>
    </form>

    <!-- 用户列表表格保持不变 -->
    <nz-table
      #userTable
      [nzData]="users"
      [nzLoading]="isLoading"
      [nzTotal]="total"
      [nzPageIndex]="pageIndex"
      [nzPageSize]="pageSize"
      (nzPageIndexChange)="onPageIndexChange($event)"
      (nzPageSizeChange)="onPageSizeChange($event)"
      [nzFrontPagination]="false"
      [nzBordered]="true"
      [nzSize]="'small'"
      [nzShowPagination]="false"
    >
      <thead>
        <tr>
          <th>UID</th>
          <th>项目</th>
          <th>国家</th>
          <th>语言</th>
          <th>设备型号</th>
          <th>应用版本</th>
          <th>首次登录时间</th>
          <th>最后活跃时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let user of userTable.data">
          <td>{{ user.uid }}</td>
          <td>{{ user.project }}</td>
          <td>{{ user.cc }}</td>
          <td>{{ user.lang }}</td>
          <td>{{ user.deviceModel }}</td>
          <td>{{ user.versionName }}</td>
          <td>{{ user.firstLoginAt | date : 'yyyy-MM-dd HH:mm:ss' }}</td>
          <td>{{ user.lastActiveAt | date : 'yyyy-MM-dd HH:mm:ss' }}</td>
          <td>
            <a (click)="showUserDetails(user)">详情</a>
            <nz-divider nzType="vertical"></nz-divider>
            <a (click)="editUser(user)">编辑</a>
            <nz-divider nzType="vertical"></nz-divider>
            <a (click)="sendMessage(user)">消息推送</a>
            <nz-divider nzType="vertical"></nz-divider>
            <a
              nz-popconfirm
              nzPopconfirmTitle="确定要删除该用户吗？"
              nzPopconfirmOkText="确定"
              nzPopconfirmCancelText="取消"
              (nzOnConfirm)="deleteUser(user.uid)"
              >删除
            </a>
          </td>
        </tr>
      </tbody>
    </nz-table>
    <!-- 独立的分页控件 -->
    <div class="pagination-container">
      <nz-pagination
        [nzPageIndex]="pageIndex"
        [nzTotal]="total"
        [nzPageSize]="pageSize"
        (nzPageIndexChange)="onPageIndexChange($event)"
        (nzPageSizeChange)="onPageSizeChange($event)"
        nzShowSizeChanger
        nzShowQuickJumper
      ></nz-pagination>
    </div>
  `,
  styles: [
    `
      .button-col {
        display: flex;
        gap: 8px;
        justify-content: end;
      }

      .full-width-range-picker {
        width: 100%;
      }

      nz-form-control {
        display: block;
      }

      .full-width-range-picker .ant-picker-input {
        width: 100%;
      }

      @media (max-width: 768px) {
        .full-width-range-picker {
          min-width: 100%;
        }
      }

      /* 分页容器样式 */
      .pagination-container {
        display: flex;
        justify-content: start;
        margin-top: 16px;
        padding: 8px 0;
        background: #fff;
        border-radius: 4px;
        box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
      }
    `,
  ],
})
export class UserComponent implements OnInit, OnDestroy {
  users: User[] = [];
  isLoading = false;
  total = 0;
  pageIndex = 1;
  pageSize = 20;
  filterForm: FormGroup;
  private queryParamsSubscription!: Subscription;

  constructor(
    private userService: UserService,
    private message: NzMessageService,
    private fb: FormBuilder,
    private modalService: NzModalService,
    private router: Router,
    private route: ActivatedRoute
  ) {
    this.filterForm = this.fb.group({
      uid: [null],
      network: [null],
      campaign: [null],
      adgroup: [null],
      creative: [null],
      cc: [null],
      firstLoginAt: [null],
      lastActiveAt: [null],
    });
  }

  ngOnInit(): void {
    // 订阅 URL 查询参数的变化
    this.queryParamsSubscription = this.route.queryParams.subscribe(
      (params) => {
        // 从 URL 参数中更新组件状态
        this.pageIndex = params['page'] ? parseInt(params['page'], 10) : 1;
        this.pageSize = params['limit'] ? parseInt(params['limit'], 10) : 20;

        // 更新表单控件的值，日期需要特殊处理
        const formValue: any = {};
        for (const key in this.filterForm.controls) {
          if (params[key]) {
            if (key === 'firstLoginAt' || key === 'lastActiveAt') {
              const dateRange = params[key].split(',');
              if (dateRange.length === 2) {
                formValue[key] = [
                  new Date(dateRange[0]),
                  new Date(dateRange[1]),
                ];
              }
            } else {
              formValue[key] = params[key];
            }
          }
        }
        // ***** 修复: 将 setValue 更改为 patchValue *****
        this.filterForm.patchValue(formValue, { emitEvent: false }); // 使用 patchValue 避免未提供值的控件报错

        this.loadUsers();
      }
    );

    // 监听表单变化，自动触发查询
    this.filterForm.valueChanges
      .pipe(debounceTime(500), distinctUntilChanged())
      .subscribe(() => {
        this.onFilter();
      });
  }

  ngOnDestroy(): void {
    if (this.queryParamsSubscription) {
      this.queryParamsSubscription.unsubscribe();
    }
  }

  // 日期选择器变化处理
  onDatePickerChange(): void {
    this.onFilter();
  }

  loadUsers(): void {
    this.isLoading = true;
    const filters = this.prepareFilters();

    this.userService
      .getPaginatedUsers(this.pageIndex, this.pageSize, filters)
      .subscribe({
        next: (response) => {
          this.users = response.users;
          this.total = response.total;
          this.isLoading = false;
        },
        error: (err) => {
          this.message.error('加载用户列表失败');
          this.isLoading = false;
          console.error('Failed to load users', err);
        },
      });
  }

  private prepareFilters(): any {
    const formValue = this.filterForm.value;
    const filters: any = {};

    for (const key in formValue) {
      if (
        formValue.hasOwnProperty(key) &&
        formValue[key] !== null &&
        formValue[key] !== ''
      ) {
        if (key === 'firstLoginAt' || key === 'lastActiveAt') {
          if (formValue[key] && formValue[key][0] && formValue[key][1]) {
            const start = this.formatDate(formValue[key][0]);
            const end = this.formatDate(formValue[key][1]);
            filters[key] = `${start},${end}`;
          }
        } else {
          filters[key] = formValue[key];
        }
      }
    }

    return filters;
  }

  private formatDate(date: Date): string {
    return date.toISOString().split('T')[0];
  }

  // 重构为私有方法，用于导航到新 URL
  private navigateToUrl(): void {
    const filters = this.prepareFilters();
    const queryParams = {
      page: this.pageIndex,
      limit: this.pageSize,
      ...filters,
    };

    // 使用 router.navigate 来更新 URL
    this.router.navigate([], {
      relativeTo: this.route,
      queryParams,
      // queryParamsHandling: 'merge', // 保留现有参数，但此处我们希望完全替换
    });
  }

  onPageSizeChange(size: number): void {
    this.pageSize = size;
    this.pageIndex = 1; // 切换分页大小时，重置到第一页
    this.navigateToUrl();
  }

  onPageIndexChange(index: number): void {
    this.pageIndex = index;
    this.navigateToUrl();
  }

  onFilter(): void {
    this.pageIndex = 1; // 筛选时重置到第一页
    this.navigateToUrl();
  }

  resetForm(): void {
    this.filterForm.reset();
    this.onFilter();
  }

  showUserDetails(user: User): void {
    this.modalService.create({
      nzTitle: `用户详情 - ${user.uid}`,
      nzContent: UserDetailModalComponent,
      nzData: user,
      nzWidth: '800px',
      nzFooter: null,
      nzBodyStyle: {
        'max-height': '70vh',
        'overflow-y': 'auto',
      },
    });
  }

  sendMessage(user: User): void {
    const modalRef = this.modalService.create({
      nzTitle: `向用户 ${user.uid} 发送消息`,
      nzContent: SendMessageModalComponent,
      nzWidth: '800px',
      nzOkText: '发送',
      nzCancelText: '取消',
      nzOnOk: () => {
        const instance =
          modalRef.componentInstance as SendMessageModalComponent;

        // 手动触发表单验证
        Object.values(instance.form.controls).forEach((control) => {
          if (control instanceof FormControl) {
            control.markAsDirty();
            control.updateValueAndValidity();
          }
        });

        if (instance.form.invalid) {
          return false;
        }

        // 处理扩展字段JSON
        let extendValue;
        if (instance.form.value.extend) {
          try {
            extendValue = JSON.parse(instance.form.value.extend);
          } catch (e) {
            instance.form.get('extend')?.setErrors({ invalidJson: true });
            return false;
          }
        }

        const payload = {
          uid: user.uid,
          ...instance.form.value,
          extend: extendValue,
        };

        this.message.loading('消息发送中...', { nzDuration: 0 });

        return new Promise((resolve) => {
          this.userService.sendDirectMessage(payload).subscribe({
            next: () => {
              this.message.remove();
              this.message.success('消息发送成功');
              resolve(true);
            },
            error: (err) => {
              this.message.remove();
              this.message.error(err.error.message);
              resolve(false);
            },
            complete: () => {
              // this.message.remove();
            },
          });
        });
      },
    });
  }

  // 显示新建用户模态框
  showCreateUserModal(): void {
    const modalRef = this.modalService.create({
      nzTitle: '新建用户',
      nzContent: UserCreateModalComponent,
      nzWidth: '800px',
      nzOkText: '创建',
      nzCancelText: '取消',
      nzOnOk: () => {
        const instance = modalRef.componentInstance as UserCreateModalComponent;

        // 手动触发表单验证
        Object.values(instance.createForm.controls).forEach((control) => {
          if (control instanceof FormControl) {
            control.markAsDirty();
            control.updateValueAndValidity();
          }
        });

        if (instance.createForm.invalid) {
          return false;
        }

        // 准备创建用户的数据
        const userData = instance.createForm.value;

        // 显示加载中状态
        this.message.loading('正在创建用户...', { nzDuration: 0 });

        return new Promise((resolve) => {
          this.userService.createUser(userData).subscribe({
            next: (createdUser) => {
              this.message.remove();
              this.message.success('用户创建成功');
              this.loadUsers(); // 刷新用户列表
              resolve(true);
            },
            error: (err) => {
              this.message.remove();
              this.message.error(err.error.message || '创建用户失败');
              resolve(false);
            },
          });
        });
      },
    });
  }

  // 添加编辑用户方法
  editUser(user: User): void {
    const modalRef = this.modalService.create({
      nzTitle: `编辑用户 - ${user.uid}`,
      nzContent: UserEditModalComponent,
      nzWidth: '800px',
      nzData: { user }, // 传递当前用户数据
      nzOkText: '保存',
      nzCancelText: '取消',
      nzOnOk: () => {
        const instance = modalRef.componentInstance as UserEditModalComponent;

        // 手动触发表单验证
        Object.values(instance.editForm.controls).forEach((control) => {
          if (control instanceof FormControl) {
            control.markAsDirty();
            control.updateValueAndValidity();
          }
        });

        if (instance.editForm.invalid) {
          return false;
        }

        // 准备更新数据
        const updateData = instance.editForm.value;
        delete updateData.uid; // 不更新UID

        // 显示加载中状态
        this.message.loading('正在更新用户...', { nzDuration: 0 });

        return new Promise((resolve) => {
          this.userService.updateUser(user.uid, updateData).subscribe({
            next: () => {
              this.message.remove();
              this.message.success('用户更新成功');
              this.loadUsers(); // 刷新用户列表
              resolve(true);
            },
            error: (err) => {
              this.message.remove();
              this.message.error(err.error.message || '更新用户失败');
              resolve(false);
            },
          });
        });
      },
    });
  }

  deleteUser(uid: string): void {
    this.userService.deleteUser(uid).subscribe({
      next: () => {
        this.message.success('用户删除成功');
        this.loadUsers(); // 重新加载用户列表
      },
      error: (err) => {
        this.message.error(err.error.message);
        console.error('Failed to delete user', err);
      },
    });
  }
}
