import { Component, OnInit, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router, ActivatedRoute, RouterModule } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { WxworkSDK, WxworkCorp } from 'fmode-ng/core';
import { FmodeParse, FmodeObject } from 'fmode-ng/parse';

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

/**
 * 项目详情核心组件
 *
 * 功能：
 * 1. 展示四阶段导航（订单分配、确认需求、交付执行、售后归档）
 * 2. 根据角色控制权限
 * 3. 子路由切换阶段内容
 * 4. 支持@Input和路由参数两种数据加载方式
 *
 * 路由：/wxwork/:cid/project/:projectId
 */
@Component({
  selector: 'app-project-detail',
  standalone: true,
  imports: [CommonModule, IonicModule, RouterModule],
  templateUrl: './project-detail.component.html',
  styleUrls: ['./project-detail.component.scss']
})
export class ProjectDetailComponent implements OnInit {
  // 输入参数（支持组件复用）
  @Input() project: FmodeObject | null = null;
  @Input() groupChat: FmodeObject | null = null;
  @Input() currentUser: FmodeObject | null = null;

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

  // 企微SDK
  wxwork: WxworkSDK | null = null;
  wecorp: WxworkCorp | null = null;

  // 加载状态
  loading: boolean = true;
  error: string | null = null;

  // 项目数据
  customer: FmodeObject | null = null;
  assignee: FmodeObject | null = null;

  // 当前阶段
  currentStage: string = 'order'; // order | requirements | delivery | aftercare
  stages = [
    { id: 'order', name: '订单分配', icon: 'document-text-outline', number: 1 },
    { id: 'requirements', name: '确认需求', icon: 'checkmark-circle-outline', number: 2 },
    { id: 'delivery', name: '交付执行', icon: 'rocket-outline', number: 3 },
    { id: 'aftercare', name: '售后归档', icon: 'archive-outline', number: 4 }
  ];

  // 权限
  canEdit: boolean = false;
  canViewCustomerPhone: boolean = false;
  role: string = '';

  constructor(
    private router: Router,
    private route: ActivatedRoute
  ) {}

  async ngOnInit() {
    // 获取路由参数
    this.cid = this.route.snapshot.paramMap.get('cid') || '';
    this.projectId = this.route.snapshot.paramMap.get('projectId') || '';
    this.groupId = this.route.snapshot.queryParamMap.get('groupId') || '';
    this.profileId = this.route.snapshot.queryParamMap.get('profileId') || '';

    // 监听路由变化
    this.route.firstChild?.url.subscribe((segments) => {
      if (segments.length > 0) {
        this.currentStage = segments[0].path;
      }
    });

    await this.loadData();
  }

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

      // 1. 初始化SDK
      if (!this.wxwork) {
        this.wxwork = new WxworkSDK({ cid: this.cid, appId: 'crm' });
        this.wecorp = new WxworkCorp(this.cid);
      }

      // 2. 获取当前用户（如果没有传入）
      if (!this.currentUser) {
        if (this.profileId) {
          const query = new Parse.Query('Profile');
          this.currentUser = await query.get(this.profileId);
        } else {
          this.currentUser = await this.wxwork.getCurrentUser();
        }
      }

      // 设置权限
      this.role = this.currentUser?.get('roleName') || '';
      this.canEdit = ['客服', '组员', '组长', '管理员'].includes(this.role);
      this.canViewCustomerPhone = ['客服', '组长', '管理员'].includes(this.role);

      // 3. 加载项目（如果没有传入）
      if (!this.project) {
        const query = new Parse.Query('Project');
        query.include('customer', 'assignee');
        this.project = await query.get(this.projectId);
      }

      this.customer = this.project.get('customer');
      this.assignee = this.project.get('assignee');

      // 4. 加载群聊（如果没有传入）
      if (!this.groupChat && this.groupId) {
        const gcQuery = new Parse.Query('GroupChat');
        this.groupChat = await gcQuery.get(this.groupId);
      }

      // 5. 根据项目当前阶段设置默认路由
      const projectStage = this.project.get('currentStage');
      const stageMap: any = {
        '订单分配': 'order',
        '确认需求': 'requirements',
        '方案确认': 'requirements',
        '建模': 'delivery',
        '软装': 'delivery',
        '渲染': 'delivery',
        '后期': 'delivery',
        '尾款结算': 'aftercare',
        '客户评价': 'aftercare',
        '投诉处理': 'aftercare'
      };

      const targetStage = stageMap[projectStage] || 'order';

      // 如果当前没有子路由，跳转到对应阶段
      if (!this.route.firstChild) {
        this.router.navigate([targetStage], { relativeTo: this.route, replaceUrl: true });
      }
    } catch (err: any) {
      console.error('加载失败:', err);
      this.error = err.message || '加载失败';
    } finally {
      this.loading = false;
    }
  }

  /**
   * 切换阶段
   */
  switchStage(stageId: string) {
    this.currentStage = stageId;
    this.router.navigate([stageId], { relativeTo: this.route });
  }

  /**
   * 获取阶段状态
   */
  getStageStatus(stageId: string): 'completed' | 'active' | 'pending' {
    const projectStage = this.project?.get('currentStage') || '';
    const stageOrder = ['订单分配', '确认需求', '建模', '软装', '渲染', '后期', '尾款结算', '客户评价'];
    const currentIndex = stageOrder.indexOf(projectStage);

    const stageIndexMap: any = {
      'order': 0,
      'requirements': 1,
      'delivery': 3,
      'aftercare': 6
    };

    const targetIndex = stageIndexMap[stageId];

    if (currentIndex > targetIndex) {
      return 'completed';
    } else if (this.currentStage === stageId) {
      return 'active';
    } else {
      return 'pending';
    }
  }

  /**
   * 返回
   */
  goBack() {
    this.router.navigate(['/wxwork', this.cid, 'project-loader']);
  }

  /**
   * 更新项目阶段
   */
  async updateProjectStage(stage: string) {
    if (!this.project || !this.canEdit) return;

    try {
      this.project.set('currentStage', stage);
      await this.project.save();

      // 添加阶段历史
      const data = this.project.get('data') || {};
      const stageHistory = data.stageHistory || [];

      stageHistory.push({
        stage,
        startTime: new Date(),
        status: 'current',
        operator: {
          id: this.currentUser!.id,
          name: this.currentUser!.get('name'),
          role: this.role
        }
      });

      this.project.set('data', { ...data, stageHistory });
      await this.project.save();
    } catch (err) {
      console.error('更新阶段失败:', err);
      alert('更新失败');
    }
  }

  /**
   * 发送企微消息
   */
  async sendWxMessage(message: string) {
    if (!this.groupChat || !this.wecorp) return;

    try {
      const chatId = this.groupChat.get('chat_id');
      await this.wecorp.appchat.sendText(chatId, message);
    } catch (err) {
      console.error('发送消息失败:', err);
    }
  }
}
