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

export interface OrderCustomer {
  id: string;
  name: string;
  phone: string;
  wechat?: string;
  avatar?: string;
  customerType?: string;
  source?: string;
  remark?: string;
}

@Component({
  selector: 'app-order-creation-card',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule],
  templateUrl: './order-creation-card.html',
  styleUrls: ['./order-creation-card.scss']
})
export class OrderCreationCardComponent {
  @Input() orderCreationMethod: 'miniprogram' | 'manual' = 'miniprogram';
  @Output() orderCreationMethodChange = new EventEmitter<'miniprogram' | 'manual'>();

  @Input() isSyncing = false;
  @Input() orderTime = '';

  @Input() customerSearchKeyword = '';
  @Output() customerSearchKeywordChange = new EventEmitter<string>();

  @Input() customerSearchResults: OrderCustomer[] = [];
  @Input() selectedCustomer: OrderCustomer | null = null;
  @Output() searchCustomer = new EventEmitter<void>();
  @Output() selectCustomer = new EventEmitter<OrderCustomer>();
  @Output() clearSelectedCustomer = new EventEmitter<void>();
  @Output() syncMiniprogram = new EventEmitter<void>();

  // 共享的表单与选项（由父组件提供）
  @Input() customerForm!: FormGroup;
  @Input() demandTypes: Array<{ value: string; label: string }> = [];
  @Input() followUpStatus: Array<{ value: string; label: string }> = [];

  // 行为封装
  setMethod(method: 'miniprogram' | 'manual') {
    if (this.orderCreationMethod !== method) {
      this.orderCreationMethod = method;
      this.orderCreationMethodChange.emit(method);
    }
  }

  onKeywordChange(v: string) {
    this.customerSearchKeyword = v;
    this.customerSearchKeywordChange.emit(v);
  }

  triggerSearch() {
    this.searchCustomer.emit();
  }

  chooseCustomer(c: OrderCustomer) {
    this.selectCustomer.emit(c);
  }

  clearCustomer() {
    this.clearSelectedCustomer.emit();
  }

  triggerSync() {
    if (!this.isSyncing) this.syncMiniprogram.emit();
  }
}