import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, ActivatedRoute } from '@angular/router';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-consultation-list',
  standalone: true,
  imports: [CommonModule, RouterModule, FormsModule],
  template: `
    <div class="ios-container">
      <header class="ios-header">
        <button class="ios-back-btn" (click)="goBack()">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path d="M19 12H5M12 19l-7-7 7-7"/>
          </svg>
        </button>
        <h1>客户咨询记录</h1>
      </header>

      <div class="ios-content">
        <div class="toolbar">
          <div class="search-bar">
            <input type="text" placeholder="搜索咨询记录..." [(ngModel)]="keyword" (input)="applyFilters()">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <circle cx="11" cy="11" r="8"/>
              <line x1="21" y1="21" x2="16.65" y2="16.65"/>
            </svg>
          </div>
          <div class="quick-filters">
            <label>
              <input type="checkbox" [(ngModel)]="filterUnrepliedOver1h" (change)="applyFilters()"> 未回复超1小时
            </label>
            <label>
              <input type="checkbox" [(ngModel)]="filterSensitive" (change)="applyFilters()"> 含敏感词
            </label>
          </div>
        </div>

        <div class="consultation-list">
          <div class="consultation-card" *ngFor="let item of filteredConsultations">
            <div class="card-header">
              <div class="customer-info">
                <div class="avatar">{{item.customer.charAt(0)}}</div>
                <div>
                  <h3>{{item.customer}}</h3>
                  <p class="time">{{item.time}}</p>
                </div>
              </div>
              <span class="status-badge" [class.urgent]="item.priority === 'high'">
                {{item.priority === 'high' ? '紧急' : '普通'}}
              </span>
            </div>
            <p class="content">{{item.content}}</p>
            <div class="card-footer">
              <button class="ios-btn" (click)="openWeCom(item)" title="跳转企业微信">同步到企微</button>
              <button class="ios-btn outline">查看详情</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  `,
  styles: [`
    .toolbar { display:flex; justify-content: space-between; align-items:center; gap:12px; margin-bottom: 12px; }
    .quick-filters { display:flex; gap: 16px; color:#636366; font-size:14px; }
    .quick-filters input { margin-right:6px; }
    .search-bar { position: relative; }
    .search-bar input { width: 260px; padding: 10px 14px 10px 36px; border-radius: 10px; border: 1px solid #d1d1d6; background: #f7f7fb; }
    .search-bar svg { position:absolute; left: 10px; top: 50%; transform: translateY(-50%); color:#8e8e93; }
  `]
})
export class ConsultationListComponent implements OnInit {
  keyword = '';
  filterUnrepliedOver1h = false;
  filterSensitive = false;

  private sensitivePatterns = /(发手机|发邮箱|找不到人)/;

  consultations = [
    {customer: '张先生', time: '10:30', content: '咨询关于厨房改造的预算和工期', priority: 'normal', lastReplyMinutes: 30, weComUserId: 'zhangxiansheng'},
    {customer: '李女士', time: '11:45', content: '询问客厅设计风格建议，发手机给你', priority: 'high', lastReplyMinutes: 120, weComUserId: 'linnvshi'},
    {customer: '王先生', time: '14:20', content: '需要全屋设计方案咨询，发邮箱吧', priority: 'normal', lastReplyMinutes: 75, weComUserId: 'wangxiansheng'}
  ];

  filteredConsultations = [...this.consultations];

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    this.route.queryParams.subscribe(params => {
      const q = params['q'];
      if (q) {
        this.keyword = q;
      }
      this.applyFilters();
    });
  }

  applyFilters(): void {
    const kw = this.keyword.trim().toLowerCase();
    this.filteredConsultations = this.consultations.filter(item => {
      const matchKw = !kw || item.customer.toLowerCase().includes(kw) || item.content.toLowerCase().includes(kw);
      const matchUnreplied = !this.filterUnrepliedOver1h || (item.lastReplyMinutes ?? 0) > 60;
      const matchSensitive = !this.filterSensitive || this.sensitivePatterns.test(item.content);
      return matchKw && matchUnreplied && matchSensitive;
    });
  }

  openWeCom(item: any): void {
    const userId = item.weComUserId || encodeURIComponent(item.customer);
    const wecomUrl = `wecom://message?username=${userId}`;
    const webUrl = `https://work.weixin.qq.com/wework_admin/frame#contacts`;
    try {
      window.location.href = wecomUrl;
      setTimeout(() => {
        window.open(webUrl, '_blank');
      }, 800);
    } catch (_) {
      window.open(webUrl, '_blank');
    }
  }

  goBack() {
    history.back();
  }
}