import { Component, EventEmitter, Input, Output, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { FmodeObject } from 'fmode-ng/parse';
import { ProjectIssueService, ProjectIssue, IssueStatus, IssuePriority, IssueType, IssueCounts } from '../../services/project-issue.service';
import { WxworkCorp } from 'fmode-ng/core';

@Component({
  selector: 'app-project-issues-modal',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './project-issues-modal.component.html',
  styleUrls: ['./project-issues-modal.component.scss']
})
export class ProjectIssuesModalComponent implements OnInit, OnChanges {
  @Input() project: FmodeObject | null = null;
  @Input() currentUser: FmodeObject | null = null;
  @Input() isVisible: boolean = false;
  @Output() close = new EventEmitter<void>();

  issues: ProjectIssue[] = [];
  counts: IssueCounts = { total: 0, open: 0, in_progress: 0, resolved: 0, closed: 0 };

  filterStatus: IssueStatus[] = [];
  searchText: string = '';

  // 创建表单
  creating: boolean = false;
  newTitle: string = '';
  newDescription: string = '';
  newPriority: IssuePriority = 'medium';
  newType: IssueType = 'task';
  newDueDate?: string;
  newTagsText: string = '';
  // 新增：负责人与关联信息
  assignees: { id: string; name: string }[] = [];
  selectedAssigneeId: string = '';
  newRelatedSpace: string = '';
  newRelatedStage: string = '';

  loading: boolean = false;
  error: string | null = null;
  wwcorp:WxworkCorp | null = null;

  constructor(private issueService: ProjectIssueService) {
    let cid = localStorage.getItem('company') || this.project?.get("company")?.id || ""
    this.wwcorp = new WxworkCorp(cid);
  }

  ngOnInit() {
    this.refresh();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['isVisible'] && this.isVisible) {
      this.refresh();
    }
    if (changes['project'] && this.project) {
      this.refresh();
    }
  }

  async refresh() {
    if (!this.project?.id) return;
    try {
      this.loading = true;
      // 从后端刷新缓存并应用筛选
      await this.issueService.refreshFromServer(this.project.id, {
        status: this.filterStatus,
        text: this.searchText
      });
      this.issues = this.issueService.listIssues(this.project.id, {
        status: this.filterStatus,
        text: this.searchText
      });
      this.counts = this.issueService.getCounts(this.project.id);
      this.loading = false;
    } catch (err: any) {
      this.error = err?.message || '加载问题列表失败';
      this.loading = false;
    }
  }

  toggleStatusFilter(status: IssueStatus) {
    const idx = this.filterStatus.indexOf(status);
    if (idx >= 0) this.filterStatus.splice(idx, 1); else this.filterStatus.push(status);
    this.refresh();
  }

  onSearchChange() {
    this.refresh();
  }

  async startCreate() {
    this.creating = true;
    this.newTitle = '';
    this.newDescription = '';
    this.newPriority = 'medium';
    this.newType = 'task';
    this.newDueDate = undefined;
    this.newTagsText = '';
    this.selectedAssigneeId = '';
    this.newRelatedSpace = '';
    this.newRelatedStage = '';
    // 加载负责人候选
    if (this.project?.id) {
      this.assignees = await this.issueService.listAssignees(this.project.id);
    }
  }

  cancelCreate() {
    this.creating = false;
  }

  async submitCreate() {
    if (!this.project?.id || !this.currentUser?.id) return;
    if (!this.newTitle.trim()) return;

    const tags = this.newTagsText
      .split(',')
      .map(t => t.trim())
      .filter(Boolean);

    const due = this.newDueDate ? new Date(this.newDueDate) : undefined;

    await this.issueService.createIssue(this.project.id, {
      title: this.newTitle.trim(),
      description: this.newDescription.trim(),
      priority: this.newPriority,
      type: this.newType,
      creatorId: this.currentUser.id,
      assigneeId: this.selectedAssigneeId || undefined,
      dueDate: due,
      tags,
      relatedSpace: this.newRelatedSpace.trim() || undefined,
      relatedStage: this.newRelatedStage.trim() || undefined
    });

    this.creating = false;
    this.refresh();
  }

  async setStatus(issue: ProjectIssue, status: IssueStatus) {
    if (!this.project?.id) return;
    await this.issueService.setStatus(this.project.id, issue.id, status);
    this.refresh();
  }

  async deleteIssue(issue: ProjectIssue) {
    if (!this.project?.id) return;
    await this.issueService.deleteIssue(this.project.id, issue.id);
    this.refresh();
  }

  async addComment(issue: ProjectIssue, text: string) {
    if (!this.project?.id || !this.currentUser?.id) return;
    const content = text.trim();
    if (!content) return;

    const md = `**项目：** ${this.project?.get('title')}
**问题：** ${issue.title}
**优先级：** ${this.priorityLabel(issue.priority)}
**类型：** ${this.typeLabel(issue.type)}
**状态：** ${this.statusLabel(issue.status)}
**评论人：** ${this.currentUser?.get('name') || ''}
<span style="color:red">**消息：** ${content}</span>`;

    this.wwcorp?.message.sendMarkdown({
      agentid:"1000017",
      touser: issue.assignee?.get('userid') || '',
      content: md
    });

    await this.issueService.addComment(this.project.id, issue.id, this.currentUser.id, content);
    this.refresh();
  }

  issueAlert(issue: ProjectIssue){
    const md = `**项目：** ${this.project?.get('title')}
**问题：** ${issue.title}
**优先级：** ${this.priorityLabel(issue.priority)}
**类型：** ${this.typeLabel(issue.type)}
**状态：** ${this.statusLabel(issue.status)}
**描述：** ${issue.description || '暂无'}
**截止日期：** ${issue.dueDate ? new Date(issue.dueDate).toLocaleString() : '未设置'}
**标签：** ${issue.tags?.join(', ') || '无'}`;

    this.wwcorp?.message.sendMarkdown({
      agentid:"1000017",
      touser: issue.assignee?.get('userid') || '',
      content: md
    });
  }

  onClose() {
    this.close.emit();
  }

  // 辅助：状态中文标签
  statusLabel(s: IssueStatus): string {
    const map: Record<IssueStatus, string> = {
      open: '待处理',
      in_progress: '进行中',
      resolved: '已解决',
      closed: '已关闭'
    };
    return map[s] || s;
  }

  // 辅助：优先级中文标签
  priorityLabel(p: IssuePriority): string {
    const map: Record<IssuePriority, string> = {
      low: '低',
      medium: '中',
      high: '高',
      critical: '紧急',
      urgent: '紧急'
    };
    return map[p] || p;
  }

  // 辅助：类型中文标签
  typeLabel(t: IssueType): string {
    const map: Record<IssueType, string> = {
      task: '任务',
      bug: '缺陷',
      feature: '需求',
      feedback:"反馈",
      risk:"风险"
    };
    return map[t] || t;
  }
}