import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { TeamAssignmentModalComponent, Designer } from '../team-assignment-modal/team-assignment-modal.component';
import { FormsModule } from '@angular/forms';
import { MatChipsModule } from '@angular/material/chips';
import { MatIconModule } from '@angular/material/icon';

// 定义客户信息接口
interface Customer {
  id: string;
  name: string;
  phone: string;
  wechat?: string;
  avatar?: string;
  customerType?: string;
  source?: string;
  remark?: string;
  demandType?: string;
  preferenceTags?: string[];
  followUpStatus?: string;
}

@Component({
  selector: 'app-consultation-order-panel',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    MatChipsModule,
    MatIconModule,
    TeamAssignmentModalComponent
  ],
  templateUrl: './consultation-order-panel.component.html',
  styleUrls: ['./consultation-order-panel.component.scss']
})
export class ConsultationOrderPanelComponent {
  @Output() orderCreated = new EventEmitter<any>();
  @Output() projectCreated = new EventEmitter<any>(); // 新增项目创建成功事件

  // 搜索客户关键词
  searchKeyword = '';
  // 搜索结果列表
  searchResults: Customer[] = [];
  // 选中的客户
  selectedCustomer: Customer | null = null;
  // 表单提交状态
  isSubmitting = false;
  // 项目需求卡片展开状态
  isRequirementCardExpanded = false;

  // 需求表单
  requirementForm: FormGroup;
  // 客户表单
  customerForm: FormGroup;
  
  // 团队分配弹窗相关
  showTeamAssignmentModal = false;
  selectedDesigner: Designer | null = null;

  // 样式选项
  styleOptions = [
    '现代简约', '北欧风', '工业风', '新中式', '法式轻奢', '日式', '美式', '混搭'
  ];

  // 项目小组选项
  projectGroupOptions = [
    '设计一组', '设计二组', '设计三组', '高端定制组', '软装设计组'
  ];

  // 偏好标签选项
  preferenceTagOptions = [
    '柔和色系', '明亮色系', '深色系', '中性色系',
    '环保材料', '实木', '大理石', '瓷砖', '地板', '墙纸',
    '现代简约', '北欧风格', '中式风格', '美式风格', '工业风',
    '智能家电', '收纳空间', '开放式厨房', '大窗户'
  ];

  preferenceTags: string[] = [];
  // 新标签输入
  newTag = '';
  // 角色上下文
  roleContext: 'customer-service' | 'designer' | 'team-leader' = 'customer-service';

  constructor(private fb: FormBuilder) {
    // 初始化需求表单
    this.requirementForm = this.fb.group({
      decorationType: ['', Validators.required],
      downPayment: ['', [Validators.required, Validators.min(0)]],
      firstDraftDate: ['', Validators.required],
      style: [''],
      projectGroup: [''],
      budget: ['', Validators.required],
      area: ['', [Validators.required, Validators.min(1)]],
      smallImageTime: [''],
      largeImageTime: [''],
      houseType: [''],
      floor: ['', Validators.min(1)],
      preferredDesigner: [''],
      specialRequirements: [''],
      referenceCases: [[]],
      priceDetails: [''],
      // 新增字段
      spaceRequirements: [''],
      designAngles: [''],
      specialAreaHandling: [''],
      materialRequirements: [''],
      lightingRequirements: ['']
    });

    // 初始化客户表单
    this.customerForm = this.fb.group({
      name: ['', Validators.required],
      phone: ['', [Validators.required, Validators.pattern(/^1[3-9]\d{9}$/)]],
      wechat: [''],
      customerType: ['新客户'],
      source: [''],
      remark: [''],
      demandType: [''],
      followUpStatus: ['']
    });
  }

  // 搜索客户
  searchCustomer() {
    if (this.searchKeyword.length >= 2) {
      // 模拟搜索结果
      this.searchResults = [
        {
          id: '1',
          name: '张先生',
          phone: '138****5678',
          customerType: '老客户',
          source: '官网咨询',
          avatar: "data:image/svg+xml,%3Csvg width='64' height='40' xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='100%25' height='100%25' fill='%23E6E6E6'/%3E%3Ctext x='50%25' y='50%25' font-family='Arial' font-size='13.333333333333334' font-weight='bold' text-anchor='middle' fill='%23555555' dy='0.3em'%3EIMG%3C/text%3E%3C/svg%3E"
        },
        {
          id: '2',
          name: '李女士',
          phone: '139****1234',
          customerType: 'VIP客户',
          source: '推荐介绍',
          avatar: "data:image/svg+xml,%3Csvg width='65' height='40' xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='100%25' height='100%25' fill='%23DCDCDC'/%3E%3Ctext x='50%25' y='50%25' font-family='Arial' font-size='13.333333333333334' font-weight='bold' text-anchor='middle' fill='%23555555' dy='0.3em'%3EIMG%3C/text%3E%3C/svg%3E"
        }
      ];
    }
  }

  // 选择客户
  selectCustomer(customer: Customer) {
    this.selectedCustomer = customer;
    // 填充客户表单
    this.customerForm.patchValue({
      name: customer.name,
      phone: customer.phone,
      wechat: customer.wechat || '',
      customerType: customer.customerType || '新客户',
      source: customer.source || '',
      remark: customer.remark || ''
    });
    
    // 清空搜索结果
    this.searchResults = [];
    this.searchKeyword = '';
  }

  // 清除选中的客户
  clearSelectedCustomer() {
    this.selectedCustomer = null;
    this.customerForm.reset({
      customerType: '新客户'
    });
  }

  // 添加偏好标签
  addPreferenceTag(tag: string): void {
    if (tag && !this.preferenceTags.includes(tag)) {
      this.preferenceTags.push(tag);
      this.newTag = ''; // 清空输入框
    }
  }

  // 删除偏好标签
  removePreferenceTag(tag: string): void {
    const index = this.preferenceTags.indexOf(tag);
    if (index >= 0) {
      this.preferenceTags.splice(index, 1);
    }
  }

  // 检查表单是否有效
  isFormValid(): boolean {
    return this.customerForm.valid && this.requirementForm.valid;
  }

  // 提交表单
  submitForm() {
    if (this.customerForm.valid && this.requirementForm.valid) {
      this.isSubmitting = true;
      
      const formData = {
        customerInfo: this.customerForm.value,
        requirementInfo: this.requirementForm.value,
        preferenceTags: this.preferenceTags,
        roleContext: this.roleContext, // 添加角色上下文信息
        createdAt: new Date()
      };

      // 模拟提交请求
      setTimeout(() => {
        this.isSubmitting = false;
        this.orderCreated.emit(formData);
      }, 1000);
    }
  }

  // 关闭团队分配弹窗
  closeTeamAssignmentModal() {
    this.showTeamAssignmentModal = false;
  }

  // 确认团队分配
  confirmTeamAssignment(designer: Designer) {
    this.selectedDesigner = designer;
    this.showTeamAssignmentModal = false;
    
    // 发出项目创建成功事件
    const projectData = {
      customerInfo: this.customerForm.value,
      requirementInfo: this.requirementForm.value,
      preferenceTags: this.preferenceTags,
      assignedDesigner: designer,
      createdAt: new Date()
    };
    
    this.projectCreated.emit(projectData);
    
    // 重置表单
    this.customerForm.reset({
      customerType: '新客户'
    });
    this.requirementForm.reset();
    this.preferenceTags = [];
    this.selectedCustomer = null;
  }
}