import { Component, OnInit, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { FmodeObject, FmodeParse } from 'fmode-ng/parse';
import { ProjectUploadService } from '../../../services/upload.service';
import { ProjectAIService } from '../../../services/ai.service';
import { WxworkSDKService } from '../../../services/wxwork-sdk.service';

const Parse = FmodeParse.with('nova');

/**
 * 确认需求阶段组件
 *
 * 功能：
 * 1. 参考图片上传与管理
 * 2. 色彩分析弹窗
 * 3. CAD文件上传
 * 4. 需求确认清单
 * 5. AI方案生成
 */
@Component({
  selector: 'app-stage-requirements',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './stage-requirements.component.html',
  styleUrls: ['./stage-requirements.component.scss']
})
export class StageRequirementsComponent implements OnInit {
  @Input() project: FmodeObject | null = null;
  @Input() customer: FmodeObject | null = null;
  @Input() currentUser: FmodeObject | null = null;
  @Input() canEdit: boolean = false;

  // 路由参数
  cid: string = '';
  projectId: string = '';

  // 服务注入
  wxwork: WxworkSDKService | null = null;

  // 参考图片
  referenceImages: Array<{
    url: string;
    name: string;
    type: string; // style | space | material
    uploadTime: Date;
    description?: string;
  }> = [];

  // CAD文件
  cadFiles: Array<{
    url: string;
    name: string;
    uploadTime: Date;
    size: number;
  }> = [];

  // 需求清单
  requirements = {
    spaces: [] as Array<{
      name: string;
      area: number;
      description: string;
      features: string[];
    }>,
    stylePreference: '',
    colorScheme: {
      primary: '',
      secondary: '',
      accent: '',
      atmosphere: '' // 温馨 | 高级 | 简约 | 时尚
    },
    budget: {
      min: 0,
      max: 0
    },
    specialRequirements: '',
    deadline: ''
  };

  // AI生成的方案
  aiSolution: {
    generated: boolean;
    content: string;
    spaces: Array<{
      name: string;
      styleDescription: string;
      colorPalette: string[];
      materials: string[];
      furnitureRecommendations: string[];
    }>;
    estimatedCost: number;
    timeline: string;
  } | null = null;

  // 加载状态
  loading: boolean = true;
  uploading: boolean = false;
  generating: boolean = false;
  saving: boolean = false;

  constructor(
    private route: ActivatedRoute,
    private uploadService: ProjectUploadService,
    private aiService: ProjectAIService,
    private wxworkService: WxworkSDKService
  ) {}

  async ngOnInit() {
    // 尝试从父组件获取数据（如果通过@Input传入）
    // 否则从路由参数加载
    if (!this.project || !this.customer || !this.currentUser) {
      this.cid = this.route.parent?.snapshot.paramMap.get('cid') || '';
      this.projectId = this.route.parent?.snapshot.paramMap.get('projectId') || '';
    }

    await this.loadData();
  }

  /**
   * 加载数据
   */
  async loadData() {
    try {
      this.loading = true;

      // 如果没有传入project，从路由参数加载
      if (!this.project && this.projectId) {
        const query = new Parse.Query('Project');
        query.include('customer', 'assignee');
        this.project = await query.get(this.projectId);
        this.customer = this.project.get('customer');
      }

      // 如果没有传入currentUser，加载当前用户
      if (!this.currentUser && this.cid) {
        await this.wxworkService.initialize(this.cid, 'crm');
        this.currentUser = await this.wxworkService.getCurrentUser();

        const role = this.currentUser?.get('roleName') || '';
        this.canEdit = ['客服', '组员', '组长', '管理员'].includes(role);
      }

      // 加载已保存的需求数据
      if (this.project) {
        const data = this.project.get('data') || {};

        if (data.requirements) {
          this.requirements = data.requirements;
        }

        if (data.referenceImages) {
          this.referenceImages = data.referenceImages;
        }

        if (data.cadFiles) {
          this.cadFiles = data.cadFiles;
        }

        if (data.aiSolution) {
          this.aiSolution = data.aiSolution;
        }

        // 从客户画像加载偏好
        if (this.customer) {
          const customerData = this.customer.get('data') || {};
          const preferences = customerData.preferences || {};

          if (!this.requirements.stylePreference && preferences.style) {
            this.requirements.stylePreference = preferences.style.join(', ');
          }

          if (!this.requirements.colorScheme.atmosphere && preferences.colorAtmosphere) {
            this.requirements.colorScheme.atmosphere = preferences.colorAtmosphere;
          }

          if (!this.requirements.budget.min && preferences.budget) {
            const [min, max] = this.parseBudgetRange(preferences.budget);
            this.requirements.budget.min = min;
            this.requirements.budget.max = max;
          }
        }
      }

    } catch (err) {
      console.error('加载失败:', err);
    } finally {
      this.loading = false;
    }
  }

  /**
   * 解析预算范围
   */
  parseBudgetRange(budgetStr: string): [number, number] {
    const match = budgetStr.match(/(\d+)-(\d+)/);
    if (match) {
      return [parseInt(match[1]) * 10000, parseInt(match[2]) * 10000];
    }
    return [0, 0];
  }

  /**
   * 上传参考图片
   */
  async uploadReferenceImage(event: any) {
    const file = event.target.files[0];
    if (!file) return;

    // 验证文件类型
    if (!this.uploadService.validateFileType(file, ['image/*'])) {
      alert('请上传图片文件');
      return;
    }

    // 验证文件大小 (10MB)
    if (!this.uploadService.validateFileSize(file, 10)) {
      alert('图片大小不能超过10MB');
      return;
    }

    try {
      this.uploading = true;

      // 上传文件到Parse Server
      const url = await this.uploadService.uploadFile(file, {
        compress: true,
        maxWidth: 1920,
        maxHeight: 1920,
        onProgress: (progress: number) => {
          console.log('上传进度:', progress);
        }
      });

      this.referenceImages.push({
        url: url,
        name: file.name,
        type: 'style',
        uploadTime: new Date()
      });

      await this.saveDraft();

    } catch (error: any) {
      console.error('上传失败:', error);
      alert('上传失败: ' + (error?.message || '未知错误'));
    } finally {
      this.uploading = false;
    }
  }

  /**
   * 删除参考图片
   */
  async deleteReferenceImage(index: number) {
    this.referenceImages.splice(index, 1);
    await this.saveDraft();
  }

  /**
   * 上传CAD文件
   */
  async uploadCAD(event: any) {
    const file = event.target.files[0];
    if (!file) return;

    // 验证文件类型
    const allowedTypes = [
      'application/acad',
      'application/x-acad',
      'application/dxf',
      'image/vnd.dwg',
      'image/x-dwg',
      'application/pdf'
    ];
    if (!allowedTypes.includes(file.type) &&
        !file.name.endsWith('.dwg') &&
        !file.name.endsWith('.dxf') &&
        !file.name.endsWith('.pdf')) {
      alert('请上传CAD文件(.dwg/.dxf)或PDF文件');
      return;
    }

    // 验证文件大小 (50MB)
    if (!this.uploadService.validateFileSize(file, 50)) {
      alert('文件大小不能超过50MB');
      return;
    }

    try {
      this.uploading = true;

      // 上传文件到Parse Server
      const url = await this.uploadService.uploadFile(file, {
        onProgress: (progress: number) => {
          console.log('上传进度:', progress);
        }
      });

      this.cadFiles.push({
        url: url,
        name: file.name,
        uploadTime: new Date(),
        size: file.size
      });

      await this.saveDraft();

    } catch (error: any) {
      console.error('上传失败:', error);
      alert('上传失败: ' + (error?.message || '未知错误'));
    } finally {
      this.uploading = false;
    }
  }

  /**
   * 删除CAD文件
   */
  async deleteCAD(index: number) {
    this.cadFiles.splice(index, 1);
    await this.saveDraft();
  }

  /**
   * 添加空间
   */
  addSpace() {
    this.requirements.spaces.push({
      name: '',
      area: 0,
      description: '',
      features: []
    });
  }

  /**
   * 删除空间
   */
  removeSpace(index: number) {
    this.requirements.spaces.splice(index, 1);
  }

  /**
   * 打开色彩分析弹窗
   */
  async openColorAnalysis() {
    // TODO: 实现色彩分析弹窗组件
    alert('色彩分析功能开发中...');
  }

  /**
   * 生成AI方案
   */
  async generateAISolution() {
    if (!this.project || !this.canEdit) return;

    // 验证必填项
    if (this.requirements.spaces.length === 0) {
      alert('请至少添加一个空间');
      return;
    }

    if (!this.requirements.stylePreference) {
      alert('请填写风格偏好');
      return;
    }

    try {
      this.generating = true;

      // 收集参考图片URL
      const imageUrls = this.referenceImages.map(img => img.url);

      // 调用AI服务生成方案
      const result = await this.aiService.generateDesignSolution(
        this.requirements,
        {
          images: imageUrls.length > 0 ? imageUrls : undefined,
          onProgress: (content) => {
            console.log('生成进度:', content.length);
          }
        }
      );

      this.aiSolution = result;

      // 保存到项目数据
      await this.saveDraft();

      alert('AI方案生成成功');

    } catch (error: any) {
      console.error('生成失败:', error);
      alert('生成失败: ' + (error?.message || '未知错误'));
    } finally {
      this.generating = false;
    }
  }


  /**
   * 保存草稿
   */
  async saveDraft() {
    if (!this.project || !this.canEdit) return;

    try {
      this.saving = true;

      const data = this.project.get('data') || {};
      data.requirements = this.requirements;
      data.referenceImages = this.referenceImages;
      data.cadFiles = this.cadFiles;

      if (this.aiSolution) {
        data.aiSolution = this.aiSolution;
      }

      this.project.set('data', data);
      await this.project.save();

    } catch (err) {
      console.error('保存失败:', err);
      alert('保存失败');
    } finally {
      this.saving = false;
    }
  }

  /**
   * 提交确认
   */
  async submitRequirements() {
    if (!this.project || !this.canEdit) return;

    // 验证必填项
    if (this.requirements.spaces.length === 0) {
      alert('请至少添加一个空间');
      return;
    }

    if (!this.requirements.stylePreference) {
      alert('请填写风格偏好');
      return;
    }

    if (!this.aiSolution) {
      alert('请先生成AI方案');
      return;
    }

    try {
      this.saving = true;

      // 保存数据
      await this.saveDraft();

      // 更新项目状态
      this.project.set('currentStage', '建模');
      this.project.set('status', '进行中');

      await this.project.save();

      alert('需求确认完成，进入交付执行阶段');

    } catch (err) {
      console.error('提交失败:', err);
      alert('提交失败');
    } finally {
      this.saving = false;
    }
  }

  /**
   * 格式化文件大小
   */
  formatFileSize(bytes: number): string {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
    return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
  }

  /**
   * 获取图片类型标签
   */
  getImageTypeLabel(type: string): string {
    const map: any = {
      'style': '风格参考',
      'space': '空间布局',
      'material': '材质参考'
    };
    return map[type] || '其他';
  }

  /**
   * 获取图片类型颜色
   */
  getImageTypeColor(type: string): string {
    const map: any = {
      'style': 'primary',
      'space': 'secondary',
      'material': 'tertiary'
    };
    return map[type] || 'medium';
  }
}
