project-detail.component.ts 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  1. import { Component, OnInit, Input, Output, EventEmitter, OnDestroy } from '@angular/core';
  2. import { CommonModule } from '@angular/common';
  3. import { Router, ActivatedRoute, RouterModule } from '@angular/router';
  4. import { IonicModule } from '@ionic/angular';
  5. import { WxworkSDK, WxworkCorp, WxworkAuth } from 'fmode-ng/core';
  6. import { FmodeParse, FmodeObject } from 'fmode-ng/parse';
  7. import { ProfileService } from '../../../../app/services/profile.service';
  8. import { ProjectBottomCardComponent } from '../../components/project-bottom-card/project-bottom-card.component';
  9. import { ProjectFilesModalComponent } from '../../components/project-files-modal/project-files-modal.component';
  10. import { ProjectMembersModalComponent } from '../../components/project-members-modal/project-members-modal.component';
  11. import { ProjectIssuesModalComponent } from '../../components/project-issues-modal/project-issues-modal.component';
  12. import { ProjectIssueService } from '../../services/project-issue.service';
  13. import { FormsModule } from '@angular/forms';
  14. import { CustomerSelectorComponent } from '../../components/contact-selector/contact-selector.component';
  15. import { OrderApprovalPanelComponent } from '../../../../app/shared/components/order-approval-panel/order-approval-panel.component';
  16. const Parse = FmodeParse.with('nova');
  17. /**
  18. * 项目详情核心组件
  19. *
  20. * 功能:
  21. * 1. 展示四阶段导航(订单分配、确认需求、交付执行、售后归档)
  22. * 2. 根据角色控制权限
  23. * 3. 子路由切换阶段内容
  24. * 4. 支持@Input和路由参数两种数据加载方式
  25. *
  26. * 路由:/wxwork/:cid/project/:projectId
  27. */
  28. @Component({
  29. selector: 'app-project-detail',
  30. standalone: true,
  31. imports: [
  32. CommonModule,
  33. IonicModule,
  34. RouterModule,
  35. ProjectBottomCardComponent,
  36. ProjectFilesModalComponent,
  37. ProjectMembersModalComponent,
  38. ProjectIssuesModalComponent,
  39. CustomerSelectorComponent,
  40. OrderApprovalPanelComponent
  41. ],
  42. templateUrl: './project-detail.component.html',
  43. styleUrls: ['./project-detail.component.scss']
  44. })
  45. export class ProjectDetailComponent implements OnInit, OnDestroy {
  46. // 输入参数(支持组件复用)
  47. @Input() project: FmodeObject | null = null;
  48. @Input() groupChat: FmodeObject | null = null;
  49. @Input() currentUser: FmodeObject | null = null;
  50. // 问题统计
  51. issueCount: number = 0;
  52. // 路由参数
  53. cid: string = '';
  54. projectId: string = '';
  55. groupId: string = '';
  56. profileId: string = '';
  57. chatId: string = ''; // 从企微进入时的 chat_id
  58. // 企微SDK
  59. wxwork: WxworkSDK | null = null;
  60. wecorp: WxworkCorp | null = null;
  61. wxAuth: WxworkAuth | null = null; // WxworkAuth 实例
  62. // 加载状态
  63. loading: boolean = true;
  64. error: string | null = null;
  65. // 项目数据
  66. contact: FmodeObject | null = null;
  67. assignee: FmodeObject | null = null;
  68. // 当前阶段
  69. currentStage: string = 'order'; // order | requirements | delivery | aftercare
  70. stages = [
  71. { id: 'order', name: '订单分配', icon: 'document-text-outline', number: 1 },
  72. { id: 'requirements', name: '确认需求', icon: 'checkmark-circle-outline', number: 2 },
  73. { id: 'delivery', name: '交付执行', icon: 'rocket-outline', number: 3 },
  74. { id: 'aftercare', name: '售后归档', icon: 'archive-outline', number: 4 }
  75. ];
  76. // 权限
  77. canEdit: boolean = false;
  78. canViewCustomerPhone: boolean = false;
  79. role: string = '';
  80. // 模态框状态
  81. showFilesModal: boolean = false;
  82. showMembersModal: boolean = false;
  83. showIssuesModal: boolean = false;
  84. // 新增:客户详情侧栏面板状态
  85. showContactPanel: boolean = false;
  86. // 问卷状态
  87. surveyStatus: {
  88. filled: boolean;
  89. text: string;
  90. icon: string;
  91. surveyLog?: FmodeObject;
  92. contact?: FmodeObject;
  93. } = {
  94. filled: false,
  95. text: '发送问卷',
  96. icon: 'document-text-outline'
  97. };
  98. // 折叠:项目基本信息
  99. showProjectInfoCollapsed: boolean = true;
  100. // 事件监听器引用
  101. private stageCompletedListener: any = null;
  102. // 🆕 停滞期和改图期状态
  103. get isStalled(): boolean {
  104. const data = this.project?.get('data') || {};
  105. return data.isStalled === true;
  106. }
  107. get isModification(): boolean {
  108. const data = this.project?.get('data') || {};
  109. return data.isModification === true;
  110. }
  111. get stagnationInfo() {
  112. const data = this.project?.get('data') || {};
  113. return {
  114. reasonType: data.stagnationReasonType,
  115. customReason: data.stagnationCustomReason,
  116. estimatedResumeDate: data.estimatedResumeDate,
  117. notes: data.reasonNotes,
  118. markedAt: data.markedAt,
  119. markedBy: data.markedBy
  120. };
  121. }
  122. get modificationInfo() {
  123. const data = this.project?.get('data') || {};
  124. return {
  125. reasonType: data.modificationReasonType,
  126. customReason: data.modificationCustomReason,
  127. notes: data.reasonNotes,
  128. markedAt: data.markedAt,
  129. markedBy: data.markedBy
  130. };
  131. }
  132. constructor(
  133. private router: Router,
  134. private route: ActivatedRoute,
  135. private profileService: ProfileService,
  136. private issueService: ProjectIssueService
  137. ) {}
  138. async ngOnInit() {
  139. // 获取路由参数
  140. this.cid = this.route.snapshot.paramMap.get('cid') || '';
  141. // 兼容:cid 在父级路由上
  142. if (!this.cid) {
  143. this.cid = this.route.parent?.snapshot.paramMap.get('cid') || '';
  144. }
  145. // 降级:从 localStorage 读取
  146. if (!this.cid) {
  147. this.cid = localStorage.getItem('company') || '';
  148. }
  149. this.projectId = this.route.snapshot.paramMap.get('projectId') || '';
  150. this.groupId = this.route.snapshot.queryParamMap.get('groupId') || '';
  151. this.profileId = this.route.snapshot.queryParamMap.get('profileId') || '';
  152. this.chatId = this.route.snapshot.queryParamMap.get('chatId') || '';
  153. console.log('📌 路由参数:', {
  154. cid: this.cid,
  155. projectId: this.projectId
  156. });
  157. // 监听路由变化
  158. this.route.firstChild?.url.subscribe((segments) => {
  159. if (segments.length > 0) {
  160. this.currentStage = segments[0].path;
  161. console.log('🔄 当前阶段已更新:', this.currentStage);
  162. }
  163. });
  164. // 初始化企微授权(不阻塞页面加载)
  165. await this.initWxworkAuth();
  166. await this.loadData();
  167. // 初始化工作流阶段(若缺失则根据已完成记录推断)
  168. this.ensureWorkflowStage();
  169. // 监听各阶段完成事件,自动推进到下一环节
  170. this.stageCompletedListener = async (e: any) => {
  171. console.log('🎯 [监听器] 事件触发', e?.detail);
  172. const stageId = e?.detail?.stage as string;
  173. if (!stageId) {
  174. console.error('❌ [监听器] 事件缺少 stage 参数');
  175. return;
  176. }
  177. console.log('✅ [监听器] 接收到阶段完成事件:', stageId);
  178. await this.advanceToNextStage(stageId);
  179. };
  180. console.log('📡 [初始化] 注册事件监听器: stage:completed');
  181. document.addEventListener('stage:completed', this.stageCompletedListener);
  182. console.log('✅ [初始化] 事件监听器注册成功');
  183. }
  184. /**
  185. * 组件销毁时清理事件监听器
  186. */
  187. ngOnDestroy() {
  188. if (this.stageCompletedListener) {
  189. document.removeEventListener('stage:completed', this.stageCompletedListener);
  190. console.log('🧹 已清理阶段完成事件监听器');
  191. }
  192. }
  193. /**
  194. * 初始化企微授权(不阻塞页面)
  195. */
  196. async initWxworkAuth() {
  197. try {
  198. let cid = this.cid || localStorage.getItem("company") || "";
  199. // 如果没有cid,记录警告但不抛出错误
  200. if (!cid) {
  201. console.warn('⚠️ 未找到company ID (cid),企微功能将不可用');
  202. return;
  203. }
  204. this.wxAuth = new WxworkAuth({ cid: cid });
  205. this.wxwork = new WxworkSDK({ cid: cid, appId: 'crm' });
  206. this.wecorp = new WxworkCorp(cid);
  207. console.log('✅ 企微SDK初始化成功,cid:', cid);
  208. } catch (error) {
  209. console.error('❌ 企微SDK初始化失败:', error);
  210. // 不阻塞页面加载
  211. }
  212. }
  213. /**
  214. * 折叠/展开 项目基本信息
  215. */
  216. toggleProjectInfo(): void {
  217. this.showProjectInfoCollapsed = !this.showProjectInfoCollapsed;
  218. }
  219. /**
  220. * 跳转到指定阶段(程序化跳转,用于阶段推进)
  221. */
  222. goToStage(stageId: 'order'|'requirements'|'delivery'|'aftercare') {
  223. console.log('🚀 [goToStage] 开始导航', {
  224. 目标阶段: stageId,
  225. 当前路由: this.router.url,
  226. cid: this.cid,
  227. projectId: this.projectId
  228. });
  229. // 更新本地状态
  230. this.currentStage = stageId;
  231. // 优先使用绝对路径导航(更可靠)
  232. if (this.cid && this.projectId) {
  233. console.log('🚀 [goToStage] 使用绝对路径导航');
  234. this.router.navigate(['/wxwork', this.cid, 'project', this.projectId, stageId])
  235. .then(success => {
  236. if (success) {
  237. console.log('✅ [goToStage] 导航成功:', stageId);
  238. }
  239. })
  240. .catch(err => {
  241. console.error('❌ [goToStage] 导航出错:', err);
  242. });
  243. } else {
  244. console.warn('⚠️ [goToStage] 缺少参数,使用相对路径', {
  245. cid: this.cid,
  246. projectId: this.projectId
  247. });
  248. // 降级:使用相对路径(直接切换子路由)
  249. this.router.navigate([stageId], { relativeTo: this.route })
  250. .then(success => {
  251. if (success) {
  252. console.log('✅ [goToStage] 相对路径导航成功');
  253. } else {
  254. console.error('❌ [goToStage] 相对路径导航失败');
  255. }
  256. })
  257. .catch(err => {
  258. console.error('❌ [goToStage] 相对路径导航出错:', err);
  259. });
  260. }
  261. }
  262. /**
  263. * 从给定阶段推进到下一个阶段
  264. */
  265. async advanceToNextStage(current: string) {
  266. console.log('🚀 [推进阶段] 开始', { current });
  267. const order = ['order','requirements','delivery','aftercare'];
  268. const idx = order.indexOf(current);
  269. console.log('🚀 [推进阶段] 阶段索引:', { current, idx });
  270. if (idx === -1) {
  271. console.error('❌ [推进阶段] 未找到当前阶段:', current);
  272. return;
  273. }
  274. if (idx >= order.length - 1) {
  275. console.log('✅ [推进阶段] 已到达最后阶段');
  276. window?.fmode?.alert('所有阶段已完成!');
  277. return;
  278. }
  279. const next = order[idx + 1];
  280. console.log('➡️ [推进阶段] 下一阶段:', next);
  281. // 持久化:标记当前阶段完成并设置下一阶段为当前
  282. console.log('💾 [推进阶段] 开始持久化');
  283. await this.persistStageProgress(current, next);
  284. console.log('✅ [推进阶段] 持久化完成');
  285. // 导航到下一阶段
  286. console.log('🚀 [推进阶段] 开始导航到:', next);
  287. this.goToStage(next as any);
  288. const nextStageName = this.stages.find(s => s.id === next)?.name || next;
  289. window?.fmode?.alert(`已自动跳转到下一阶段: ${nextStageName}`);
  290. console.log('✅ [推进阶段] 完成');
  291. }
  292. /**
  293. * 确保存在工作流当前阶段。如缺失则根据完成记录计算
  294. */
  295. ensureWorkflowStage() {
  296. if (!this.project) return;
  297. const order = ['order','requirements','delivery','aftercare'];
  298. const data = this.project.get('data') || {};
  299. const statuses = data.stageStatuses || {};
  300. let current = this.project.get('currentStage');
  301. if (!current) {
  302. // 找到第一个未完成的阶段
  303. current = order.find(s => statuses[s] !== 'completed') || 'aftercare';
  304. this.project.set('currentStage', current);
  305. }
  306. }
  307. /**
  308. * 持久化阶段推进(标记当前完成、设置下一阶段)
  309. */
  310. private async persistStageProgress(current: string, next: string) {
  311. if (!this.project) {
  312. console.warn('⚠️ 项目对象不存在,无法持久化');
  313. return;
  314. }
  315. console.log('💾 开始持久化阶段:', { current, next });
  316. const data = this.project.get('data') || {};
  317. data.stageStatuses = data.stageStatuses || {};
  318. data.stageStatuses[current] = 'completed';
  319. this.project.set('data', data);
  320. // 🔥 关键修复:将英文阶段ID映射为中文阶段名称
  321. const stageNameMap: Record<string, string> = {
  322. 'order': '订单分配',
  323. 'requirements': '确认需求',
  324. 'delivery': '白模', // 交付执行的第一个子阶段
  325. 'aftercare': '尾款结算'
  326. };
  327. const chineseStageName = stageNameMap[next] || next;
  328. this.project.set('currentStage', chineseStageName);
  329. console.log('💾 设置阶段状态:', {
  330. currentStage: chineseStageName,
  331. stageStatuses: data.stageStatuses
  332. });
  333. try {
  334. await this.project.save();
  335. console.log('✅ 阶段状态持久化成功');
  336. } catch (e) {
  337. console.warn('⚠️ 阶段状态持久化失败(忽略以保证流程可继续):', e);
  338. }
  339. }
  340. /**
  341. * 加载数据
  342. */
  343. async loadData() {
  344. try {
  345. this.loading = true;
  346. // 2. 获取当前用户(优先从全局服务获取)
  347. if (!this.currentUser?.id && this.wxAuth) {
  348. try {
  349. this.currentUser = await this.wxAuth.currentProfile();
  350. } catch (error) {
  351. console.warn('⚠️ 获取当前用户Profile失败:', error);
  352. }
  353. }
  354. // 设置权限
  355. this.role = this.currentUser?.get('roleName') || '';
  356. this.canEdit = ['客服', '组员', '组长', '管理员', '设计师', '客服主管'].includes(this.role);
  357. this.canViewCustomerPhone = ['客服', '组长', '管理员'].includes(this.role);
  358. const companyId = this.currentUser?.get('company')?.id || localStorage?.getItem("company");
  359. // 3. 加载项目
  360. // 🔥 关键修改:每次都重新加载项目数据,确保获取最新的停滞期/改图期状态
  361. if (this.projectId) {
  362. // 通过 projectId 加载(从后台进入)
  363. const query = new Parse.Query('Project');
  364. query.include('contact', 'assignee','department','department.leader');
  365. this.project = await query.get(this.projectId);
  366. console.log('🔄 [项目数据] 已从服务器重新加载,停滞期状态:', this.project?.get('data')?.isStalled, '改图期状态:', this.project?.get('data')?.isModification);
  367. } else if (this.chatId) {
  368. // 通过 chat_id 查找项目(从企微群聊进入)
  369. if (companyId) {
  370. // 先查找 GroupChat
  371. const gcQuery = new Parse.Query('GroupChat');
  372. gcQuery.equalTo('chat_id', this.chatId);
  373. gcQuery.equalTo('company', companyId);
  374. let groupChat = await gcQuery.first();
  375. if (groupChat) {
  376. this.groupChat = groupChat;
  377. const projectPointer = groupChat.get('project');
  378. if (projectPointer) {
  379. const pQuery = new Parse.Query('Project');
  380. pQuery.include('contact', 'assignee','department','department.leader');
  381. // 🔥 强制从服务器获取最新数据(确保停滞期/改图期状态实时更新)
  382. this.project = await pQuery.get(projectPointer.id);
  383. }
  384. }
  385. if (!this.project) {
  386. throw new Error('该群聊尚未关联项目,请先在后台创建项目');
  387. }
  388. }
  389. }
  390. if(!this.groupChat?.id){
  391. const gcQuery2 = new Parse.Query('GroupChat');
  392. gcQuery2.equalTo('project', this.projectId);
  393. gcQuery2.equalTo('company', companyId);
  394. this.groupChat = await gcQuery2.first();
  395. }
  396. this.wxwork?.syncGroupChat(this.groupChat?.toJSON())
  397. if (!this.project) {
  398. throw new Error('无法加载项目信息');
  399. }
  400. this.contact = this.project.get('contact');
  401. this.assignee = this.project.get('assignee');
  402. // 加载问卷状态
  403. await this.loadSurveyStatus();
  404. // 更新问题计数
  405. try {
  406. if (this.project?.id) {
  407. this.issueService.seed(this.project.id!);
  408. const counts = this.issueService.getCounts(this.project.id!);
  409. this.issueCount = counts.total;
  410. }
  411. } catch (e) {
  412. console.warn('统计问题数量失败:', e);
  413. }
  414. // 4. 加载群聊(如果没有传入且有groupId)
  415. if (!this.groupChat && this.groupId) {
  416. try {
  417. const gcQuery = new Parse.Query('GroupChat');
  418. this.groupChat = await gcQuery.get(this.groupId);
  419. } catch (err) {
  420. console.warn('加载群聊失败:', err);
  421. }
  422. }
  423. // 5. 【已禁用】验证项目阶段 - 只显示警告,不自动回退
  424. // ⚠️ 原因:自动回退会覆盖组长审批通过后的阶段推进,导致反复回退
  425. let projectStage = this.project.get('currentStage');
  426. const data = this.project.get('data') || {};
  427. console.log('🔍 [项目详情] 当前项目阶段:', projectStage);
  428. console.log('🔍 [项目详情] 项目数据:', {
  429. title: this.project.get('title'),
  430. projectType: this.project.get('projectType'),
  431. demoday: this.project.get('demoday'),
  432. quotationTotal: data.quotation?.total,
  433. approvalStatus: data.approvalStatus,
  434. approvalHistory: data.approvalHistory,
  435. requirementsAnalysis: !!data.requirementsAnalysis,
  436. spaceRequirements: !!data.spaceRequirements
  437. });
  438. // ⚠️ 【已禁用】自动回退检查 - 改为只记录警告
  439. let needRollback = false;
  440. let correctStage = projectStage;
  441. let rollbackReason = '';
  442. // 【已禁用】检查1:订单分配阶段完成情况 - 只记录警告,不回退
  443. if (projectStage && ['确认需求', '方案确认', '方案深化', '交付执行', '白模', '软装', '渲染', '后期', '建模', '尾款结算', '客户评价', '投诉处理', '售后归档'].includes(projectStage)) {
  444. const title = this.project.get('title');
  445. const projectType = this.project.get('projectType');
  446. const demoday = this.project.get('demoday');
  447. const quotationTotal = data.quotation?.total || 0;
  448. const approvalStatus = data.approvalStatus;
  449. // 检查订单分配阶段是否完成
  450. const orderStageIncomplete = !title || !projectType || !demoday || quotationTotal <= 0;
  451. // ✅ 智能判断审批状态:检查审批历史
  452. const hasApprovedHistory = data.approvalHistory?.some((h: any) =>
  453. h.stage === '订单分配' && h.status === 'approved'
  454. );
  455. const notApproved = approvalStatus !== 'approved' && !hasApprovedHistory;
  456. // ⚠️ 【已禁用回退】只记录警告,不执行回退
  457. if (orderStageIncomplete || notApproved) {
  458. const reasons = [];
  459. if (!title) reasons.push('缺少项目名称');
  460. if (!projectType) reasons.push('缺少项目类型');
  461. if (!demoday) reasons.push('缺少小图日期');
  462. if (quotationTotal <= 0) reasons.push('缺少报价数据');
  463. if (notApproved) reasons.push('待组长审批');
  464. console.warn('⚠️ [数据警告] 订单分配阶段数据不完整,但不执行回退:', {
  465. currentStage: projectStage,
  466. 缺失项: reasons,
  467. approvalStatus,
  468. hasApprovedHistory
  469. });
  470. } else {
  471. console.log('✅ [数据验证] 订单分配阶段数据完整');
  472. }
  473. }
  474. // 【已禁用】检查2:确认需求阶段完成情况 - 只记录警告,不回退
  475. if (projectStage && ['交付执行', '白模', '软装', '渲染', '后期', '建模', '尾款结算', '客户评价', '投诉处理', '售后归档'].includes(projectStage)) {
  476. const hasRequirements = data.requirementsAnalysis || data.spaceRequirements;
  477. if (!hasRequirements) {
  478. console.warn('⚠️ [数据警告] 确认需求阶段数据不完整,但不执行回退:', {
  479. currentStage: projectStage,
  480. hasRequirementsAnalysis: !!data.requirementsAnalysis,
  481. hasSpaceRequirements: !!data.spaceRequirements
  482. });
  483. } else {
  484. console.log('✅ [数据验证] 确认需求阶段数据完整');
  485. }
  486. }
  487. // 【已禁用】自动回退功能 - 避免覆盖审批通过后的阶段推进
  488. console.log('ℹ️ [阶段验证] 自动回退功能已禁用,当前阶段:', projectStage);
  489. // 映射到路由ID
  490. const stageMap: any = {
  491. '订单分配': 'order',
  492. '确认需求': 'requirements',
  493. '方案确认': 'requirements',
  494. '方案深化': 'requirements',
  495. '交付执行': 'delivery',
  496. '白模': 'delivery', // 🔥 交付执行子阶段
  497. '软装': 'delivery',
  498. '渲染': 'delivery',
  499. '后期': 'delivery',
  500. '建模': 'delivery',
  501. '尾款结算': 'aftercare',
  502. '客户评价': 'aftercare',
  503. '投诉处理': 'aftercare'
  504. };
  505. const targetStage = stageMap[projectStage] || 'order';
  506. console.log('🎯 [项目详情] 目标路由阶段:', targetStage);
  507. // 🔥 修复:始终导航到正确的阶段,即使已有子路由
  508. const currentChildRoute = this.route.firstChild?.snapshot.url[0]?.path;
  509. console.log('📍 [项目详情] 当前子路由:', currentChildRoute);
  510. if (!currentChildRoute || currentChildRoute !== targetStage) {
  511. console.log('🚀 [项目详情] 导航到正确阶段:', targetStage);
  512. this.router.navigate([targetStage], { relativeTo: this.route, replaceUrl: true });
  513. } else {
  514. console.log('✅ [项目详情] 已在正确阶段,无需导航');
  515. }
  516. } catch (err: any) {
  517. console.error('加载失败:', err);
  518. this.error = err.message || '加载失败';
  519. } finally {
  520. this.loading = false;
  521. }
  522. }
  523. /**
  524. * 切换阶段(查看模式)
  525. * 允许查看所有阶段,但不改变项目的实际阶段(currentStage)
  526. * 只有通过各阶段的提交按钮(如"确认订单")才能推进项目阶段
  527. */
  528. switchStage(stageId: string) {
  529. console.log('🔄 用户点击切换阶段(查看模式):', stageId, {
  530. currentRoute: this.router.url,
  531. currentViewStage: this.currentStage,
  532. projectActualStage: this.project?.get('currentStage')
  533. });
  534. // ✅ 允许查看所有阶段(包括未开始的)
  535. const status = this.getStageStatus(stageId);
  536. console.log(`✅ 切换到阶段视图: ${stageId} (项目实际状态: ${status})`);
  537. // ⚠️ 如果查看未开始的阶段,给予友好提示
  538. if (status === 'pending') {
  539. const stageName = this.stages.find(s => s.id === stageId)?.name || stageId;
  540. console.warn(`⚠️ 正在查看未开始的阶段: ${stageName}`);
  541. console.warn(`💡 提示: 这是查看模式,项目实际阶段不会改变`);
  542. console.warn(`💡 需要完成当前阶段的必填项才能推进到 ${stageName}`);
  543. }
  544. // 更新本地视图状态(仅影响显示,不影响项目实际阶段)
  545. this.currentStage = stageId;
  546. // 导航到指定阶段(查看模式)
  547. this.router.navigate([stageId], { relativeTo: this.route })
  548. .then(success => {
  549. if (success) {
  550. console.log('✅ 导航成功(查看模式):', stageId);
  551. } else {
  552. console.warn('⚠️ 导航失败:', stageId);
  553. }
  554. })
  555. .catch(err => {
  556. console.error('❌ 导航出错:', err);
  557. });
  558. }
  559. /**
  560. * 获取阶段状态(参考设计师端 getSectionStatus 实现)
  561. * @returns 'completed' - 已完成(绿色)| 'active' - 当前进行中(红色)| 'pending' - 待开始(灰色)
  562. */
  563. getStageStatus(stageId: string): 'completed' | 'active' | 'pending' {
  564. // 颜色显示仅依据“工作流状态”,不受临时浏览路由影响
  565. const data = this.project?.get('data') || {};
  566. const statuses = data.stageStatuses || {};
  567. let workflowCurrent = this.project?.get('currentStage') || 'order';
  568. // 🔥 关键修复:将中文阶段名称映射为英文ID
  569. const stageNameToId: Record<string, string> = {
  570. '订单分配': 'order',
  571. '确认需求': 'requirements',
  572. // 设计师阶段(需求阶段)
  573. '方案深化': 'requirements',
  574. // 交付执行子阶段统一归为 delivery
  575. '交付执行': 'delivery',
  576. '交付': 'delivery',
  577. '白模': 'delivery',
  578. '建模': 'delivery',
  579. '软装': 'delivery',
  580. '渲染': 'delivery',
  581. '后期': 'delivery',
  582. // 售后归档
  583. '售后归档': 'aftercare',
  584. '尾款结算': 'aftercare',
  585. '已完成': 'aftercare'
  586. };
  587. // 如果是中文名称,转换为英文ID
  588. if (stageNameToId[workflowCurrent]) {
  589. workflowCurrent = stageNameToId[workflowCurrent];
  590. }
  591. // 如果没有当前阶段(新创建的项目),默认订单分配为active(红色)
  592. if (!workflowCurrent || workflowCurrent === 'order') {
  593. return stageId === 'order' ? 'active' : 'pending';
  594. }
  595. // 计算阶段索引
  596. const stageOrder = ['order', 'requirements', 'delivery', 'aftercare'];
  597. const currentIdx = stageOrder.indexOf(workflowCurrent);
  598. const idx = stageOrder.indexOf(stageId);
  599. if (idx === -1 || currentIdx === -1) return 'pending';
  600. // 已完成的阶段:当前阶段之前的所有阶段(绿色)
  601. if (idx < currentIdx) return 'completed';
  602. // 当前进行中的阶段:等于当前阶段(红色)
  603. if (idx === currentIdx) return 'active';
  604. // 未开始的阶段:当前阶段之后的所有阶段(灰色)
  605. return 'pending';
  606. }
  607. /**
  608. * 返回
  609. */
  610. goBack() {
  611. let ua = navigator.userAgent.toLowerCase();
  612. let isWeixin = ua.indexOf("micromessenger") != -1;
  613. if(isWeixin){
  614. this.router.navigate(['/wxwork', this.cid, 'project-loader']);
  615. }else{
  616. history.back();
  617. }
  618. }
  619. /**
  620. * 更新项目阶段
  621. */
  622. async updateProjectStage(stage: string) {
  623. if (!this.project || !this.canEdit) return;
  624. try {
  625. this.project.set('currentStage', stage);
  626. await this.project.save();
  627. // 添加阶段历史
  628. const data = this.project.get('data') || {};
  629. const stageHistory = data.stageHistory || [];
  630. stageHistory.push({
  631. stage,
  632. startTime: new Date(),
  633. status: 'current',
  634. operator: {
  635. id: this.currentUser!.id,
  636. name: this.currentUser!.get('name'),
  637. role: this.role
  638. }
  639. });
  640. this.project.set('data', { ...data, stageHistory });
  641. await this.project.save();
  642. } catch (err) {
  643. console.error('更新阶段失败:', err);
  644. window?.fmode?.alert('更新失败');
  645. }
  646. }
  647. /**
  648. * 发送企微消息
  649. */
  650. async sendWxMessage(message: string) {
  651. if (!this.groupChat || !this.wecorp) return;
  652. try {
  653. const chatId = this.groupChat.get('chat_id');
  654. await this.wecorp.appchat.sendText(chatId, message);
  655. } catch (err) {
  656. console.error('发送消息失败:', err);
  657. }
  658. }
  659. /**
  660. * 选择客户(从群聊成员中选择外部联系人)
  661. */
  662. async selectCustomer() {
  663. console.log(this.canEdit, this.groupChat)
  664. if (!this.groupChat) return;
  665. try {
  666. const memberList = this.groupChat.get('member_list') || [];
  667. const externalMembers = memberList.filter((m: any) => m.type === 2);
  668. if (externalMembers.length === 0) {
  669. window?.fmode?.alert('当前群聊中没有外部联系人');
  670. return;
  671. }
  672. console.log(externalMembers)
  673. // 简单实现:选择第一个外部联系人
  674. // TODO: 实现选择器UI
  675. const selectedMember = externalMembers[0];
  676. await this.setCustomerFromMember(selectedMember);
  677. } catch (err) {
  678. console.error('选择客户失败:', err);
  679. window?.fmode?.alert('选择客户失败');
  680. }
  681. }
  682. /**
  683. * 从群成员设置客户
  684. */
  685. async setCustomerFromMember(member: any) {
  686. if (!this.wecorp) return;
  687. try {
  688. const companyId = this.currentUser?.get('company')?.id || localStorage.getItem("company");
  689. if (!companyId) throw new Error('无法获取企业信息');
  690. // 1. 查询是否已存在 ContactInfo
  691. const query = new Parse.Query('ContactInfo');
  692. query.equalTo('external_userid', member.userid);
  693. query.equalTo('company', companyId);
  694. let contactInfo = await query.first();
  695. // 2. 如果不存在,通过企微API获取并创建
  696. if (!contactInfo) {
  697. contactInfo = new Parse.Object("ContactInfo");
  698. }
  699. const externalContactData = await this.wecorp.externalContact.get(member.userid);
  700. console.log("externalContactData",externalContactData)
  701. const ContactInfo = Parse.Object.extend('ContactInfo');
  702. contactInfo.set('name', externalContactData.name);
  703. contactInfo.set('external_userid', member.userid);
  704. const company = new Parse.Object('Company');
  705. company.id = companyId;
  706. const companyPointer = company.toPointer();
  707. contactInfo.set('company', companyPointer);
  708. contactInfo.set('data', externalContactData);
  709. await contactInfo.save();
  710. // 3. 设置为项目客户
  711. if (this.project) {
  712. this.project.set('contact', contactInfo.toPointer());
  713. await this.project.save();
  714. this.contact = contactInfo;
  715. window?.fmode?.alert('客户设置成功');
  716. }
  717. } catch (err) {
  718. console.error('设置客户失败:', err);
  719. throw err;
  720. }
  721. }
  722. /**
  723. * 显示文件模态框
  724. */
  725. showFiles() {
  726. this.showFilesModal = true;
  727. }
  728. /**
  729. * 显示成员模态框
  730. */
  731. showMembers() {
  732. this.showMembersModal = true;
  733. }
  734. /** 显示问题模态框 */
  735. showIssues() {
  736. this.showIssuesModal = true;
  737. }
  738. /**
  739. * 关闭文件模态框
  740. */
  741. closeFilesModal() {
  742. this.showFilesModal = false;
  743. }
  744. /**
  745. * 关闭成员模态框
  746. */
  747. closeMembersModal() {
  748. this.showMembersModal = false;
  749. }
  750. /** 显示客户详情面板 */
  751. openContactPanel() {
  752. if (this.contact) {
  753. this.showContactPanel = true;
  754. }
  755. }
  756. /** 关闭客户详情面板 */
  757. closeContactPanel() {
  758. this.showContactPanel = false;
  759. }
  760. /** 关闭问题模态框 */
  761. closeIssuesModal() {
  762. this.showIssuesModal = false;
  763. if (this.project?.id) {
  764. const counts = this.issueService.getCounts(this.project.id!);
  765. this.issueCount = counts.total;
  766. }
  767. }
  768. /** 客户选择事件回调(接收子组件输出) */
  769. onContactSelected(evt: { contact: FmodeObject; isNewCustomer: boolean; action: 'selected' | 'created' | 'updated' }) {
  770. this.contact = evt.contact;
  771. // 重新加载问卷状态
  772. this.loadSurveyStatus();
  773. }
  774. /**
  775. * 加载问卷状态
  776. */
  777. async loadSurveyStatus() {
  778. if (!this.project?.id) return;
  779. try {
  780. const query = new Parse.Query('SurveyLog');
  781. query.equalTo('project', this.project.toPointer());
  782. query.equalTo('type', 'survey-project');
  783. query.equalTo('isCompleted', true);
  784. query.include("contact")
  785. const surveyLog = await query.first();
  786. if (surveyLog) {
  787. this.surveyStatus = {
  788. filled: true,
  789. text: '查看问卷',
  790. icon: 'checkmark-circle',
  791. surveyLog,
  792. contact:surveyLog?.get("contact")
  793. };
  794. console.log('✅ 问卷已填写');
  795. } else {
  796. this.surveyStatus = {
  797. filled: false,
  798. text: '发送问卷',
  799. icon: 'document-text-outline'
  800. };
  801. console.log('✅ 问卷未填写');
  802. }
  803. } catch (err) {
  804. console.error('❌ 查询问卷状态失败:', err);
  805. }
  806. }
  807. /**
  808. * 发送问卷
  809. */
  810. async sendSurvey() {
  811. if (!this.groupChat || !this.wxwork) {
  812. window?.fmode?.alert('无法发送问卷:未找到群聊或企微SDK未初始化');
  813. return;
  814. }
  815. try {
  816. const chatId = this.groupChat.get('chat_id');
  817. const surveyUrl = `${document.baseURI}/wxwork/${this.cid}/survey/project/${this.project?.id}`;
  818. await this.wxwork.ww.openExistedChatWithMsg({
  819. chatId: chatId,
  820. msg: {
  821. msgtype: 'link',
  822. link: {
  823. title: '《家装效果图服务需求调查表》',
  824. desc: '为让本次服务更贴合您的需求,请花3-5分钟填写简短问卷,感谢支持!',
  825. url: surveyUrl,
  826. imgUrl: `${document.baseURI}/assets/logo.jpg`
  827. }
  828. }
  829. });
  830. window?.fmode?.alert('问卷已发送到群聊!');
  831. } catch (err) {
  832. console.error('❌ 发送问卷失败:', err);
  833. window?.fmode?.alert('发送失败,请重试');
  834. }
  835. }
  836. /**
  837. * 查看问卷结果
  838. */
  839. async viewSurvey() {
  840. if (!this.surveyStatus.surveyLog) return;
  841. // 跳转到问卷页面查看结果
  842. this.router.navigate(['/wxwork', this.cid, 'survey', 'project', this.project?.id]);
  843. }
  844. /**
  845. * 处理问卷点击
  846. */
  847. async handleSurveyClick(event: Event) {
  848. event.stopPropagation();
  849. if (this.surveyStatus.filled) {
  850. // 已填写,查看结果
  851. await this.viewSurvey();
  852. } else {
  853. // 未填写,发送问卷
  854. await this.sendSurvey();
  855. }
  856. }
  857. /**
  858. * 是否显示审批面板
  859. * 条件:当前用户是组长 + 项目处于订单分配阶段 + 审批状态为待审批
  860. */
  861. get showApprovalPanel(): boolean {
  862. if (!this.project || !this.currentUser) {
  863. console.log('🔍 审批面板检查: 缺少项目或用户数据');
  864. return false;
  865. }
  866. const userRole = this.currentUser.get('roleName') || '';
  867. // ✅ 恢复正确的角色检查:只有组长才能看到审批面板
  868. const isTeamLeader = userRole === '设计组长' || userRole === 'team-leader' || userRole === '组长';
  869. const currentStage = this.project.get('currentStage') || '';
  870. const isOrderStage = currentStage === '订单分配' || currentStage === 'order';
  871. const data = this.project.get('data') || {};
  872. const approvalStatus = data.approvalStatus;
  873. const isPending = approvalStatus === 'pending';
  874. // console.log('🔍 审批面板检查:', {
  875. // userRole,
  876. // isTeamLeader,
  877. // currentStage,
  878. // isOrderStage,
  879. // approvalStatus,
  880. // isPending,
  881. // result: isTeamLeader && isOrderStage && isPending
  882. // });
  883. return isTeamLeader && isOrderStage && isPending;
  884. }
  885. /**
  886. * 处理审批完成事件
  887. */
  888. async onApprovalCompleted(event: any) {
  889. if (!this.project) return;
  890. try {
  891. const data = this.project.get('data') || {};
  892. const approvalHistory = data.approvalHistory || [];
  893. const latestRecord = approvalHistory[approvalHistory.length - 1];
  894. if (latestRecord) {
  895. latestRecord.status = event.action;
  896. latestRecord.approver = {
  897. id: this.currentUser?.id,
  898. name: this.currentUser?.get('name'),
  899. role: this.currentUser?.get('roleName')
  900. };
  901. latestRecord.approvalTime = new Date();
  902. latestRecord.comment = event.comment;
  903. latestRecord.reason = event.reason;
  904. }
  905. if (event.action === 'approved') {
  906. // 通过审批:推进到确认需求阶段
  907. data.approvalStatus = 'approved';
  908. this.project.set('currentStage', '确认需求');
  909. this.project.set('data', data);
  910. await this.project.save();
  911. alert('✅ 审批通过,项目已进入确认需求阶段');
  912. // 刷新页面数据
  913. await this.loadData();
  914. } else {
  915. // 驳回:保持在订单分配阶段,记录驳回原因
  916. data.approvalStatus = 'rejected';
  917. data.lastRejectionReason = event.reason || '未提供原因';
  918. this.project.set('data', data);
  919. await this.project.save();
  920. alert('✅ 已驳回订单,客服将收到通知');
  921. // 刷新页面数据
  922. await this.loadData();
  923. }
  924. } catch (err) {
  925. console.error('处理审批失败:', err);
  926. alert('审批操作失败,请重试');
  927. }
  928. }
  929. /**
  930. * 取消停滞期标记
  931. */
  932. async cancelStagnation(event?: Event) {
  933. // 阻止事件冒泡
  934. if (event) {
  935. event.stopPropagation();
  936. event.preventDefault();
  937. }
  938. if (!this.project) {
  939. console.warn('❌ 项目数据不存在');
  940. return;
  941. }
  942. // 确认对话框
  943. const confirmed = confirm('确定要取消该项目的停滞期状态吗?');
  944. if (!confirmed) return;
  945. try {
  946. console.log('🔄 [取消停滞期] 开始取消...');
  947. const data = this.project.get('data') || {};
  948. // 清除停滞期相关字段
  949. data.isStalled = false;
  950. delete data.stagnationReasonType;
  951. delete data.stagnationCustomReason;
  952. delete data.estimatedResumeDate;
  953. delete data.reasonNotes;
  954. delete data.markedAt;
  955. delete data.markedBy;
  956. this.project.set('data', data);
  957. await this.project.save();
  958. console.log('✅ 停滞期标记已取消');
  959. window?.fmode?.alert('停滞期标记已取消');
  960. // 刷新页面数据
  961. await this.loadData();
  962. } catch (err) {
  963. console.error('❌ 取消停滞期失败:', err);
  964. window?.fmode?.alert('操作失败,请重试');
  965. }
  966. }
  967. /**
  968. * 取消改图期标记(由上传文件后自动触发)
  969. */
  970. async cancelModification() {
  971. if (!this.project) return;
  972. try {
  973. const data = this.project.get('data') || {};
  974. // 清除改图期相关字段
  975. data.isModification = false;
  976. data.modificationReasonType = undefined;
  977. data.modificationCustomReason = undefined;
  978. data.reasonNotes = undefined;
  979. data.markedAt = undefined;
  980. data.markedBy = undefined;
  981. this.project.set('data', data);
  982. await this.project.save();
  983. console.log('✅ 改图期标记已自动取消');
  984. // 刷新页面数据
  985. await this.loadData();
  986. } catch (err) {
  987. console.error('❌ 取消改图期失败:', err);
  988. }
  989. }
  990. /**
  991. * 获取停滞/改图原因的显示文本
  992. */
  993. getReasonText(type: 'stagnation' | 'modification'): string {
  994. const info = type === 'stagnation' ? this.stagnationInfo : this.modificationInfo;
  995. if (!info.reasonType) return '';
  996. const reasonMap: Record<string, string> = {
  997. 'designer': '设计师原因',
  998. 'customer': '客户原因',
  999. 'custom': info.customReason || '其他原因'
  1000. };
  1001. return reasonMap[info.reasonType] || '';
  1002. }
  1003. }
  1004. // duplicate inline CustomerSelectorComponent removed (we keep single declaration above)