dashboard.ts 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493
  1. import { CommonModule } from '@angular/common';
  2. import { FormsModule } from '@angular/forms';
  3. import { Router, RouterModule } from '@angular/router';
  4. import { Component, OnInit, OnDestroy, ElementRef, ViewChild } from '@angular/core';
  5. import { ProjectService } from '../../../services/project.service';
  6. import { DesignerService } from '../services/designer.service';
  7. import { WxworkAuth } from 'fmode-ng/core';
  8. import { ProjectIssueService, ProjectIssue, IssueStatus, IssuePriority, IssueType } from '../../../../modules/project/services/project-issue.service';
  9. import { FmodeParse } from 'fmode-ng/parse';
  10. // 项目阶段定义
  11. interface ProjectStage {
  12. id: string;
  13. name: string;
  14. order: number;
  15. }
  16. interface ProjectPhase {
  17. name: string;
  18. percentage: number;
  19. startPercentage: number;
  20. isCompleted: boolean;
  21. isCurrent: boolean;
  22. }
  23. interface Project {
  24. id: string;
  25. name: string;
  26. type: 'soft' | 'hard';
  27. memberType: 'vip' | 'normal';
  28. designerName: string;
  29. status: string;
  30. expectedEndDate: Date; // TODO: 兼容旧字段,后续可移除
  31. deadline: Date; // 真实截止时间字段
  32. createdAt?: Date; // 真实开始时间字段(可选)
  33. isOverdue: boolean;
  34. overdueDays: number;
  35. dueSoon: boolean;
  36. urgency: 'high' | 'medium' | 'low';
  37. phases: ProjectPhase[];
  38. currentStage: string; // 新增:当前项目阶段
  39. // 新增:质量评级
  40. qualityRating?: 'excellent' | 'qualified' | 'unqualified' | 'pending';
  41. lastCustomerFeedback?: string;
  42. // 预构建的搜索索引,减少重复 toLowerCase 与拼接
  43. searchIndex?: string;
  44. }
  45. interface TodoTask {
  46. id: string;
  47. title: string;
  48. description: string;
  49. deadline: Date;
  50. priority: 'high' | 'medium' | 'low';
  51. type: 'review' | 'assign' | 'performance';
  52. targetId: string;
  53. }
  54. // 新增:从问题板块映射的待办任务
  55. interface TodoTaskFromIssue {
  56. id: string;
  57. title: string;
  58. description?: string;
  59. priority: IssuePriority;
  60. type: IssueType;
  61. status: IssueStatus;
  62. projectId: string;
  63. projectName: string;
  64. relatedSpace?: string;
  65. relatedStage?: string;
  66. assigneeName?: string;
  67. creatorName?: string;
  68. createdAt: Date;
  69. updatedAt: Date;
  70. dueDate?: Date;
  71. tags?: string[];
  72. }
  73. // 员工请假记录接口
  74. interface LeaveRecord {
  75. id: string;
  76. employeeName: string;
  77. date: string; // YYYY-MM-DD 格式
  78. isLeave: boolean;
  79. leaveType?: 'sick' | 'personal' | 'annual' | 'other'; // 请假类型
  80. reason?: string; // 请假原因
  81. }
  82. // 员工详情面板数据接口
  83. interface EmployeeDetail {
  84. name: string;
  85. currentProjects: number; // 当前负责项目数
  86. projectNames: string[]; // 项目名称列表(用于显示)
  87. projectData: Array<{ id: string; name: string }>; // 项目数据(包含ID和名称,用于跳转)
  88. leaveRecords: LeaveRecord[]; // 未来7天请假记录
  89. redMarkExplanation: string; // 红色标记说明
  90. calendarData?: EmployeeCalendarData; // 负载日历数据
  91. // 新增:问卷相关
  92. surveyCompleted?: boolean; // 是否完成问卷
  93. surveyData?: any; // 问卷答案数据
  94. profileId?: string; // Profile ID
  95. }
  96. // 员工日历数据接口
  97. interface EmployeeCalendarData {
  98. currentMonth: Date;
  99. days: EmployeeCalendarDay[];
  100. }
  101. // 日历日期数据
  102. interface EmployeeCalendarDay {
  103. date: Date;
  104. projectCount: number; // 当天项目数量
  105. projects: Array<{ id: string; name: string; deadline?: Date }>; // 项目列表
  106. isToday: boolean;
  107. isCurrentMonth: boolean;
  108. }
  109. declare const echarts: any;
  110. @Component({
  111. selector: 'app-dashboard',
  112. standalone: true,
  113. imports: [CommonModule, FormsModule, RouterModule],
  114. templateUrl: './dashboard.html',
  115. styleUrl: './dashboard.scss'
  116. })
  117. export class Dashboard implements OnInit, OnDestroy {
  118. // 暴露 Array 给模板使用
  119. Array = Array;
  120. projects: Project[] = [];
  121. filteredProjects: Project[] = [];
  122. todoTasks: TodoTask[] = [];
  123. urgentPinnedProjects: Project[] = [];
  124. showAlert: boolean = false;
  125. selectedProjectId: string = '';
  126. // 新增:从问题板块加载的待办任务
  127. todoTasksFromIssues: TodoTaskFromIssue[] = [];
  128. loadingTodoTasks: boolean = false;
  129. todoTaskError: string = '';
  130. private todoTaskRefreshTimer: any;
  131. // 新增:当前用户信息
  132. currentUser = {
  133. name: '组长',
  134. avatar: "data:image/svg+xml,%3Csvg width='40' height='40' xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='100%25' height='100%25' fill='%23CCFFCC'/%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'%3E组长%3C/text%3E%3C/svg%3E",
  135. roleName: '组长'
  136. };
  137. currentDate = new Date();
  138. // 真实设计师数据(从fmode-ng获取)
  139. realDesigners: any[] = [];
  140. // 设计师工作量映射(从 ProjectTeam 表)
  141. designerWorkloadMap: Map<string, any[]> = new Map(); // designerId/name -> projects[]
  142. // 智能推荐相关
  143. showSmartMatch: boolean = false;
  144. selectedProject: any = null;
  145. recommendations: any[] = [];
  146. // 新增:关键词搜索
  147. searchTerm: string = '';
  148. searchSuggestions: Project[] = [];
  149. showSuggestions: boolean = false;
  150. private hideSuggestionsTimer: any;
  151. // 搜索性能与交互控制
  152. private searchDebounceTimer: any;
  153. private readonly SEARCH_DEBOUNCE_MS = 200; // 防抖时长(毫秒)
  154. private readonly MIN_SEARCH_LEN = 2; // 最小触发建议长度
  155. private readonly MAX_SUGGESTIONS = 8; // 建议最大条数
  156. private isSearchFocused: boolean = false; // 是否处于输入聚焦态
  157. // 新增:临期项目与筛选状态
  158. selectedType: 'all' | 'soft' | 'hard' = 'all';
  159. selectedUrgency: 'all' | 'high' | 'medium' | 'low' = 'all';
  160. selectedStatus: 'all' | 'progress' | 'completed' | 'overdue' | 'pendingApproval' | 'pendingAssignment' | 'dueSoon' = 'all';
  161. selectedDesigner: string = 'all';
  162. selectedMemberType: 'all' | 'vip' | 'normal' = 'all';
  163. // 新增:时间窗筛选
  164. selectedTimeWindow: 'all' | 'today' | 'threeDays' | 'sevenDays' = 'all';
  165. designers: string[] = [];
  166. // 新增:四大板块筛选
  167. selectedCorePhase: 'all' | 'order' | 'requirements' | 'delivery' | 'aftercare' = 'all';
  168. // 设计师画像(从fmode-ng动态获取,保留此字段作为兼容)
  169. designerProfiles: any[] = [];
  170. // 10个项目阶段
  171. projectStages: ProjectStage[] = [
  172. { id: 'pendingApproval', name: '待确认', order: 1 },
  173. { id: 'pendingAssignment', name: '待分配', order: 2 },
  174. { id: 'requirement', name: '需求沟通', order: 3 },
  175. { id: 'planning', name: '方案规划', order: 4 },
  176. { id: 'modeling', name: '建模阶段', order: 5 },
  177. { id: 'rendering', name: '渲染阶段', order: 6 },
  178. { id: 'postProduction', name: '后期处理', order: 7 },
  179. { id: 'review', name: '方案评审', order: 8 },
  180. { id: 'revision', name: '方案修改', order: 9 },
  181. { id: 'delivery', name: '交付完成', order: 10 }
  182. ];
  183. // 5大核心阶段(聚合展示)
  184. corePhases: ProjectStage[] = [
  185. { id: 'order', name: '订单分配', order: 1 }, // 待确认、待分配
  186. { id: 'requirements', name: '确认需求', order: 2 }, // 需求沟通、方案规划
  187. { id: 'delivery', name: '交付执行', order: 3 }, // 建模、渲染、后期/评审/修改
  188. { id: 'aftercare', name: '售后', order: 4 } // 交付完成 → 售后
  189. ];
  190. // 甘特视图开关与实例引用
  191. showGanttView: boolean = false;
  192. private ganttChart: any | null = null;
  193. @ViewChild('ganttChartRef', { static: false }) ganttChartRef!: ElementRef<HTMLDivElement>;
  194. // 工作负载甘特图引用
  195. @ViewChild('workloadGanttContainer', { static: false }) workloadGanttContainer!: ElementRef<HTMLDivElement>;
  196. private workloadGanttChart: any | null = null;
  197. workloadGanttScale: 'week' | 'month' = 'week';
  198. // 甘特时间尺度:仅周/月
  199. ganttScale: 'day' | 'week' | 'month' = 'week';
  200. // 新增:甘特模式(项目 / 设计师排班)
  201. ganttMode: 'project' | 'designer' = 'project';
  202. // 个人详情面板相关属性
  203. showEmployeeDetailPanel: boolean = false;
  204. selectedEmployeeDetail: EmployeeDetail | null = null;
  205. refreshingSurvey: boolean = false; // 新增:刷新问卷状态
  206. showFullSurvey: boolean = false; // 新增:是否显示完整问卷
  207. // 日历项目列表弹窗
  208. showCalendarProjectList: boolean = false;
  209. selectedDayProjects: Array<{ id: string; name: string; deadline?: Date }> = [];
  210. selectedDate: Date | null = null;
  211. // 当前员工日历相关数据(用于切换月份)
  212. private currentEmployeeName: string = '';
  213. private currentEmployeeProjects: any[] = [];
  214. // 员工请假数据(模拟数据)
  215. private leaveRecords: LeaveRecord[] = [
  216. { id: '1', employeeName: '张三', date: '2024-01-20', isLeave: true, leaveType: 'personal', reason: '事假' },
  217. { id: '2', employeeName: '张三', date: '2024-01-21', isLeave: false },
  218. { id: '3', employeeName: '张三', date: '2024-01-22', isLeave: false },
  219. { id: '4', employeeName: '张三', date: '2024-01-23', isLeave: false },
  220. { id: '5', employeeName: '张三', date: '2024-01-24', isLeave: false },
  221. { id: '6', employeeName: '张三', date: '2024-01-25', isLeave: false },
  222. { id: '7', employeeName: '张三', date: '2024-01-26', isLeave: false },
  223. { id: '8', employeeName: '李四', date: '2024-01-20', isLeave: false },
  224. { id: '9', employeeName: '李四', date: '2024-01-21', isLeave: true, leaveType: 'sick', reason: '病假' },
  225. { id: '10', employeeName: '李四', date: '2024-01-22', isLeave: true, leaveType: 'sick', reason: '病假' },
  226. { id: '11', employeeName: '李四', date: '2024-01-23', isLeave: false },
  227. { id: '12', employeeName: '李四', date: '2024-01-24', isLeave: false },
  228. { id: '13', employeeName: '李四', date: '2024-01-25', isLeave: false },
  229. { id: '14', employeeName: '李四', date: '2024-01-26', isLeave: false },
  230. { id: '15', employeeName: '王五', date: '2024-01-20', isLeave: false },
  231. { id: '16', employeeName: '王五', date: '2024-01-21', isLeave: false },
  232. { id: '17', employeeName: '王五', date: '2024-01-22', isLeave: false },
  233. { id: '18', employeeName: '王五', date: '2024-01-23', isLeave: true, leaveType: 'annual', reason: '年假' },
  234. { id: '19', employeeName: '王五', date: '2024-01-24', isLeave: false },
  235. { id: '20', employeeName: '王五', date: '2024-01-25', isLeave: false },
  236. { id: '21', employeeName: '王五', date: '2024-01-26', isLeave: false },
  237. { id: '22', employeeName: '赵六', date: '2024-01-20', isLeave: false },
  238. { id: '23', employeeName: '赵六', date: '2024-01-21', isLeave: false },
  239. { id: '24', employeeName: '赵六', date: '2024-01-22', isLeave: false },
  240. { id: '25', employeeName: '赵六', date: '2024-01-23', isLeave: false },
  241. { id: '26', employeeName: '赵六', date: '2024-01-24', isLeave: false },
  242. { id: '27', employeeName: '赵六', date: '2024-01-25', isLeave: false },
  243. { id: '28', employeeName: '赵六', date: '2024-01-26', isLeave: false }
  244. ];
  245. constructor(
  246. private projectService: ProjectService,
  247. private router: Router,
  248. private designerService: DesignerService,
  249. private issueService: ProjectIssueService
  250. ) {}
  251. async ngOnInit(): Promise<void> {
  252. // 新增:加载用户Profile信息
  253. await this.loadUserProfile();
  254. await this.loadProjects();
  255. await this.loadDesigners();
  256. this.loadTodoTasks();
  257. // 首次微任务后尝试初始化一次,确保容器已渲染
  258. setTimeout(() => this.updateWorkloadGantt(), 0);
  259. // 新增:加载待办任务(从问题板块)
  260. await this.loadTodoTasksFromIssues();
  261. // 启动自动刷新
  262. this.startAutoRefresh();
  263. }
  264. /**
  265. * 从fmode-ng加载真实设计师数据
  266. */
  267. async loadDesigners(): Promise<void> {
  268. try {
  269. this.realDesigners = await this.designerService.getDesigners();
  270. // 更新设计师列表(用于筛选下拉框)
  271. this.designers = this.realDesigners.map(d => d.name);
  272. // 同时更新designerProfiles以保持兼容性
  273. this.designerProfiles = this.realDesigners.map(d => ({
  274. id: d.id,
  275. name: d.name,
  276. skills: d.tags.expertise.styles || [],
  277. workload: 0, // 后续动态计算
  278. avgRating: d.tags.history.avgRating || 0,
  279. experience: 0 // 暂无此字段
  280. }));
  281. // 加载设计师的实际工作量
  282. await this.loadDesignerWorkload();
  283. } catch (error) {
  284. console.error('加载设计师数据失败:', error);
  285. }
  286. }
  287. /**
  288. * 🔧 从 ProjectTeam 表加载每个设计师的实际工作量
  289. */
  290. async loadDesignerWorkload(): Promise<void> {
  291. try {
  292. const Parse = await import('fmode-ng/parse').then(m => m.FmodeParse.with('nova'));
  293. // 查询所有 ProjectTeam 记录
  294. const cid = localStorage.getItem('company') || 'cDL6R1hgSi';
  295. // 先查询当前公司的所有项目
  296. const projectQuery = new Parse.Query('Project');
  297. projectQuery.equalTo('company', cid);
  298. projectQuery.notEqualTo('isDeleted', true);
  299. // 查询当前公司项目的 ProjectTeam
  300. const teamQuery = new Parse.Query('ProjectTeam');
  301. teamQuery.matchesQuery('project', projectQuery);
  302. teamQuery.notEqualTo('isDeleted', true);
  303. teamQuery.include('project');
  304. teamQuery.include('profile');
  305. teamQuery.limit(1000);
  306. const teamRecords = await teamQuery.find();
  307. // 如果 ProjectTeam 表为空,使用降级方案
  308. if (teamRecords.length === 0) {
  309. await this.loadDesignerWorkloadFromProjects();
  310. return;
  311. }
  312. // 构建设计师工作量映射
  313. this.designerWorkloadMap.clear();
  314. teamRecords.forEach((record: any) => {
  315. const profile = record.get('profile');
  316. const project = record.get('project');
  317. if (!profile || !project) {
  318. return;
  319. }
  320. const profileId = profile.id;
  321. const profileName = profile.get('name') || profile.get('user')?.get?.('name') || `设计师-${profileId.slice(-4)}`;
  322. // 提取项目信息
  323. // 优先获取各个日期字段
  324. const createdAtValue = project.get('createdAt');
  325. const updatedAtValue = project.get('updatedAt');
  326. const deadlineValue = project.get('deadline');
  327. const deliveryDateValue = project.get('deliveryDate');
  328. const expectedDeliveryDateValue = project.get('expectedDeliveryDate');
  329. // 🔧 如果 get() 方法都返回假值,尝试从 createdAt/updatedAt 属性直接获取
  330. // Parse 对象的 createdAt/updatedAt 是内置属性
  331. let finalCreatedAt = createdAtValue || updatedAtValue;
  332. if (!finalCreatedAt && project.createdAt) {
  333. finalCreatedAt = project.createdAt; // Parse 内置属性
  334. }
  335. if (!finalCreatedAt && project.updatedAt) {
  336. finalCreatedAt = project.updatedAt; // Parse 内置属性
  337. }
  338. const projectData = {
  339. id: project.id,
  340. name: project.get('title') || '未命名项目',
  341. status: project.get('status') || '进行中',
  342. currentStage: project.get('currentStage') || '未知阶段',
  343. deadline: deadlineValue || deliveryDateValue || expectedDeliveryDateValue,
  344. createdAt: finalCreatedAt,
  345. designerName: profileName
  346. };
  347. // 添加到映射 (by ID)
  348. if (!this.designerWorkloadMap.has(profileId)) {
  349. this.designerWorkloadMap.set(profileId, []);
  350. }
  351. this.designerWorkloadMap.get(profileId)!.push(projectData);
  352. // 同时建立 name -> projects 的映射(用于甘特图)
  353. if (!this.designerWorkloadMap.has(profileName)) {
  354. this.designerWorkloadMap.set(profileName, []);
  355. }
  356. this.designerWorkloadMap.get(profileName)!.push(projectData);
  357. });
  358. } catch (error) {
  359. console.error('加载设计师工作量失败:', error);
  360. }
  361. }
  362. /**
  363. * 🔧 降级方案:从 Project.assignee 统计工作量
  364. * 当 ProjectTeam 表为空时使用
  365. */
  366. async loadDesignerWorkloadFromProjects(): Promise<void> {
  367. try {
  368. const Parse = await import('fmode-ng/parse').then(m => m.FmodeParse.with('nova'));
  369. const cid = localStorage.getItem('company') || 'cDL6R1hgSi';
  370. // 查询所有项目
  371. const projectQuery = new Parse.Query('Project');
  372. projectQuery.equalTo('company', cid);
  373. projectQuery.equalTo('isDeleted', false);
  374. projectQuery.include('assignee');
  375. projectQuery.include('department');
  376. projectQuery.limit(1000);
  377. const projects = await projectQuery.find();
  378. // 构建设计师工作量映射
  379. this.designerWorkloadMap.clear();
  380. projects.forEach((project: any) => {
  381. const assignee = project.get('assignee');
  382. if (!assignee) return;
  383. // 只统计组员角色的项目
  384. const assigneeRole = assignee.get('roleName');
  385. if (assigneeRole !== '组员') {
  386. return;
  387. }
  388. const assigneeName = assignee.get('name') || assignee.get('user')?.get?.('name') || `设计师-${assignee.id.slice(-4)}`;
  389. // 提取项目信息
  390. // 优先获取各个日期字段
  391. const createdAtValue = project.get('createdAt');
  392. const updatedAtValue = project.get('updatedAt');
  393. const deadlineValue = project.get('deadline');
  394. const deliveryDateValue = project.get('deliveryDate');
  395. const expectedDeliveryDateValue = project.get('expectedDeliveryDate');
  396. // 🔧 如果 get() 方法都返回假值,尝试从 createdAt/updatedAt 属性直接获取
  397. let finalCreatedAt = createdAtValue || updatedAtValue;
  398. if (!finalCreatedAt && project.createdAt) {
  399. finalCreatedAt = project.createdAt;
  400. }
  401. if (!finalCreatedAt && project.updatedAt) {
  402. finalCreatedAt = project.updatedAt;
  403. }
  404. const projectData = {
  405. id: project.id,
  406. name: project.get('title') || '未命名项目',
  407. status: project.get('status') || '进行中',
  408. currentStage: project.get('currentStage') || '未知阶段',
  409. deadline: deadlineValue || deliveryDateValue || expectedDeliveryDateValue,
  410. createdAt: finalCreatedAt,
  411. designerName: assigneeName
  412. };
  413. // 添加到映射
  414. if (!this.designerWorkloadMap.has(assigneeName)) {
  415. this.designerWorkloadMap.set(assigneeName, []);
  416. }
  417. this.designerWorkloadMap.get(assigneeName)!.push(projectData);
  418. });
  419. } catch (error) {
  420. console.error('[降级方案] 加载工作量失败:', error);
  421. }
  422. }
  423. /**
  424. * 从fmode-ng加载真实项目数据
  425. */
  426. async loadProjects(): Promise<void> {
  427. try {
  428. const realProjects = await this.designerService.getProjects();
  429. // 如果有真实数据,使用真实数据
  430. if (realProjects && realProjects.length > 0) {
  431. this.projects = realProjects;
  432. } else {
  433. // 如果没有真实数据,使用模拟数据
  434. this.projects = this.getMockProjects();
  435. }
  436. } catch (error) {
  437. console.error('加载项目数据失败:', error);
  438. this.projects = this.getMockProjects();
  439. }
  440. // 应用筛选
  441. this.applyFilters();
  442. }
  443. /**
  444. * 构建搜索索引(如果需要)
  445. */
  446. private buildSearchIndexes(): void {
  447. this.projects.forEach(p => {
  448. if (!p.searchIndex) {
  449. p.searchIndex = `${p.name}|${p.designerName}`.toLowerCase();
  450. }
  451. });
  452. }
  453. /**
  454. * 模拟项目数据(作为备用)
  455. */
  456. private getMockProjects(): Project[] {
  457. return [
  458. {
  459. id: 'proj-001',
  460. name: '现代风格客厅设计',
  461. type: 'soft',
  462. memberType: 'vip',
  463. designerName: '张三',
  464. status: '进行中',
  465. expectedEndDate: new Date(2023, 9, 15),
  466. deadline: new Date(2023, 9, 15),
  467. isOverdue: true,
  468. overdueDays: 2,
  469. dueSoon: false,
  470. urgency: 'high',
  471. currentStage: 'rendering',
  472. phases: [
  473. { name: '建模', percentage: 15, startPercentage: 0, isCompleted: true, isCurrent: false },
  474. { name: '渲染', percentage: 20, startPercentage: 15, isCompleted: false, isCurrent: true },
  475. { name: '后期', percentage: 15, startPercentage: 35, isCompleted: false, isCurrent: false },
  476. { name: '交付', percentage: 50, startPercentage: 50, isCompleted: false, isCurrent: false }
  477. ]
  478. },
  479. {
  480. id: 'proj-002',
  481. name: '北欧风格卧室设计',
  482. type: 'soft',
  483. memberType: 'normal',
  484. designerName: '李四',
  485. status: '进行中',
  486. expectedEndDate: new Date(2023, 9, 20),
  487. deadline: new Date(2023, 9, 20),
  488. isOverdue: false,
  489. overdueDays: 0,
  490. dueSoon: false,
  491. urgency: 'medium',
  492. currentStage: 'postProduction',
  493. phases: [
  494. { name: '建模', percentage: 15, startPercentage: 0, isCompleted: true, isCurrent: false },
  495. { name: '渲染', percentage: 20, startPercentage: 15, isCompleted: true, isCurrent: false },
  496. { name: '后期', percentage: 15, startPercentage: 35, isCompleted: false, isCurrent: true },
  497. { name: '交付', percentage: 50, startPercentage: 50, isCompleted: false, isCurrent: false }
  498. ]
  499. },
  500. {
  501. id: 'proj-003',
  502. name: '新中式餐厅设计',
  503. type: 'hard',
  504. memberType: 'normal',
  505. designerName: '王五',
  506. status: '进行中',
  507. expectedEndDate: new Date(2023, 9, 25),
  508. deadline: new Date(2023, 9, 25),
  509. isOverdue: false,
  510. overdueDays: 0,
  511. dueSoon: false,
  512. urgency: 'low',
  513. currentStage: 'modeling',
  514. phases: [
  515. { name: '建模', percentage: 15, startPercentage: 0, isCompleted: false, isCurrent: true },
  516. { name: '渲染', percentage: 20, startPercentage: 15, isCompleted: false, isCurrent: false },
  517. { name: '后期', percentage: 15, startPercentage: 35, isCompleted: false, isCurrent: false },
  518. { name: '交付', percentage: 50, startPercentage: 50, isCompleted: false, isCurrent: false }
  519. ]
  520. },
  521. {
  522. id: 'proj-004',
  523. name: '工业风办公室设计',
  524. type: 'hard',
  525. memberType: 'normal',
  526. designerName: '赵六',
  527. status: '进行中',
  528. expectedEndDate: new Date(2023, 9, 10),
  529. deadline: new Date(2023, 9, 10),
  530. isOverdue: true,
  531. overdueDays: 7,
  532. dueSoon: false,
  533. urgency: 'high',
  534. currentStage: 'review',
  535. phases: [
  536. { name: '建模', percentage: 15, startPercentage: 0, isCompleted: true, isCurrent: false },
  537. { name: '渲染', percentage: 20, startPercentage: 15, isCompleted: true, isCurrent: false },
  538. { name: '后期', percentage: 15, startPercentage: 35, isCompleted: false, isCurrent: false },
  539. { name: '交付', percentage: 50, startPercentage: 50, isCompleted: false, isCurrent: false }
  540. ]
  541. },
  542. // 添加更多不同阶段的项目
  543. {
  544. id: 'proj-005',
  545. name: '现代简约厨房设计',
  546. type: 'soft',
  547. memberType: 'normal',
  548. designerName: '',
  549. status: '待分配',
  550. expectedEndDate: new Date(2023, 10, 5),
  551. deadline: new Date(2023, 10, 5),
  552. isOverdue: false,
  553. overdueDays: 0,
  554. dueSoon: false,
  555. urgency: 'medium',
  556. currentStage: 'pendingAssignment',
  557. phases: []
  558. },
  559. {
  560. id: 'proj-006',
  561. name: '日式风格书房设计',
  562. type: 'hard',
  563. memberType: 'normal',
  564. designerName: '',
  565. status: '待确认',
  566. expectedEndDate: new Date(2023, 10, 10),
  567. deadline: new Date(2023, 10, 10),
  568. isOverdue: false,
  569. overdueDays: 0,
  570. dueSoon: false,
  571. urgency: 'low',
  572. currentStage: 'pendingApproval',
  573. phases: []
  574. },
  575. {
  576. id: 'proj-007',
  577. name: '轻奢风格浴室设计',
  578. type: 'soft',
  579. memberType: 'normal',
  580. designerName: '钱七',
  581. status: '已完成',
  582. expectedEndDate: new Date(2023, 9, 5),
  583. deadline: new Date(2023, 9, 5),
  584. isOverdue: false,
  585. overdueDays: 0,
  586. dueSoon: false,
  587. urgency: 'medium',
  588. currentStage: 'delivery',
  589. phases: []
  590. }
  591. ];
  592. // ===== 追加生成示例数据:保证总量达到100条 =====
  593. const stageIds = this.projectStages.map(s => s.id);
  594. const designers = ['张三','李四','王五','赵六','孙七','周八','吴九','陈十'];
  595. const statusMap: Record<string, string> = {
  596. pendingApproval: '待确认',
  597. pendingAssignment: '待分配',
  598. requirement: '进行中',
  599. planning: '进行中',
  600. modeling: '进行中',
  601. rendering: '进行中',
  602. postProduction: '进行中',
  603. review: '进行中',
  604. revision: '进行中',
  605. delivery: '已完成'
  606. };
  607. // 为有项目的设计师分配项目
  608. const busyDesigners = ['张三', '王五', '吴九']; // 高负荷设计师
  609. const moderateDesigners = ['孙七']; // 中等负荷设计师
  610. const idleDesigners = ['李四', '赵六', '周八', '陈十']; // 空闲设计师
  611. // 为忙碌的设计师分配更多项目
  612. for (let i = 8; i <= 30; i++) {
  613. const designerIndex = (i - 8) % busyDesigners.length;
  614. const designerName = busyDesigners[designerIndex];
  615. const stageIndex = (i - 1) % 7 + 3; // 主要在进行中的阶段
  616. const currentStage = stageIds[stageIndex];
  617. const type: 'soft' | 'hard' = i % 2 === 0 ? 'soft' : 'hard';
  618. const urgency: 'high' | 'medium' | 'low' = i % 4 === 0 ? 'high' : (i % 3 === 0 ? 'medium' : 'low');
  619. const isOverdue = i % 8 === 0;
  620. const overdueDays = isOverdue ? (i % 5) + 1 : 0;
  621. const status = statusMap[currentStage] || '进行中';
  622. const expectedEndDate = new Date();
  623. const daysOffset = isOverdue ? -(overdueDays + (i % 3)) : ((i % 15) + 5);
  624. expectedEndDate.setDate(expectedEndDate.getDate() + daysOffset);
  625. const daysToDeadline = Math.ceil((expectedEndDate.getTime() - Date.now()) / (1000 * 60 * 60 * 24));
  626. const dueSoon = !isOverdue && daysToDeadline >= 0 && daysToDeadline <= 3;
  627. const memberType: 'vip' | 'normal' = i % 5 === 0 ? 'vip' : 'normal';
  628. this.projects.push({
  629. id: `proj-${String(i).padStart(3, '0')}`,
  630. name: `${designerName}负责的${type === 'soft' ? '软装' : '硬装'}项目 ${i}`,
  631. type,
  632. memberType,
  633. designerName,
  634. status,
  635. expectedEndDate,
  636. deadline: expectedEndDate,
  637. isOverdue,
  638. overdueDays,
  639. dueSoon,
  640. urgency,
  641. currentStage,
  642. phases: []
  643. });
  644. }
  645. // 为中等负荷设计师分配少量项目
  646. for (let i = 31; i <= 35; i++) {
  647. const designerName = moderateDesigners[0];
  648. const stageIndex = (i - 1) % 5 + 4; // 中间阶段
  649. const currentStage = stageIds[stageIndex];
  650. const type: 'soft' | 'hard' = i % 2 === 0 ? 'soft' : 'hard';
  651. const urgency: 'high' | 'medium' | 'low' = 'medium';
  652. const status = statusMap[currentStage] || '进行中';
  653. const expectedEndDate = new Date();
  654. expectedEndDate.setDate(expectedEndDate.getDate() + (i % 10) + 7);
  655. const memberType: 'vip' | 'normal' = 'normal';
  656. this.projects.push({
  657. id: `proj-${String(i).padStart(3, '0')}`,
  658. name: `${designerName}负责的${type === 'soft' ? '软装' : '硬装'}项目 ${i}`,
  659. type,
  660. memberType,
  661. designerName,
  662. status,
  663. expectedEndDate,
  664. deadline: expectedEndDate,
  665. isOverdue: false,
  666. overdueDays: 0,
  667. dueSoon: false,
  668. urgency,
  669. currentStage,
  670. phases: []
  671. });
  672. }
  673. // 空闲设计师不分配项目,或只分配很少的已完成项目
  674. for (let i = 36; i <= 40; i++) {
  675. const designerIndex = (i - 36) % idleDesigners.length;
  676. const designerName = idleDesigners[designerIndex];
  677. const currentStage = 'delivery'; // 已完成的项目
  678. const type: 'soft' | 'hard' = i % 2 === 0 ? 'soft' : 'hard';
  679. const urgency: 'high' | 'medium' | 'low' = 'low';
  680. const status = '已完成';
  681. const expectedEndDate = new Date();
  682. expectedEndDate.setDate(expectedEndDate.getDate() - (i % 10) - 5); // 过去的日期
  683. const memberType: 'vip' | 'normal' = 'normal';
  684. this.projects.push({
  685. id: `proj-${String(i).padStart(3, '0')}`,
  686. name: `${designerName}已完成的${type === 'soft' ? '软装' : '硬装'}项目 ${i}`,
  687. type,
  688. memberType,
  689. designerName,
  690. status,
  691. expectedEndDate,
  692. deadline: expectedEndDate,
  693. isOverdue: false,
  694. overdueDays: 0,
  695. dueSoon: false,
  696. urgency,
  697. currentStage,
  698. phases: []
  699. });
  700. }
  701. // ===== 示例数据生成结束 =====
  702. // 统一补齐真实时间字段(deadline/createdAt),以真实字段贯通筛选与甘特
  703. const DAY = 24 * 60 * 60 * 1000;
  704. this.projects = this.projects.map(p => {
  705. const deadline = p.deadline || p.expectedEndDate;
  706. const baseDays = p.type === 'hard' ? 30 : 14;
  707. const createdAt = p.createdAt || new Date(new Date(deadline).getTime() - baseDays * DAY);
  708. return { ...p, deadline, createdAt } as Project;
  709. });
  710. // 筛选结果初始化为全部项目
  711. this.filteredProjects = [...this.projects];
  712. // 供筛选用的设计师列表
  713. this.designers = Array.from(new Set(this.projects.map(p => p.designerName).filter(n => !!n)));
  714. // 显示超期提醒(使用 getter)
  715. if (this.overdueProjects.length > 0) {
  716. this.showAlert = true;
  717. }
  718. }
  719. loadTodoTasks(): void {
  720. // 模拟待办任务数据
  721. this.todoTasks = [
  722. {
  723. id: 'todo-001',
  724. title: '待评审效果图',
  725. description: '现代风格客厅设计项目需要进行效果图评审',
  726. deadline: new Date(2023, 9, 18, 15, 0),
  727. priority: 'high',
  728. type: 'review',
  729. targetId: 'proj-001'
  730. },
  731. {
  732. id: 'todo-002',
  733. title: '待分配项目',
  734. description: '新中式厨房设计项目需要分配给合适的设计师',
  735. deadline: new Date(2023, 9, 19, 10, 0),
  736. priority: 'high',
  737. type: 'assign',
  738. targetId: 'proj-new'
  739. },
  740. {
  741. id: 'todo-003',
  742. title: '待确认绩效',
  743. description: '9月份团队绩效需要进行审核确认',
  744. deadline: new Date(2023, 9, 22, 18, 0),
  745. priority: 'medium',
  746. type: 'performance',
  747. targetId: 'sep-2023'
  748. },
  749. {
  750. id: 'todo-004',
  751. title: '待处理客户反馈',
  752. description: '北欧风格卧室设计项目有客户反馈需要处理',
  753. deadline: new Date(2023, 9, 20, 14, 0),
  754. priority: 'medium',
  755. type: 'review',
  756. targetId: 'proj-002'
  757. },
  758. {
  759. id: 'todo-005',
  760. title: '团队会议',
  761. description: '每周团队进度沟通会议',
  762. deadline: new Date(2023, 9, 18, 10, 0),
  763. priority: 'low',
  764. type: 'performance',
  765. targetId: 'weekly-meeting'
  766. }
  767. ];
  768. // 按优先级排序:紧急且重要 > 重要不紧急 > 紧急不重要
  769. this.todoTasks.sort((a, b) => {
  770. const priorityOrder = {
  771. 'high': 3,
  772. 'medium': 2,
  773. 'low': 1
  774. };
  775. return priorityOrder[b.priority] - priorityOrder[a.priority];
  776. });
  777. }
  778. // 筛选项目类型
  779. filterProjects(event: Event): void {
  780. const target = event.target as HTMLSelectElement;
  781. this.selectedType = (target && target.value ? target.value : 'all') as any;
  782. this.applyFilters();
  783. }
  784. // 筛选紧急程度
  785. filterByUrgency(event: Event): void {
  786. const target = event.target as HTMLSelectElement;
  787. this.selectedUrgency = (target && target.value ? target.value : 'all') as any;
  788. this.applyFilters();
  789. }
  790. // 筛选项目状态
  791. filterByStatus(status: string): void {
  792. // 点击同一状态时,切换回“全部”,以便恢复全量项目列表
  793. const next = (this.selectedStatus === status) ? 'all' : (status && status.length ? status : 'all');
  794. this.selectedStatus = next as any;
  795. this.applyFilters();
  796. }
  797. // 处理状态筛选下拉框变化
  798. onStatusChange(event: Event): void {
  799. const target = event.target as HTMLSelectElement;
  800. this.selectedStatus = (target && target.value ? target.value : 'all') as any;
  801. this.applyFilters();
  802. }
  803. // 新增:设计师筛选下拉事件处理
  804. onDesignerChange(event: Event): void {
  805. const target = event.target as HTMLSelectElement;
  806. this.selectedDesigner = (target && target.value ? target.value : 'all');
  807. this.applyFilters();
  808. }
  809. // 新增:会员类型筛选下拉事件处理
  810. onMemberTypeChange(event: Event): void {
  811. const select = event.target as HTMLSelectElement;
  812. this.selectedMemberType = select.value as any;
  813. this.applyFilters();
  814. }
  815. // 新增:四大板块改变
  816. onCorePhaseChange(event: Event): void {
  817. const select = event.target as HTMLSelectElement;
  818. this.selectedCorePhase = select.value as any;
  819. this.applyFilters();
  820. }
  821. // 时间窗快捷筛选(供UI按钮触发)
  822. filterByTimeWindow(timeWindow: 'all' | 'today' | 'threeDays' | 'sevenDays'): void {
  823. this.selectedTimeWindow = timeWindow;
  824. this.applyFilters();
  825. }
  826. // 新增:搜索输入变化
  827. onSearchChange(): void {
  828. if (this.searchDebounceTimer) clearTimeout(this.searchDebounceTimer);
  829. this.searchDebounceTimer = setTimeout(() => {
  830. this.updateSearchSuggestions();
  831. this.applyFilters();
  832. }, this.SEARCH_DEBOUNCE_MS);
  833. }
  834. // 新增:搜索框聚焦/失焦控制建议显隐
  835. onSearchFocus(): void {
  836. if (this.hideSuggestionsTimer) clearTimeout(this.hideSuggestionsTimer);
  837. this.isSearchFocused = true;
  838. this.updateSearchSuggestions();
  839. }
  840. onSearchBlur(): void {
  841. // 延迟隐藏以允许选择项的 mousedown 触发
  842. this.isSearchFocused = false;
  843. this.hideSuggestionsTimer = setTimeout(() => {
  844. this.showSuggestions = false;
  845. }, 150);
  846. }
  847. // 新增:更新搜索建议(不叠加其它筛选,仅基于关键字)
  848. private updateSearchSuggestions(): void {
  849. const q = (this.searchTerm || '').trim().toLowerCase();
  850. if (q.length < this.MIN_SEARCH_LEN) {
  851. this.searchSuggestions = [];
  852. this.showSuggestions = false;
  853. return;
  854. }
  855. const scored = this.projects
  856. .filter(p => (p.searchIndex || `${(p.name || '')}|${(p.designerName || '')}`.toLowerCase()).includes(q))
  857. .map(p => {
  858. const dl = p.deadline || p.expectedEndDate;
  859. const dlTime = dl ? new Date(dl).getTime() : NaN;
  860. const daysToDl = Math.ceil(((isNaN(dlTime) ? 0 : dlTime) - Date.now()) / (1000 * 60 * 60 * 24));
  861. const urgencyScore = p.urgency === 'high' ? 3 : p.urgency === 'medium' ? 2 : 1;
  862. const overdueScore = p.isOverdue ? 10 : 0;
  863. const score = overdueScore + (4 - urgencyScore) * 2 - (isNaN(daysToDl) ? 0 : daysToDl);
  864. return { p, score };
  865. })
  866. .sort((a, b) => b.score - a.score)
  867. .slice(0, this.MAX_SUGGESTIONS)
  868. .map(x => x.p);
  869. this.searchSuggestions = scored;
  870. this.showSuggestions = this.isSearchFocused && this.searchSuggestions.length > 0;
  871. }
  872. // 新增:选择建议项
  873. selectSuggestion(project: Project): void {
  874. this.searchTerm = project.name;
  875. this.showSuggestions = false;
  876. this.viewProjectDetails(project.id);
  877. }
  878. // 统一筛选
  879. private applyFilters(): void {
  880. let result = [...this.projects];
  881. // 新增:关键词搜索(项目名 / 设计师名 / 含风格关键词的项目名)
  882. const q = (this.searchTerm || '').trim().toLowerCase();
  883. if (q) {
  884. result = result.filter(p => (p.searchIndex || `${(p.name || '')}|${(p.designerName || '')}`.toLowerCase()).includes(q));
  885. }
  886. // 类型筛选
  887. if (this.selectedType !== 'all') {
  888. result = result.filter(p => p.type === this.selectedType);
  889. }
  890. // 紧急程度筛选
  891. if (this.selectedUrgency !== 'all') {
  892. result = result.filter(p => p.urgency === this.selectedUrgency);
  893. }
  894. // 项目状态筛选
  895. if (this.selectedStatus !== 'all') {
  896. if (this.selectedStatus === 'overdue') {
  897. result = result.filter(p => p.isOverdue);
  898. } else if (this.selectedStatus === 'dueSoon') {
  899. result = result.filter(p => p.dueSoon && !p.isOverdue);
  900. } else if (this.selectedStatus === 'pendingApproval') {
  901. result = result.filter(p => p.currentStage === 'pendingApproval');
  902. } else if (this.selectedStatus === 'pendingAssignment') {
  903. result = result.filter(p => p.currentStage === 'pendingAssignment');
  904. } else if (this.selectedStatus === 'progress') {
  905. const progressStages = ['requirement','planning','modeling','rendering','postProduction','review','revision'];
  906. result = result.filter(p => progressStages.includes(p.currentStage));
  907. } else if (this.selectedStatus === 'completed') {
  908. result = result.filter(p => p.currentStage === 'delivery');
  909. }
  910. }
  911. // 新增:四大板块筛选
  912. if (this.selectedCorePhase !== 'all') {
  913. result = result.filter(p => this.mapStageToCorePhase(p.currentStage) === this.selectedCorePhase);
  914. }
  915. // 设计师筛选
  916. if (this.selectedDesigner !== 'all') {
  917. result = result.filter(p => p.designerName === this.selectedDesigner);
  918. }
  919. // 会员类型筛选
  920. if (this.selectedMemberType !== 'all') {
  921. result = result.filter(p => p.memberType === this.selectedMemberType);
  922. }
  923. // 新增:时间窗筛选
  924. if (this.selectedTimeWindow !== 'all') {
  925. const now = new Date();
  926. const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  927. result = result.filter(p => {
  928. const projectDeadline = new Date(p.deadline);
  929. const timeDiff = projectDeadline.getTime() - today.getTime();
  930. const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
  931. switch (this.selectedTimeWindow) {
  932. case 'today':
  933. return daysDiff <= 1 && daysDiff >= 0;
  934. case 'threeDays':
  935. return daysDiff <= 3 && daysDiff >= 0;
  936. case 'sevenDays':
  937. return daysDiff <= 7 && daysDiff >= 0;
  938. default:
  939. return true;
  940. }
  941. });
  942. }
  943. this.filteredProjects = result;
  944. // 新增:计算紧急任务固定区(超期 + 高紧急),与筛选联动
  945. this.urgentPinnedProjects = this.filteredProjects
  946. .filter(p => p.isOverdue && p.urgency === 'high')
  947. .sort((a, b) => (b.overdueDays - a.overdueDays) || a.name.localeCompare(b.name, 'zh-Hans-CN'));
  948. // 当显示甘特卡片时,同步刷新甘特图
  949. if (this.showGanttView) {
  950. this.updateGantt();
  951. }
  952. // 同步刷新工作负载甘特图
  953. setTimeout(() => this.updateWorkloadGantt(), 0);
  954. }
  955. /**
  956. * 计算项目加权值
  957. */
  958. calculateWorkloadWeight(project: any): number {
  959. return this.designerService.calculateProjectWeight(project);
  960. }
  961. /**
  962. * 获取设计师加权工作量
  963. */
  964. getDesignerWeightedWorkload(designerName: string): {
  965. weightedTotal: number;
  966. projectCount: number;
  967. overdueCount: number;
  968. loadRate: number;
  969. } {
  970. const designerProjects = this.filteredProjects.filter(p => p.designerName === designerName);
  971. const weightedTotal = designerProjects.reduce((sum, p) => sum + this.calculateWorkloadWeight(p), 0);
  972. const overdueCount = designerProjects.filter(p => p.isOverdue).length;
  973. // 从realDesigners获取设计师的单周处理量
  974. const designer = this.realDesigners.find(d => d.name === designerName);
  975. const weeklyCapacity = designer?.tags?.capacity?.weeklyProjects || 3;
  976. const loadRate = weeklyCapacity > 0 ? (weightedTotal / weeklyCapacity) * 100 : 0;
  977. return {
  978. weightedTotal,
  979. projectCount: designerProjects.length,
  980. overdueCount,
  981. loadRate
  982. };
  983. }
  984. /**
  985. * 工作量卡片数据(替代ECharts)
  986. */
  987. get designerWorkloadCards(): Array<{
  988. name: string;
  989. loadRate: number;
  990. weightedValue: number;
  991. projectCount: number;
  992. overdueCount: number;
  993. status: 'overload' | 'busy' | 'idle';
  994. }> {
  995. const designers = Array.from(new Set(this.filteredProjects.map(p => p.designerName).filter(n => n && n !== '未分配')));
  996. return designers.map(name => {
  997. const workload = this.getDesignerWeightedWorkload(name);
  998. let status: 'overload' | 'busy' | 'idle' = 'idle';
  999. if (workload.loadRate > 80) status = 'overload';
  1000. else if (workload.loadRate > 50) status = 'busy';
  1001. return {
  1002. name,
  1003. loadRate: workload.loadRate,
  1004. weightedValue: workload.weightedTotal,
  1005. projectCount: workload.projectCount,
  1006. overdueCount: workload.overdueCount,
  1007. status
  1008. };
  1009. }).sort((a, b) => b.loadRate - a.loadRate); // 按负载率降序
  1010. }
  1011. /**
  1012. * 获取超负荷设计师数量
  1013. */
  1014. get overloadedDesignersCount(): number {
  1015. return this.designerWorkloadCards.filter(d => d.status === 'overload').length;
  1016. }
  1017. /**
  1018. * 获取平均负载率
  1019. */
  1020. get averageWorkloadRate(): number {
  1021. const cards = this.designerWorkloadCards;
  1022. if (cards.length === 0) return 0;
  1023. const sum = cards.reduce((acc, card) => acc + card.loadRate, 0);
  1024. return sum / cards.length;
  1025. }
  1026. /**
  1027. * 获取预警汇总数据
  1028. */
  1029. getAlertSummary(): {
  1030. totalAlerts: number;
  1031. overdueHighRisk: Project[];
  1032. overloadedDesigners: any[];
  1033. dueSoonProjects: Project[];
  1034. } {
  1035. // 1. 超期高危项目(超期>=5天 或 高紧急度超期)
  1036. const overdueHighRisk = this.filteredProjects
  1037. .filter(p => p.isOverdue && (p.overdueDays >= 5 || p.urgency === 'high'))
  1038. .sort((a, b) => b.overdueDays - a.overdueDays)
  1039. .slice(0, 5);
  1040. // 2. 超负荷设计师
  1041. const overloadedDesigners = this.designerWorkloadCards
  1042. .filter(d => d.loadRate > 80)
  1043. .sort((a, b) => b.loadRate - a.loadRate)
  1044. .slice(0, 5);
  1045. // 3. 即将到期项目(1-2天内)
  1046. const now = new Date();
  1047. const dueSoonProjects = this.filteredProjects
  1048. .filter(p => {
  1049. if (p.isOverdue) return false;
  1050. const daysLeft = Math.ceil((p.deadline.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
  1051. return daysLeft >= 1 && daysLeft <= 2;
  1052. })
  1053. .sort((a, b) => a.deadline.getTime() - b.deadline.getTime())
  1054. .slice(0, 5);
  1055. const totalAlerts = overdueHighRisk.length + overloadedDesigners.length + dueSoonProjects.length;
  1056. return {
  1057. totalAlerts,
  1058. overdueHighRisk,
  1059. overloadedDesigners,
  1060. dueSoonProjects
  1061. };
  1062. }
  1063. /**
  1064. * 打开智能推荐弹窗
  1065. */
  1066. async openSmartMatch(project: any): Promise<void> {
  1067. this.selectedProject = project;
  1068. this.showSmartMatch = true;
  1069. try {
  1070. this.recommendations = await this.designerService.getRecommendedDesigners(project, this.realDesigners);
  1071. } catch (error) {
  1072. console.error('智能推荐失败:', error);
  1073. this.recommendations = [];
  1074. }
  1075. }
  1076. /**
  1077. * 关闭智能推荐弹窗
  1078. */
  1079. closeSmartMatch(): void {
  1080. this.showSmartMatch = false;
  1081. this.selectedProject = null;
  1082. this.recommendations = [];
  1083. }
  1084. /**
  1085. * 分配项目给设计师
  1086. */
  1087. async assignToDesigner(designerId: string): Promise<void> {
  1088. if (!this.selectedProject) return;
  1089. try {
  1090. const success = await this.designerService.assignProject(this.selectedProject.id, designerId);
  1091. if (success) {
  1092. this.closeSmartMatch();
  1093. await this.loadProjects(); // 重新加载项目数据
  1094. }
  1095. } catch (error) {
  1096. console.error('❌ 分配项目失败:', error);
  1097. window?.fmode?.alert('分配失败,请重试');
  1098. }
  1099. }
  1100. /**
  1101. * 获取紧急度标签
  1102. */
  1103. getUrgencyLabel(urgency: string): string {
  1104. const labels: Record<string, string> = {
  1105. 'high': '高',
  1106. 'medium': '中',
  1107. 'low': '低'
  1108. };
  1109. return labels[urgency] || '未知';
  1110. }
  1111. // 切换项目看板/负载日历(甘特)视图
  1112. toggleView(): void {
  1113. this.showGanttView = !this.showGanttView;
  1114. if (this.showGanttView) {
  1115. setTimeout(() => this.initOrUpdateGantt(), 0);
  1116. } else {
  1117. if (this.ganttChart) {
  1118. this.ganttChart.dispose();
  1119. this.ganttChart = null;
  1120. }
  1121. }
  1122. }
  1123. // 设置甘特时间尺度
  1124. setGanttScale(scale: 'day' | 'week' | 'month'): void {
  1125. if (this.ganttScale !== scale) {
  1126. this.ganttScale = scale;
  1127. this.updateGantt();
  1128. }
  1129. }
  1130. // 工作负载甘特图时间尺度切换
  1131. setWorkloadGanttScale(scale: 'week' | 'month'): void {
  1132. if (this.workloadGanttScale !== scale) {
  1133. this.workloadGanttScale = scale;
  1134. this.updateWorkloadGantt();
  1135. }
  1136. }
  1137. // 新增:切换甘特模式
  1138. setGanttMode(mode: 'project' | 'designer'): void {
  1139. if (this.ganttMode !== mode) {
  1140. this.ganttMode = mode;
  1141. this.updateGantt();
  1142. }
  1143. }
  1144. private initOrUpdateGantt(): void {
  1145. if (!this.ganttChartRef) return;
  1146. const el = this.ganttChartRef.nativeElement;
  1147. if (!this.ganttChart) {
  1148. this.ganttChart = echarts.init(el);
  1149. // 添加点击事件监听器
  1150. this.ganttChart.on('click', (params: any) => {
  1151. if (params.componentType === 'series' && params.seriesType === 'custom') {
  1152. // 获取点击的员工名称(从y轴类目数据中获取)
  1153. const yAxisData = this.ganttChart.getOption().yAxis[0].data;
  1154. if (yAxisData && params.dataIndex !== undefined) {
  1155. const employeeName = yAxisData[params.value[0]];
  1156. if (employeeName && employeeName !== '未分配') {
  1157. this.onEmployeeClick(employeeName);
  1158. }
  1159. }
  1160. }
  1161. });
  1162. window.addEventListener('resize', () => {
  1163. this.ganttChart && this.ganttChart.resize();
  1164. });
  1165. }
  1166. this.updateGantt();
  1167. }
  1168. private updateGantt(): void {
  1169. if (!this.ganttChart) return;
  1170. if (this.ganttMode === 'designer') {
  1171. this.updateGanttDesigner();
  1172. return;
  1173. }
  1174. // 按紧急程度从上到下排序(高->中->低),同级按到期时间升序
  1175. const urgencyRank: Record<'high'|'medium'|'low', number> = { high: 0, medium: 1, low: 2 };
  1176. const projects = [...this.filteredProjects]
  1177. .sort((a, b) => {
  1178. const u = urgencyRank[a.urgency] - urgencyRank[b.urgency];
  1179. if (u !== 0) return u;
  1180. // 二级排序:临期优先(到期更近)> 已分配人员 > VIP客户 > 其他
  1181. const endDiff = new Date(a.deadline).getTime() - new Date(b.deadline).getTime();
  1182. if (endDiff !== 0) return endDiff;
  1183. const assignedA = !!a.designerName;
  1184. const assignedB = !!b.designerName;
  1185. if (assignedA !== assignedB) return assignedA ? -1 : 1; // 已分配在前
  1186. const vipA = a.memberType === 'vip';
  1187. const vipB = b.memberType === 'vip';
  1188. if (vipA !== vipB) return vipA ? -1 : 1; // VIP在前
  1189. return a.name.localeCompare(b.name, 'zh-CN');
  1190. });
  1191. const categories = projects.map(p => p.name);
  1192. const urgencyMap: Record<string, 'high'|'medium'|'low'> = Object.fromEntries(projects.map(p => [p.name, p.urgency])) as any;
  1193. const colorByUrgency: Record<'high'|'medium'|'low', string> = {
  1194. high: '#ef4444',
  1195. medium: '#f59e0b',
  1196. low: '#22c55e'
  1197. } as const;
  1198. const DAY = 24 * 60 * 60 * 1000;
  1199. const data = projects.map((p, idx) => {
  1200. const end = new Date(p.deadline).getTime();
  1201. const baseDays = p.type === 'hard' ? 30 : 14;
  1202. const start = p.createdAt ? new Date(p.createdAt).getTime() : end - baseDays * DAY;
  1203. const color = colorByUrgency[p.urgency] || '#60a5fa';
  1204. return {
  1205. name: p.name,
  1206. value: [idx, start, end, p.designerName, p.urgency, p.memberType, p.currentStage],
  1207. itemStyle: { color }
  1208. };
  1209. });
  1210. // 计算时间范围(仅周/月)
  1211. const now = new Date();
  1212. const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  1213. const todayTs = today.getTime();
  1214. let xMin: number;
  1215. let xMax: number;
  1216. let xSplitNumber: number;
  1217. let xLabelFormatter: (value: number) => string;
  1218. if (this.ganttScale === 'week') {
  1219. const day = today.getDay(); // 0=周日
  1220. const diffToMonday = (day === 0 ? 6 : day - 1);
  1221. const startOfWeek = new Date(today.getTime() - diffToMonday * DAY);
  1222. const endOfWeek = new Date(startOfWeek.getTime() + 7 * DAY - 1);
  1223. xMin = startOfWeek.getTime();
  1224. xMax = endOfWeek.getTime();
  1225. xSplitNumber = 7;
  1226. const WEEK_LABELS = ['周日','周一','周二','周三','周四','周五','周六'];
  1227. xLabelFormatter = (val) => {
  1228. const d = new Date(val);
  1229. return WEEK_LABELS[d.getDay()];
  1230. };
  1231. } else { // month
  1232. const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
  1233. const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0, 23, 59, 59, 999);
  1234. xMin = startOfMonth.getTime();
  1235. xMax = endOfMonth.getTime();
  1236. xSplitNumber = 4;
  1237. xLabelFormatter = (val) => {
  1238. const d = new Date(val);
  1239. const weekOfMonth = Math.ceil(d.getDate() / 7);
  1240. return `第${weekOfMonth}周`;
  1241. };
  1242. }
  1243. // 计算默认可视区,并尝试保留上一次的滚动/缩放位置
  1244. const total = categories.length;
  1245. const visible = Math.min(total, 15); // 默认首屏展开15条
  1246. const defaultEndPercent = total > 0 ? Math.min(100, (visible / total) * 100) : 100;
  1247. const prevOpt: any = (this.ganttChart as any).getOption ? (this.ganttChart as any).getOption() : null;
  1248. const preservedStart = typeof prevOpt?.dataZoom?.[0]?.start === 'number' ? prevOpt.dataZoom[0].start : 0;
  1249. const preservedEnd = typeof prevOpt?.dataZoom?.[0]?.end === 'number' ? prevOpt.dataZoom[0].end : defaultEndPercent;
  1250. // 生成请假覆盖层数据
  1251. const leaveOverlayData = this.generateLeaveOverlayData(categories, xMin, xMax);
  1252. const option = {
  1253. backgroundColor: 'transparent',
  1254. tooltip: {
  1255. trigger: 'item',
  1256. formatter: (params: any) => {
  1257. const v = params.value;
  1258. const start = new Date(v[1]);
  1259. const end = new Date(v[2]);
  1260. return `项目:${params.name}<br/>负责人:${v[3] || '未分配'}<br/>阶段:${v[6]}<br/>起止:${start.toLocaleDateString()} ~ ${end.toLocaleDateString()}`;
  1261. }
  1262. },
  1263. grid: { left: 100, right: 64, top: 30, bottom: 30 },
  1264. xAxis: {
  1265. type: 'time',
  1266. min: xMin,
  1267. max: xMax,
  1268. splitNumber: xSplitNumber,
  1269. axisLine: { lineStyle: { color: '#e5e7eb' } },
  1270. axisLabel: { color: '#6b7280', formatter: (value: number) => xLabelFormatter(value) },
  1271. splitLine: { lineStyle: { color: '#f1f5f9' } }
  1272. },
  1273. yAxis: {
  1274. type: 'category',
  1275. data: categories,
  1276. inverse: true,
  1277. axisLabel: {
  1278. color: '#374151',
  1279. margin: 8,
  1280. formatter: (val: string) => {
  1281. const u = urgencyMap[val] || 'low';
  1282. const text = val.length > 16 ? val.slice(0, 16) + '…' : val;
  1283. return `{${u}Dot|●} ${text}`;
  1284. },
  1285. rich: {
  1286. highDot: { color: '#ef4444' },
  1287. mediumDot: { color: '#f59e0b' },
  1288. lowDot: { color: '#22c55e' }
  1289. }
  1290. },
  1291. axisTick: { show: false },
  1292. axisLine: { lineStyle: { color: '#e5e7eb' } }
  1293. },
  1294. dataZoom: [
  1295. { type: 'slider', yAxisIndex: 0, orient: 'vertical', right: 6, width: 14, start: preservedStart, end: preservedEnd, zoomLock: false },
  1296. { type: 'inside', yAxisIndex: 0, zoomOnMouseWheel: true, moveOnMouseMove: true, moveOnMouseWheel: true }
  1297. ],
  1298. series: [
  1299. // 项目条形图系列
  1300. {
  1301. type: 'custom',
  1302. name: '项目进度',
  1303. renderItem: (params: any, api: any) => {
  1304. const categoryIndex = api.value(0);
  1305. const start = api.coord([api.value(1), categoryIndex]);
  1306. const end = api.coord([api.value(2), categoryIndex]);
  1307. const height = Math.max(api.size([0, 1])[1] * 0.5, 8);
  1308. const rectShape = echarts.graphic.clipRectByRect({
  1309. x: start[0],
  1310. y: start[1] - height / 2,
  1311. width: Math.max(end[0] - start[0], 2),
  1312. height
  1313. }, {
  1314. x: params.coordSys.x,
  1315. y: params.coordSys.y,
  1316. width: params.coordSys.width,
  1317. height: params.coordSys.height
  1318. });
  1319. return rectShape ? { type: 'rect', shape: rectShape, style: api.style() } : undefined;
  1320. },
  1321. encode: { x: [1, 2], y: 0 },
  1322. data,
  1323. itemStyle: { borderRadius: 4 },
  1324. emphasis: { focus: 'self' },
  1325. markLine: {
  1326. silent: true,
  1327. symbol: 'none',
  1328. lineStyle: { color: '#ef4444', type: 'dashed', width: 1 },
  1329. label: { formatter: '今日', color: '#ef4444', fontSize: 10, position: 'end' },
  1330. data: [ { xAxis: todayTs } ]
  1331. }
  1332. },
  1333. // 请假覆盖层系列
  1334. {
  1335. type: 'custom',
  1336. name: '请假/繁忙标记',
  1337. renderItem: (params: any, api: any) => {
  1338. const categoryIndex = api.value(0);
  1339. const start = api.coord([api.value(1), categoryIndex]);
  1340. const end = api.coord([api.value(2), categoryIndex]);
  1341. const height = Math.max(api.size([0, 1])[1] * 0.8, 12); // 稍微高一点,覆盖项目条
  1342. const rectShape = echarts.graphic.clipRectByRect({
  1343. x: start[0],
  1344. y: start[1] - height / 2,
  1345. width: Math.max(end[0] - start[0], 2),
  1346. height
  1347. }, {
  1348. x: params.coordSys.x,
  1349. y: params.coordSys.y,
  1350. width: params.coordSys.width,
  1351. height: params.coordSys.height
  1352. });
  1353. return rectShape ? { type: 'rect', shape: rectShape, style: api.style() } : undefined;
  1354. },
  1355. encode: { x: [1, 2], y: 0 },
  1356. data: leaveOverlayData,
  1357. itemStyle: { borderRadius: 4 },
  1358. emphasis: { focus: 'self' },
  1359. z: 10 // 确保覆盖层在项目条之上
  1360. }
  1361. ]
  1362. };
  1363. // 强制刷新,避免缓存导致坐标轴不更新
  1364. this.ganttChart.clear();
  1365. this.ganttChart.setOption(option, true);
  1366. this.ganttChart.resize();
  1367. }
  1368. // 新增:设计师排班甘特
  1369. private updateGanttDesigner(): void {
  1370. if (!this.ganttChart) return;
  1371. const DAY = 24 * 60 * 60 * 1000;
  1372. const now = new Date();
  1373. const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  1374. const todayTs = today.getTime();
  1375. // 时间轴按当前周/月/日
  1376. let xMin: number;
  1377. let xMax: number;
  1378. let xSplitNumber: number;
  1379. let xLabelFormatter: (value: number) => string;
  1380. if (this.ganttScale === 'day') {
  1381. // 日视图:显示今日24小时
  1382. const startOfDay = new Date(today.getTime());
  1383. const endOfDay = new Date(today.getTime() + DAY - 1);
  1384. xMin = startOfDay.getTime();
  1385. xMax = endOfDay.getTime();
  1386. xSplitNumber = 24;
  1387. xLabelFormatter = (val) => `${new Date(val).getHours()}:00`;
  1388. } else if (this.ganttScale === 'week') {
  1389. // 周视图:从今天开始显示未来7天的具体日期
  1390. const startOfWeek = new Date(today.getTime());
  1391. const endOfWeek = new Date(today.getTime() + 7 * DAY - 1);
  1392. xMin = startOfWeek.getTime();
  1393. xMax = endOfWeek.getTime();
  1394. xSplitNumber = 7;
  1395. xLabelFormatter = (val) => {
  1396. const date = new Date(val);
  1397. const month = date.getMonth() + 1;
  1398. const day = date.getDate();
  1399. return `${month}月${day}日`;
  1400. };
  1401. } else {
  1402. // 月视图:从当前月份开始显示未来几个月
  1403. const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
  1404. const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 3, 0, 23, 59, 59, 999); // 显示未来3个月
  1405. xMin = startOfMonth.getTime();
  1406. xMax = endOfMonth.getTime();
  1407. xSplitNumber = 3;
  1408. xLabelFormatter = (val) => {
  1409. const date = new Date(val);
  1410. const year = date.getFullYear();
  1411. const month = date.getMonth() + 1;
  1412. return `${year}年${month}月`;
  1413. };
  1414. }
  1415. // 仅统计已分配项目
  1416. const assigned = this.filteredProjects.filter(p => !!p.designerName);
  1417. const designers = Array.from(new Set(assigned.map(p => p.designerName)));
  1418. const byDesigner: Record<string, typeof assigned> = {} as any;
  1419. designers.forEach(n => byDesigner[n] = [] as any);
  1420. assigned.forEach(p => byDesigner[p.designerName].push(p));
  1421. const busyCountMap: Record<string, number> = Object.fromEntries(designers.map(n => [n, byDesigner[n].length]));
  1422. const sortedDesigners = designers.sort((a, b) => {
  1423. const diff = (busyCountMap[b] || 0) - (busyCountMap[a] || 0);
  1424. return diff !== 0 ? diff : a.localeCompare(b, 'zh-CN');
  1425. });
  1426. const categories = sortedDesigners;
  1427. // 工作量等级(用于左侧小圆点颜色和负荷状态判断)
  1428. const workloadLevelMap: Record<string, 'high'|'medium'|'low'> = {} as any;
  1429. const workloadStatusMap: Record<string, 'overloaded'|'busy'|'available'> = {} as any;
  1430. categories.forEach(name => {
  1431. const cnt = busyCountMap[name] || 0;
  1432. if (cnt >= 5) {
  1433. workloadLevelMap[name] = 'high';
  1434. workloadStatusMap[name] = 'overloaded'; // 不宜派单
  1435. } else if (cnt >= 3) {
  1436. workloadLevelMap[name] = 'medium';
  1437. workloadStatusMap[name] = 'busy'; // 适度忙碌
  1438. } else {
  1439. workloadLevelMap[name] = 'low';
  1440. workloadStatusMap[name] = 'available'; // 可接单
  1441. }
  1442. });
  1443. // 条形颜色按项目紧急度,增强高负荷时段的视觉效果
  1444. const colorByUrgency: Record<'high'|'medium'|'low', string> = {
  1445. high: '#dc2626', // 更深的红色,突出高紧急度
  1446. medium: '#ea580c', // 更深的橙色
  1447. low: '#16a34a' // 更深的绿色
  1448. } as const;
  1449. const data = assigned.flatMap(p => {
  1450. const end = new Date(p.deadline).getTime();
  1451. const baseDays = p.type === 'hard' ? 30 : 14;
  1452. const start = p.createdAt ? new Date(p.createdAt).getTime() : end - baseDays * DAY;
  1453. const yIndex = categories.indexOf(p.designerName);
  1454. if (yIndex === -1) return [] as any[];
  1455. // 根据设计师工作负荷状态调整项目条的视觉效果
  1456. const workloadStatus = workloadStatusMap[p.designerName];
  1457. let color = colorByUrgency[p.urgency] || '#60a5fa';
  1458. let borderWidth = 1;
  1459. let borderColor = 'transparent';
  1460. // 高负荷时段增强视觉效果
  1461. if (workloadStatus === 'overloaded') {
  1462. borderWidth = 3;
  1463. borderColor = '#991b1b'; // 深红色边框
  1464. // 对于超负荷状态,使用更深的红色调
  1465. if (p.urgency === 'high') {
  1466. color = '#7f1d1d'; // 深红色
  1467. } else if (p.urgency === 'medium') {
  1468. color = '#c2410c'; // 深橙色
  1469. } else {
  1470. color = '#dc2626'; // 红色(即使是低紧急度也用红色表示超负荷)
  1471. }
  1472. }
  1473. return [{
  1474. name: p.name,
  1475. value: [yIndex, start, end, p.designerName, p.urgency, p.memberType, p.currentStage, workloadStatus],
  1476. itemStyle: {
  1477. color,
  1478. borderWidth,
  1479. borderColor,
  1480. opacity: workloadStatus === 'overloaded' ? 0.9 : 1.0
  1481. }
  1482. }];
  1483. });
  1484. // 生成空闲时段背景数据 - 只在真正空闲的时间段显示
  1485. const idleBackgroundData: any[] = [];
  1486. categories.forEach((designerName, yIndex) => {
  1487. const designerProjects = byDesigner[designerName] || [];
  1488. const workloadStatus = workloadStatusMap[designerName];
  1489. // 获取该设计师的所有项目时间段
  1490. const projectTimeRanges = designerProjects.map(p => {
  1491. const end = new Date(p.deadline).getTime();
  1492. const baseDays = p.type === 'hard' ? 30 : 14;
  1493. const start = p.createdAt ? new Date(p.createdAt).getTime() : end - baseDays * DAY;
  1494. return { start, end };
  1495. }).sort((a, b) => a.start - b.start);
  1496. // 找出空闲时间段
  1497. const idleTimeRanges: { start: number; end: number }[] = [];
  1498. if (projectTimeRanges.length === 0) {
  1499. // 完全没有项目,整个时间轴都是空闲
  1500. idleTimeRanges.push({ start: xMin, end: xMax });
  1501. } else {
  1502. // 检查项目之间的空隙
  1503. let currentTime = xMin;
  1504. for (const range of projectTimeRanges) {
  1505. if (currentTime < range.start) {
  1506. // 在项目开始前有空闲时间
  1507. idleTimeRanges.push({ start: currentTime, end: range.start });
  1508. }
  1509. currentTime = Math.max(currentTime, range.end);
  1510. }
  1511. // 检查最后一个项目后是否还有空闲时间
  1512. if (currentTime < xMax) {
  1513. idleTimeRanges.push({ start: currentTime, end: xMax });
  1514. }
  1515. }
  1516. // 为每个空闲时间段创建背景数据
  1517. idleTimeRanges.forEach((idleRange, index) => {
  1518. // 只有当空闲时间段足够长时才显示(至少1天)
  1519. if (idleRange.end - idleRange.start >= DAY) {
  1520. let backgroundColor = 'transparent';
  1521. if (workloadStatus === 'available') {
  1522. backgroundColor = 'rgba(34, 197, 94, 0.15)'; // 淡绿色背景表示空闲可接单
  1523. } else if (workloadStatus === 'overloaded') {
  1524. backgroundColor = 'rgba(239, 68, 68, 0.1)'; // 淡红色背景表示超负荷
  1525. }
  1526. if (backgroundColor !== 'transparent') {
  1527. idleBackgroundData.push({
  1528. name: `${designerName}-空闲${index + 1}`,
  1529. value: [yIndex, idleRange.start, idleRange.end, designerName, 'background', workloadStatus],
  1530. itemStyle: {
  1531. color: backgroundColor,
  1532. borderWidth: 0
  1533. }
  1534. });
  1535. }
  1536. }
  1537. });
  1538. });
  1539. const prevOpt: any = (this.ganttChart as any).getOption ? (this.ganttChart as any).getOption() : null;
  1540. const total = categories.length || 1;
  1541. const visible = Math.min(total, 30);
  1542. const defaultEndPercent = Math.min(100, (visible / total) * 100);
  1543. const preservedStart = typeof prevOpt?.dataZoom?.[0]?.start === 'number' ? prevOpt.dataZoom[0].start : 0;
  1544. const preservedEnd = typeof prevOpt?.dataZoom?.[0]?.end === 'number' ? prevOpt.dataZoom[0].end : defaultEndPercent;
  1545. const option = {
  1546. backgroundColor: 'transparent',
  1547. tooltip: {
  1548. trigger: 'item',
  1549. backgroundColor: 'rgba(255, 255, 255, 0.95)',
  1550. borderColor: '#e5e7eb',
  1551. borderWidth: 1,
  1552. padding: [12, 16],
  1553. textStyle: { color: '#374151', fontSize: 13 },
  1554. formatter: (params: any) => {
  1555. const v = params.value;
  1556. if (v[4] === 'background') {
  1557. const workloadStatus = v[5];
  1558. const statusText = workloadStatus === 'available' ? '空闲可接单' :
  1559. workloadStatus === 'overloaded' ? '超负荷不宜派单' : '适度忙碌';
  1560. return `<div style="padding: 4px 0;">
  1561. <div style="font-weight: 600; margin-bottom: 6px;">👤 ${v[3]}</div>
  1562. <div style="color: #6b7280;">状态:${statusText}</div>
  1563. </div>`;
  1564. }
  1565. const start = new Date(v[1]);
  1566. const end = new Date(v[2]);
  1567. const urgency = v[4];
  1568. const memberType = v[5];
  1569. const currentStage = v[6];
  1570. const workloadStatus = v[7];
  1571. // 紧急度标识
  1572. const urgencyBadge = urgency === 'high' ? '<span style="background:#dc2626;color:white;padding:2px 6px;border-radius:3px;font-size:11px;">🔥 高紧急</span>' :
  1573. urgency === 'medium' ? '<span style="background:#ea580c;color:white;padding:2px 6px;border-radius:3px;font-size:11px;">⚡ 中紧急</span>' :
  1574. '<span style="background:#16a34a;color:white;padding:2px 6px;border-radius:3px;font-size:11px;">✓ 正常</span>';
  1575. // VIP标识
  1576. const vipBadge = memberType === 'vip' ? '<span style="background:#f59e0b;color:white;padding:2px 6px;border-radius:3px;font-size:11px;margin-left:4px;">⭐ VIP</span>' : '';
  1577. // 负载状态
  1578. const statusIcon = workloadStatus === 'available' ? '🟢' :
  1579. workloadStatus === 'overloaded' ? '🔴' : '🟡';
  1580. const statusText = workloadStatus === 'available' ? '可接单' :
  1581. workloadStatus === 'overloaded' ? '超负荷' : '适度忙碌';
  1582. // 计算项目持续天数
  1583. const durationDays = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
  1584. // 剩余天数
  1585. const now = new Date();
  1586. const remainingDays = Math.ceil((end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
  1587. const remainingText = remainingDays > 0 ? `剩余${remainingDays}天` :
  1588. remainingDays === 0 ? '今天截止' :
  1589. `已超期${Math.abs(remainingDays)}天`;
  1590. const remainingColor = remainingDays > 7 ? '#16a34a' :
  1591. remainingDays > 0 ? '#ea580c' : '#dc2626';
  1592. return `<div style="min-width: 280px;">
  1593. <div style="font-weight: 600; margin-bottom: 8px; font-size: 14px; display: flex; align-items: center; gap: 6px;">
  1594. 🎨 ${params.name}
  1595. </div>
  1596. <div style="display: flex; gap: 4px; margin-bottom: 8px;">
  1597. ${urgencyBadge}${vipBadge}
  1598. </div>
  1599. <div style="border-top: 1px solid #e5e7eb; padding-top: 8px; margin-top: 4px;">
  1600. <div style="margin-bottom: 4px;">👤 设计师:<strong>${v[3]}</strong> ${statusIcon} <span style="color: #6b7280;">${statusText}</span></div>
  1601. <div style="margin-bottom: 4px;">📋 阶段:<span style="color: #6b7280;">${currentStage}</span></div>
  1602. <div style="margin-bottom: 4px;">📅 周期:<span style="color: #6b7280;">${start.toLocaleDateString()} ~ ${end.toLocaleDateString()}</span> (${durationDays}天)</div>
  1603. <div style="margin-bottom: 4px;">⏱️ 状态:<span style="color: ${remainingColor}; font-weight: 600;">${remainingText}</span></div>
  1604. </div>
  1605. <div style="border-top: 1px solid #e5e7eb; padding-top: 6px; margin-top: 6px; color: #9ca3af; font-size: 11px;">
  1606. 💡 点击条形可查看项目详情
  1607. </div>
  1608. </div>`;
  1609. }
  1610. },
  1611. title: {
  1612. text: this.ganttScale === 'week' ? '本周项目排期' : '本月项目排期',
  1613. subtext: '每个条形代表一个项目,颜色越深紧急度越高',
  1614. left: 'center',
  1615. top: 10,
  1616. textStyle: { fontSize: 15, color: '#374151', fontWeight: 600 },
  1617. subtextStyle: { fontSize: 12, color: '#6b7280' }
  1618. },
  1619. legend: {
  1620. data: ['🔥 高紧急', '⚡ 中紧急', '✓ 正常', '🟢 可接单', '🟡 忙碌', '🔴 超负荷'],
  1621. bottom: 10,
  1622. itemGap: 20,
  1623. textStyle: { fontSize: 12, color: '#6b7280' }
  1624. },
  1625. grid: { left: 150, right: 70, top: 60, bottom: 70 },
  1626. xAxis: {
  1627. type: 'time',
  1628. min: xMin,
  1629. max: xMax,
  1630. splitNumber: xSplitNumber,
  1631. axisLine: { lineStyle: { color: '#e5e7eb' } },
  1632. axisLabel: { color: '#6b7280', formatter: (value: number) => xLabelFormatter(value) },
  1633. splitLine: { lineStyle: { color: '#f1f5f9' } }
  1634. },
  1635. yAxis: {
  1636. type: 'category',
  1637. data: categories,
  1638. inverse: true,
  1639. axisLabel: {
  1640. color: '#374151',
  1641. margin: 10,
  1642. fontSize: 13,
  1643. fontWeight: 500,
  1644. formatter: (val: string) => {
  1645. const lvl = workloadLevelMap[val] || 'low';
  1646. const count = busyCountMap[val] || 0;
  1647. const status = workloadStatusMap[val] || 'available';
  1648. const text = val.length > 6 ? val.slice(0, 6) + '…' : val;
  1649. // 根据负载状态选择图标和颜色
  1650. const statusIcon = status === 'available' ? '○' :
  1651. status === 'overloaded' ? '🔥' : '⚡';
  1652. // 项目数量的视觉强化
  1653. const countDisplay = count >= 5 ? `{highCount|${count}}` :
  1654. count >= 3 ? `{mediumCount|${count}}` :
  1655. count >= 1 ? `{lowCount|${count}}` :
  1656. `{idleCount|${count}}`;
  1657. return `${statusIcon} {name|${text}} ${countDisplay}`;
  1658. },
  1659. rich: {
  1660. name: {
  1661. color: '#374151',
  1662. fontSize: 13,
  1663. fontWeight: 500,
  1664. padding: [0, 4, 0, 2]
  1665. },
  1666. highCount: {
  1667. color: '#dc2626',
  1668. fontSize: 12,
  1669. fontWeight: 700,
  1670. backgroundColor: '#fee2e2',
  1671. padding: [2, 6],
  1672. borderRadius: 3
  1673. },
  1674. mediumCount: {
  1675. color: '#ea580c',
  1676. fontSize: 12,
  1677. fontWeight: 700,
  1678. backgroundColor: '#ffedd5',
  1679. padding: [2, 6],
  1680. borderRadius: 3
  1681. },
  1682. lowCount: {
  1683. color: '#16a34a',
  1684. fontSize: 12,
  1685. fontWeight: 600,
  1686. backgroundColor: '#dcfce7',
  1687. padding: [2, 6],
  1688. borderRadius: 3
  1689. },
  1690. idleCount: {
  1691. color: '#9ca3af',
  1692. fontSize: 12,
  1693. fontWeight: 500,
  1694. backgroundColor: '#f3f4f6',
  1695. padding: [2, 6],
  1696. borderRadius: 3
  1697. }
  1698. }
  1699. },
  1700. axisTick: { show: false },
  1701. axisLine: { lineStyle: { color: '#e5e7eb' } }
  1702. },
  1703. dataZoom: [
  1704. { type: 'slider', yAxisIndex: 0, orient: 'vertical', right: 6, start: preservedStart, end: preservedEnd, zoomLock: false },
  1705. { type: 'inside', yAxisIndex: 0, zoomOnMouseWheel: true, moveOnMouseMove: true, moveOnMouseWheel: true }
  1706. ],
  1707. series: [
  1708. // 背景层 - 显示空闲时段
  1709. {
  1710. type: 'custom',
  1711. name: '工作负荷背景',
  1712. renderItem: (params: any, api: any) => {
  1713. const categoryIndex = api.value(0);
  1714. const start = api.coord([api.value(1), categoryIndex]);
  1715. const end = api.coord([api.value(2), categoryIndex]);
  1716. const height = api.size([0, 1])[1] * 0.8;
  1717. const rectShape = echarts.graphic.clipRectByRect({
  1718. x: start[0],
  1719. y: start[1] - height / 2,
  1720. width: Math.max(end[0] - start[0], 2),
  1721. height
  1722. }, {
  1723. x: params.coordSys.x,
  1724. y: params.coordSys.y,
  1725. width: params.coordSys.width,
  1726. height: params.coordSys.height
  1727. });
  1728. return rectShape ? { type: 'rect', shape: rectShape, style: api.style() } : undefined;
  1729. },
  1730. encode: { x: [1, 2], y: 0 },
  1731. data: idleBackgroundData,
  1732. z: 1
  1733. },
  1734. // 项目条层
  1735. {
  1736. type: 'custom',
  1737. name: '项目进度',
  1738. renderItem: (params: any, api: any) => {
  1739. const categoryIndex = api.value(0);
  1740. const start = api.coord([api.value(1), categoryIndex]);
  1741. const end = api.coord([api.value(2), categoryIndex]);
  1742. // 增加条形高度,让项目更明显
  1743. const height = Math.max(api.size([0, 1])[1] * 0.6, 16);
  1744. const width = Math.max(end[0] - start[0], 2);
  1745. const rectShape = echarts.graphic.clipRectByRect({
  1746. x: start[0],
  1747. y: start[1] - height / 2,
  1748. width,
  1749. height
  1750. }, {
  1751. x: params.coordSys.x,
  1752. y: params.coordSys.y,
  1753. width: params.coordSys.width,
  1754. height: params.coordSys.height
  1755. });
  1756. if (!rectShape) return undefined;
  1757. // 获取项目数据
  1758. const urgency = api.value(4);
  1759. const workloadStatus = api.value(7);
  1760. // 基础矩形样式
  1761. const rectStyle = api.style();
  1762. // 根据负载状态添加额外的视觉效果
  1763. if (workloadStatus === 'overloaded') {
  1764. rectStyle.shadowBlur = 8;
  1765. rectStyle.shadowColor = 'rgba(220, 38, 38, 0.4)';
  1766. rectStyle.shadowOffsetY = 2;
  1767. }
  1768. const rect = {
  1769. type: 'rect',
  1770. shape: rectShape,
  1771. style: rectStyle
  1772. };
  1773. // 项目名称和紧急度标识
  1774. const projectName = params.name || '';
  1775. const minWidthForText = 50; // 降低最小宽度要求
  1776. if (width >= minWidthForText && projectName) {
  1777. // 紧急度图标
  1778. const urgencyIcon = urgency === 'high' ? '🔥' :
  1779. urgency === 'medium' ? '⚡' : '✓';
  1780. // 截断过长的项目名称
  1781. const maxChars = Math.floor(width / 9); // 估算能显示的字符数
  1782. const displayName = projectName.length > maxChars ?
  1783. projectName.slice(0, maxChars - 2) + '…' :
  1784. projectName;
  1785. const fullText = `${urgencyIcon} ${displayName}`;
  1786. // 返回组合图形:矩形 + 文本
  1787. return {
  1788. type: 'group',
  1789. children: [
  1790. rect,
  1791. {
  1792. type: 'text',
  1793. style: {
  1794. text: fullText,
  1795. x: rectShape.x + 8,
  1796. y: rectShape.y + rectShape.height / 2,
  1797. textVerticalAlign: 'middle',
  1798. fontSize: 12,
  1799. fontWeight: 600,
  1800. fill: '#ffffff',
  1801. stroke: 'rgba(0, 0, 0, 0.4)',
  1802. lineWidth: 0.8,
  1803. textShadowColor: 'rgba(0, 0, 0, 0.5)',
  1804. textShadowBlur: 3,
  1805. textShadowOffsetX: 0,
  1806. textShadowOffsetY: 1
  1807. }
  1808. }
  1809. ]
  1810. };
  1811. } else if (width >= 30) {
  1812. // 如果空间太小,只显示紧急度图标
  1813. const urgencyIcon = urgency === 'high' ? '🔥' :
  1814. urgency === 'medium' ? '⚡' : '✓';
  1815. return {
  1816. type: 'group',
  1817. children: [
  1818. rect,
  1819. {
  1820. type: 'text',
  1821. style: {
  1822. text: urgencyIcon,
  1823. x: rectShape.x + width / 2,
  1824. y: rectShape.y + rectShape.height / 2,
  1825. textAlign: 'center',
  1826. textVerticalAlign: 'middle',
  1827. fontSize: 12
  1828. }
  1829. }
  1830. ]
  1831. };
  1832. }
  1833. return rect;
  1834. },
  1835. encode: { x: [1, 2], y: 0 },
  1836. data,
  1837. itemStyle: { borderRadius: 4 },
  1838. emphasis: {
  1839. focus: 'self',
  1840. itemStyle: {
  1841. borderWidth: 2,
  1842. borderColor: '#374151',
  1843. shadowBlur: 8,
  1844. shadowColor: 'rgba(0, 0, 0, 0.3)'
  1845. }
  1846. },
  1847. z: 2,
  1848. markLine: {
  1849. silent: true,
  1850. symbol: 'none',
  1851. lineStyle: { color: '#ef4444', type: 'dashed', width: 2 },
  1852. label: {
  1853. formatter: '今日',
  1854. color: '#ef4444',
  1855. fontSize: 11,
  1856. fontWeight: 600,
  1857. position: 'end',
  1858. backgroundColor: '#ffffff',
  1859. padding: [2, 6],
  1860. borderRadius: 3
  1861. },
  1862. data: [ { xAxis: todayTs } ]
  1863. }
  1864. }
  1865. ]
  1866. } as any;
  1867. this.ganttChart.clear();
  1868. this.ganttChart.setOption(option, true);
  1869. this.ganttChart.resize();
  1870. }
  1871. /**
  1872. * 工作负载甘特图:显示设计师在周/月内的工作状态
  1873. */
  1874. private updateWorkloadGantt(): void {
  1875. if (!this.workloadGanttContainer?.nativeElement) {
  1876. setTimeout(() => this.updateWorkloadGantt(), 100);
  1877. return;
  1878. }
  1879. if (!this.workloadGanttChart) {
  1880. this.workloadGanttChart = echarts.init(this.workloadGanttContainer.nativeElement);
  1881. }
  1882. const DAY = 24 * 60 * 60 * 1000;
  1883. const now = new Date();
  1884. const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  1885. const todayTs = today.getTime();
  1886. // 时间范围
  1887. let xMin: number;
  1888. let xMax: number;
  1889. let xSplitNumber: number;
  1890. let xLabelFormatter: (value: number) => string;
  1891. if (this.workloadGanttScale === 'week') {
  1892. // 周视图:显示未来7天
  1893. xMin = todayTs;
  1894. xMax = todayTs + 7 * DAY;
  1895. xSplitNumber = 7;
  1896. xLabelFormatter = (val: any) => {
  1897. const date = new Date(val);
  1898. const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  1899. return `${date.getMonth() + 1}/${date.getDate()}\n${weekDays[date.getDay()]}`;
  1900. };
  1901. } else {
  1902. // 月视图:显示未来30天
  1903. xMin = todayTs;
  1904. xMax = todayTs + 30 * DAY;
  1905. xSplitNumber = 30;
  1906. xLabelFormatter = (val: any) => {
  1907. const date = new Date(val);
  1908. return `${date.getMonth() + 1}/${date.getDate()}`;
  1909. };
  1910. }
  1911. // 获取所有真实设计师
  1912. let designers: string[] = [];
  1913. if (this.realDesigners && this.realDesigners.length > 0) {
  1914. designers = this.realDesigners.map(d => d.name);
  1915. } else {
  1916. // 降级:从已分配的项目中提取设计师
  1917. const assigned = this.filteredProjects.filter(p => p.designerName && p.designerName !== '未分配');
  1918. designers = Array.from(new Set(assigned.map(p => p.designerName)));
  1919. }
  1920. if (designers.length === 0) {
  1921. // 没有设计师数据,显示空状态
  1922. const emptyOption = {
  1923. title: {
  1924. text: '暂无组员数据',
  1925. subtext: '请先在系统中添加设计师(组员角色)',
  1926. left: 'center',
  1927. top: 'center',
  1928. textStyle: { fontSize: 16, color: '#9ca3af' },
  1929. subtextStyle: { fontSize: 13, color: '#d1d5db' }
  1930. }
  1931. };
  1932. this.workloadGanttChart.setOption(emptyOption, true);
  1933. return;
  1934. }
  1935. // 🔧 使用 ProjectTeam 表的数据(实际执行人)
  1936. const workloadByDesigner: Record<string, any[]> = {};
  1937. designers.forEach(name => {
  1938. workloadByDesigner[name] = [];
  1939. });
  1940. // 计算每个设计师的总负载(用于排序)
  1941. const designerTotalLoad: Record<string, number> = {};
  1942. designers.forEach(name => {
  1943. const projects = this.designerWorkloadMap.get(name) || [];
  1944. designerTotalLoad[name] = projects.length;
  1945. });
  1946. // 按总负载从高到低排序设计师
  1947. const sortedDesigners = designers.sort((a, b) => {
  1948. return designerTotalLoad[b] - designerTotalLoad[a];
  1949. });
  1950. // 为每个设计师生成时间段数据
  1951. sortedDesigners.forEach((designerName, yIndex) => {
  1952. const designerProjects = this.designerWorkloadMap.get(designerName) || [];
  1953. // 计算每一天的状态
  1954. const days = this.workloadGanttScale === 'week' ? 7 : 30;
  1955. for (let i = 0; i < days; i++) {
  1956. const dayStart = todayTs + i * DAY;
  1957. const dayEnd = dayStart + DAY - 1;
  1958. // 查找该天有哪些项目
  1959. const dayProjects = designerProjects.filter(p => {
  1960. // 如果项目没有 deadline,则认为项目一直在进行中
  1961. if (!p.deadline) {
  1962. return true; // 没有截止日期的项目始终显示
  1963. }
  1964. const pEnd = new Date(p.deadline).getTime();
  1965. // 检查时间是否有效
  1966. if (isNaN(pEnd)) {
  1967. return true; // 如果截止日期无效,认为项目在进行中
  1968. }
  1969. // 🔧 修复:对于进行中的项目(状态不是"已完成"),即使过期也显示
  1970. // 这样可以在甘特图中看到超期的项目
  1971. const isCompleted = p.status === '已完成' || p.status === '已交付';
  1972. if (!isCompleted) {
  1973. // 进行中的项目:只要截止日期还没到很久之前(比如30天前),就显示
  1974. const thirtyDaysAgo = todayTs - 30 * DAY;
  1975. if (pEnd >= thirtyDaysAgo) {
  1976. return true; // 30天内的项目都显示
  1977. }
  1978. }
  1979. // 已完成的项目:正常时间范围判断
  1980. const pStart = p.createdAt ? new Date(p.createdAt).getTime() : dayStart;
  1981. return !(pEnd < dayStart || pStart > dayEnd);
  1982. });
  1983. let status: 'idle' | 'busy' | 'overload' | 'leave' = 'idle';
  1984. let color = '#d1fae5'; // 空闲-浅绿色
  1985. const projectCount = dayProjects.length;
  1986. // TODO: 检查请假记录,如果该天请假则标记为leave
  1987. // const isOnLeave = this.checkLeave(designerName, dayStart, dayEnd);
  1988. // if (isOnLeave) {
  1989. // status = 'leave';
  1990. // color = '#e5e7eb'; // 请假-灰色
  1991. // }
  1992. if (projectCount === 0) {
  1993. status = 'idle';
  1994. color = '#d1fae5'; // 空闲-浅绿色(0个项目)
  1995. } else if (projectCount >= 3) {
  1996. status = 'overload';
  1997. color = '#fecaca'; // 超负荷-浅红色(≥3个项目)
  1998. } else {
  1999. status = 'busy';
  2000. color = '#bfdbfe'; // 忙碌-浅蓝色(1-2个项目)
  2001. }
  2002. workloadByDesigner[designerName].push({
  2003. name: `${designerName}-${i}`,
  2004. value: [yIndex, dayStart, dayEnd, designerName, status, projectCount, dayProjects.map(p => p.name)],
  2005. itemStyle: { color }
  2006. });
  2007. }
  2008. });
  2009. // 合并所有数据
  2010. const data = Object.values(workloadByDesigner).flat();
  2011. const option = {
  2012. backgroundColor: '#fff',
  2013. title: {
  2014. text: this.workloadGanttScale === 'week' ? '未来7天工作状态' : '未来30天工作状态',
  2015. subtext: '🟢空闲 🔵忙碌 🔴超负荷',
  2016. left: 'center',
  2017. textStyle: { fontSize: 14, color: '#374151', fontWeight: 600 },
  2018. subtextStyle: { fontSize: 12, color: '#6b7280' }
  2019. },
  2020. tooltip: {
  2021. formatter: (params: any) => {
  2022. const [yIndex, start, end, name, status, projectCount, projectNames = []] = params.value;
  2023. const startDate = new Date(start);
  2024. const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  2025. let statusText = '';
  2026. let statusColor = '';
  2027. let statusBadge = '';
  2028. if (status === 'leave') {
  2029. statusText = '请假';
  2030. statusColor = '#6b7280';
  2031. statusBadge = '<span style="background:#e5e7eb;color:#374151;padding:2px 8px;border-radius:4px;font-size:11px;">请假</span>';
  2032. } else if (projectCount === 0) {
  2033. statusText = '空闲';
  2034. statusColor = '#10b981';
  2035. statusBadge = '<span style="background:#d1fae5;color:#059669;padding:2px 8px;border-radius:4px;font-size:11px;">🟢 空闲</span>';
  2036. } else if (projectCount >= 3) {
  2037. statusText = '超负荷';
  2038. statusColor = '#dc2626';
  2039. statusBadge = '<span style="background:#fecaca;color:#dc2626;padding:2px 8px;border-radius:4px;font-size:11px;">🔴 超负荷</span>';
  2040. } else {
  2041. statusText = '忙碌';
  2042. statusColor = '#3b82f6';
  2043. statusBadge = '<span style="background:#bfdbfe;color:#1d4ed8;padding:2px 8px;border-radius:4px;font-size:11px;">🔵 忙碌</span>';
  2044. }
  2045. let projectListHtml = '';
  2046. if (projectNames && projectNames.length > 0) {
  2047. projectListHtml = `
  2048. <div style="margin-top: 8px; padding-top: 8px; border-top: 1px dashed #e5e7eb;">
  2049. <div style="font-size: 12px; color: #6b7280; margin-bottom: 4px;">项目列表:</div>
  2050. ${projectNames.slice(0, 5).map((pName: string, idx: number) =>
  2051. `<div style="font-size: 12px; color: #374151; margin-left: 8px;">
  2052. ${idx + 1}. ${pName.length > 20 ? pName.substring(0, 20) + '...' : pName}
  2053. </div>`
  2054. ).join('')}
  2055. ${projectNames.length > 5 ? `<div style="font-size: 12px; color: #6b7280; margin-left: 8px;">...及${projectNames.length - 5}个其他项目</div>` : ''}
  2056. </div>
  2057. `;
  2058. }
  2059. return `<div style="padding: 12px; min-width: 220px;">
  2060. <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
  2061. <strong style="font-size: 15px; color: #1f2937;">${name}</strong>
  2062. ${statusBadge}
  2063. </div>
  2064. <div style="color: #6b7280; font-size: 13px;">
  2065. 📅 ${startDate.getMonth() + 1}月${startDate.getDate()}日 ${weekDays[startDate.getDay()]}<br/>
  2066. 📊 项目数量: <span style="font-weight: 600; color: ${statusColor};">${projectCount}个</span>
  2067. </div>
  2068. ${projectListHtml}
  2069. <div style="margin-top: 10px; padding-top: 8px; border-top: 1px solid #e5e7eb; color: #6b7280; font-size: 11px; text-align: center;">
  2070. 💡 点击查看设计师详细信息
  2071. </div>
  2072. </div>`;
  2073. }
  2074. },
  2075. grid: {
  2076. left: 100,
  2077. right: 50,
  2078. top: 60,
  2079. bottom: 60
  2080. },
  2081. xAxis: {
  2082. type: 'time',
  2083. min: xMin,
  2084. max: xMax,
  2085. boundaryGap: false,
  2086. axisLine: { lineStyle: { color: '#e5e7eb' } },
  2087. axisLabel: {
  2088. color: '#6b7280',
  2089. formatter: xLabelFormatter,
  2090. interval: 0,
  2091. rotate: this.workloadGanttScale === 'week' ? 0 : 45,
  2092. showMinLabel: true,
  2093. showMaxLabel: true
  2094. },
  2095. axisTick: {
  2096. alignWithLabel: true,
  2097. interval: 0
  2098. },
  2099. splitLine: {
  2100. show: true,
  2101. lineStyle: { color: '#f1f5f9' }
  2102. },
  2103. splitNumber: xSplitNumber,
  2104. minInterval: DAY
  2105. },
  2106. yAxis: {
  2107. type: 'category',
  2108. data: sortedDesigners,
  2109. inverse: true,
  2110. axisLabel: {
  2111. color: '#374151',
  2112. margin: 8,
  2113. fontSize: 13,
  2114. fontWeight: 500,
  2115. formatter: (value: string) => {
  2116. const totalProjects = designerTotalLoad[value] || 0;
  2117. const icon = totalProjects >= 3 ? '🔥' : totalProjects >= 2 ? '⚡' : totalProjects >= 1 ? '✓' : '○';
  2118. return `${icon} ${value} (${totalProjects})`;
  2119. }
  2120. },
  2121. axisTick: { show: false },
  2122. axisLine: { lineStyle: { color: '#e5e7eb' } }
  2123. },
  2124. series: [
  2125. {
  2126. type: 'custom',
  2127. name: '工作负载',
  2128. renderItem: (params: any, api: any) => {
  2129. const categoryIndex = api.value(0);
  2130. const start = api.coord([api.value(1), categoryIndex]);
  2131. const end = api.coord([api.value(2), categoryIndex]);
  2132. const height = api.size([0, 1])[1] * 0.6;
  2133. const rectShape = echarts.graphic.clipRectByRect({
  2134. x: start[0],
  2135. y: start[1] - height / 2,
  2136. width: Math.max(end[0] - start[0], 2),
  2137. height
  2138. }, {
  2139. x: params.coordSys.x,
  2140. y: params.coordSys.y,
  2141. width: params.coordSys.width,
  2142. height: params.coordSys.height
  2143. });
  2144. return rectShape ? {
  2145. type: 'rect',
  2146. shape: rectShape,
  2147. style: api.style()
  2148. } : undefined;
  2149. },
  2150. encode: { x: [1, 2], y: 0 },
  2151. data,
  2152. z: 2
  2153. }
  2154. ]
  2155. } as any;
  2156. this.workloadGanttChart.setOption(option, true);
  2157. // 添加点击事件:点击设计师行时显示详情
  2158. this.workloadGanttChart.on('click', (params: any) => {
  2159. if (params.componentType === 'series' && params.seriesType === 'custom') {
  2160. const designerName = params.value[3]; // value[3]是设计师名称
  2161. if (designerName && designerName !== '未分配') {
  2162. this.onEmployeeClick(designerName);
  2163. }
  2164. }
  2165. });
  2166. }
  2167. ngOnDestroy(): void {
  2168. if (this.ganttChart) {
  2169. this.ganttChart.dispose();
  2170. this.ganttChart = null;
  2171. }
  2172. if (this.workloadGanttChart) {
  2173. this.workloadGanttChart.dispose();
  2174. this.workloadGanttChart = null;
  2175. }
  2176. // 清理待办任务自动刷新定时器
  2177. if (this.todoTaskRefreshTimer) {
  2178. clearInterval(this.todoTaskRefreshTimer);
  2179. }
  2180. }
  2181. // 选择单个项目
  2182. selectProject(): void {
  2183. if (this.selectedProjectId) {
  2184. const cid = localStorage.getItem('company') || 'cDL6R1hgSi';
  2185. this.router.navigate(['/wxwork', cid, 'project', this.selectedProjectId]);
  2186. }
  2187. }
  2188. // 获取特定阶段的项目
  2189. getProjectsByStage(stageId: string): Project[] {
  2190. return this.filteredProjects.filter(project => project.currentStage === stageId);
  2191. }
  2192. // 新增:阶段到核心阶段的映射
  2193. private mapStageToCorePhase(stageId: string): 'order' | 'requirements' | 'delivery' | 'aftercare' {
  2194. if (!stageId) return 'order'; // 空值默认为订单分配
  2195. // 标准化阶段名称(去除空格,转小写)
  2196. const normalizedStage = stageId.trim().toLowerCase();
  2197. // 1. 订单分配阶段(英文ID + 中文名称)
  2198. if (normalizedStage === 'order' ||
  2199. normalizedStage === 'pendingapproval' ||
  2200. normalizedStage === 'pendingassignment' ||
  2201. normalizedStage === '订单分配' ||
  2202. normalizedStage === '待审批' ||
  2203. normalizedStage === '待分配') {
  2204. return 'order';
  2205. }
  2206. // 2. 确认需求阶段(英文ID + 中文名称)
  2207. if (normalizedStage === 'requirements' ||
  2208. normalizedStage === 'requirement' ||
  2209. normalizedStage === 'planning' ||
  2210. normalizedStage === '确认需求' ||
  2211. normalizedStage === '需求沟通' ||
  2212. normalizedStage === '方案规划') {
  2213. return 'requirements';
  2214. }
  2215. // 3. 交付执行阶段(英文ID + 中文名称)
  2216. if (normalizedStage === 'delivery' ||
  2217. normalizedStage === 'modeling' ||
  2218. normalizedStage === 'rendering' ||
  2219. normalizedStage === 'postproduction' ||
  2220. normalizedStage === 'review' ||
  2221. normalizedStage === 'revision' ||
  2222. normalizedStage === '交付执行' ||
  2223. normalizedStage === '建模' ||
  2224. normalizedStage === '建模阶段' ||
  2225. normalizedStage === '渲染' ||
  2226. normalizedStage === '渲染阶段' ||
  2227. normalizedStage === '后期制作' ||
  2228. normalizedStage === '评审' ||
  2229. normalizedStage === '修改' ||
  2230. normalizedStage === '修订') {
  2231. return 'delivery';
  2232. }
  2233. // 4. 售后归档阶段(英文ID + 中文名称)
  2234. if (normalizedStage === 'aftercare' ||
  2235. normalizedStage === 'completed' ||
  2236. normalizedStage === 'archived' ||
  2237. normalizedStage === '售后归档' ||
  2238. normalizedStage === '售后' ||
  2239. normalizedStage === '归档' ||
  2240. normalizedStage === '已完成' ||
  2241. normalizedStage === '已交付') {
  2242. return 'aftercare';
  2243. }
  2244. // 未匹配的阶段:默认为交付执行(因为大部分时间项目都在执行中)
  2245. console.warn(`⚠️ 未识别的阶段: "${stageId}" → 默认归类为交付执行`);
  2246. return 'delivery';
  2247. }
  2248. // 新增:获取核心阶段的项目
  2249. getProjectsByCorePhase(coreId: string): Project[] {
  2250. return this.filteredProjects.filter(p => this.mapStageToCorePhase(p.currentStage) === coreId);
  2251. }
  2252. // 新增:获取核心阶段的项目数量
  2253. getProjectCountByCorePhase(coreId: string): number {
  2254. return this.getProjectsByCorePhase(coreId).length;
  2255. }
  2256. // 获取特定阶段的项目数量
  2257. getProjectCountByStage(stageId: string): number {
  2258. return this.getProjectsByStage(stageId).length;
  2259. }
  2260. // 🔥 已延期项目
  2261. get overdueProjects(): Project[] {
  2262. return this.projects.filter(p => p.isOverdue);
  2263. }
  2264. // ⏳ 临期项目(3天内)
  2265. get dueSoonProjects(): Project[] {
  2266. return this.projects.filter(p => p.dueSoon && !p.isOverdue);
  2267. }
  2268. // 📋 待审批项目(支持中文和英文阶段名称)
  2269. get pendingApprovalProjects(): Project[] {
  2270. return this.projects.filter(p => {
  2271. const stage = (p.currentStage || '').trim();
  2272. const data = (p as any).data || {};
  2273. const approvalStatus = data.approvalStatus;
  2274. // 1. 阶段为"订单分配"且审批状态为 pending
  2275. // 2. 或者阶段为"待确认"/"待审批"(兼容旧数据)
  2276. return (stage === '订单分配' && approvalStatus === 'pending') ||
  2277. stage === '待审批' ||
  2278. stage === '待确认';
  2279. });
  2280. }
  2281. // 检查项目是否待审批
  2282. isPendingApproval(project: Project): boolean {
  2283. const stage = (project.currentStage || '').trim();
  2284. const data = (project as any).data || {};
  2285. return stage === '订单分配' && data.approvalStatus === 'pending';
  2286. }
  2287. // 🎯 待分配项目(支持中文和英文阶段名称)
  2288. get pendingAssignmentProjects(): Project[] {
  2289. return this.projects.filter(p => {
  2290. const stage = (p.currentStage || '').trim().toLowerCase();
  2291. return stage === 'pendingassignment' ||
  2292. stage === '待分配' ||
  2293. stage === '订单分配';
  2294. });
  2295. }
  2296. // 智能推荐设计师
  2297. private getRecommendedDesigner(projectType: 'soft' | 'hard') {
  2298. if (!this.designerProfiles || !this.designerProfiles.length) return null;
  2299. const scoreOf = (p: any) => {
  2300. const workloadScore = 100 - (p.workload ?? 0); // 负载越低越好
  2301. const ratingScore = (p.avgRating ?? 0) * 10; // 评分越高越好
  2302. const expScore = (p.experience ?? 0) * 5; // 经验越高越好
  2303. return workloadScore * 0.5 + ratingScore * 0.3 + expScore * 0.2;
  2304. };
  2305. const sorted = [...this.designerProfiles].sort((a, b) => scoreOf(b) - scoreOf(a));
  2306. return sorted[0] || null;
  2307. }
  2308. // 质量评审
  2309. reviewProjectQuality(projectId: string, rating: 'excellent' | 'qualified' | 'unqualified'): void {
  2310. const project = this.projects.find(p => p.id === projectId);
  2311. if (!project) return;
  2312. project.qualityRating = rating;
  2313. if (rating === 'unqualified') {
  2314. // 不合格:回退到修改阶段
  2315. project.currentStage = 'revision';
  2316. }
  2317. this.applyFilters();
  2318. window?.fmode?.alert('质量评审已提交');
  2319. }
  2320. // 查看绩效预警(占位:跳转到团队管理)
  2321. viewPerformanceDetails(): void {
  2322. this.router.navigate(['/team-leader/team-management']);
  2323. }
  2324. // 打开负载日历(占位:跳转到团队管理)
  2325. navigateToWorkloadCalendar(): void {
  2326. this.router.navigate(['/team-leader/workload-calendar']);
  2327. }
  2328. // 查看项目详情 - 跳转到纯净的项目详情页(无管理端UI)
  2329. viewProjectDetails(projectId: string): void {
  2330. if (!projectId) {
  2331. return;
  2332. }
  2333. // 获取公司ID
  2334. const cid = localStorage.getItem('company') || 'cDL6R1hgSi';
  2335. // 跳转到企微认证项目详情页(正确路由)
  2336. this.router.navigate(['/wxwork', cid, 'project', projectId]);
  2337. }
  2338. // 快速分配项目(增强:加入智能推荐)
  2339. async quickAssignProject(projectId: string): Promise<void> {
  2340. const project = this.projects.find(p => p.id === projectId);
  2341. if (!project) {
  2342. window?.fmode?.alert('未找到对应项目');
  2343. return;
  2344. }
  2345. const recommended = this.getRecommendedDesigner(project.type);
  2346. if (recommended) {
  2347. const reassigning = !!project.designerName;
  2348. const message = `推荐设计师:${recommended.name}(工作负载:${recommended.workload}%,评分:${recommended.avgRating}分)` +
  2349. (reassigning ? `\n\n该项目当前已由「${project.designerName}」负责,是否改为分配给「${recommended.name}」?` : '\n\n是否确认分配?');
  2350. const confirmAssign = await window?.fmode?.confirm(message);
  2351. if (confirmAssign) {
  2352. project.designerName = recommended.name;
  2353. if (project.currentStage === 'pendingAssignment' || project.currentStage === 'pendingApproval') {
  2354. project.currentStage = 'requirement';
  2355. }
  2356. project.status = '进行中';
  2357. // 更新设计师筛选列表
  2358. this.designers = Array.from(new Set(this.projects.map(p => p.designerName).filter(n => !!n)));
  2359. this.applyFilters();
  2360. window?.fmode?.alert(`项目已${reassigning ? '重新' : ''}分配给 ${recommended.name}`);
  2361. return;
  2362. }
  2363. }
  2364. // 无推荐或用户取消,跳转到详细分配页面
  2365. // 跳转到项目详情页
  2366. const cid = localStorage.getItem('company') || 'cDL6R1hgSi';
  2367. this.router.navigate(['/wxwork', cid, 'project', projectId]);
  2368. }
  2369. // 导航到待办任务
  2370. navigateToTask(task: TodoTask): void {
  2371. switch (task.type) {
  2372. case 'review':
  2373. this.router.navigate(['team-leader/quality-management', task.targetId]);
  2374. break;
  2375. case 'assign':
  2376. this.router.navigate(['/team-leader/dashboard']);
  2377. break;
  2378. case 'performance':
  2379. this.router.navigate(['team-leader/team-management']);
  2380. break;
  2381. }
  2382. }
  2383. // 获取优先级标签
  2384. getPriorityLabel(priority: 'high' | 'medium' | 'low'): string {
  2385. const labels: Record<'high' | 'medium' | 'low', string> = {
  2386. 'high': '紧急且重要',
  2387. 'medium': '重要不紧急',
  2388. 'low': '紧急不重要'
  2389. };
  2390. return labels[priority];
  2391. }
  2392. // 导航到团队管理
  2393. navigateToTeamManagement(): void {
  2394. this.router.navigate(['/team-leader/team-management']);
  2395. }
  2396. // 导航到项目评审
  2397. navigateToProjectReview(): void {
  2398. // 统一入口:跳转到项目列表/看板,而非旧评审页
  2399. this.router.navigate(['/team-leader/dashboard']);
  2400. }
  2401. // 导航到质量管理
  2402. navigateToQualityManagement(): void {
  2403. this.router.navigate(['/team-leader/quality-management']);
  2404. }
  2405. // 打开工作量预估工具(已迁移)
  2406. openWorkloadEstimator(): void {
  2407. // 工具迁移至详情页:引导前往当前选中项目详情
  2408. const cid = localStorage.getItem('company') || 'cDL6R1hgSi';
  2409. if (this.selectedProjectId) {
  2410. this.router.navigate(['/wxwork', cid, 'project', this.selectedProjectId]);
  2411. } else {
  2412. this.router.navigate(['/wxwork', cid, 'team-leader']);
  2413. }
  2414. window?.fmode?.alert('工作量预估工具已迁移至项目详情页,您可以在建模阶段之前使用该工具进行工作量计算。');
  2415. }
  2416. // 查看所有超期项目
  2417. viewAllOverdueProjects(): void {
  2418. this.filterByStatus('overdue');
  2419. this.closeAlert();
  2420. }
  2421. // 关闭提醒
  2422. closeAlert(): void {
  2423. this.showAlert = false;
  2424. }
  2425. resetStatusFilter(): void {
  2426. this.selectedStatus = 'all';
  2427. this.applyFilters();
  2428. }
  2429. // 处理甘特图员工点击事件
  2430. async onEmployeeClick(employeeName: string): Promise<void> {
  2431. if (!employeeName || employeeName === '未分配') {
  2432. return;
  2433. }
  2434. // 生成员工详情数据
  2435. this.selectedEmployeeDetail = await this.generateEmployeeDetail(employeeName);
  2436. this.showEmployeeDetailPanel = true;
  2437. }
  2438. // 生成员工详情数据
  2439. private async generateEmployeeDetail(employeeName: string): Promise<EmployeeDetail> {
  2440. // 从 ProjectTeam 表获取该员工负责的项目
  2441. const employeeProjects = this.designerWorkloadMap.get(employeeName) || [];
  2442. const currentProjects = employeeProjects.length;
  2443. // 保存完整的项目数据(最多显示3个)
  2444. const projectData = employeeProjects.slice(0, 3).map(p => ({
  2445. id: p.id,
  2446. name: p.name
  2447. }));
  2448. const projectNames = projectData.map(p => p.name); // 项目名称列表
  2449. // 获取该员工的请假记录(未来7天)
  2450. const today = new Date();
  2451. const next7Days = Array.from({ length: 7 }, (_, i) => {
  2452. const date = new Date(today);
  2453. date.setDate(today.getDate() + i);
  2454. return date.toISOString().split('T')[0]; // YYYY-MM-DD 格式
  2455. });
  2456. const employeeLeaveRecords = this.leaveRecords.filter(record =>
  2457. record.employeeName === employeeName && next7Days.includes(record.date)
  2458. );
  2459. // 生成红色标记说明
  2460. const redMarkExplanation = this.generateRedMarkExplanation(employeeName, employeeLeaveRecords, currentProjects);
  2461. // 保存当前员工信息和项目数据(用于切换月份)
  2462. this.currentEmployeeName = employeeName;
  2463. this.currentEmployeeProjects = employeeProjects;
  2464. // 生成日历数据
  2465. const calendarData = this.generateEmployeeCalendar(employeeName, employeeProjects);
  2466. // 新增:加载问卷数据
  2467. let surveyCompleted = false;
  2468. let surveyData = null;
  2469. let profileId = '';
  2470. try {
  2471. const Parse = await import('fmode-ng/parse').then(m => m.FmodeParse.with('nova'));
  2472. // 通过员工名字查找Profile(同时查询 realname 和 name 字段)
  2473. const realnameQuery = new Parse.Query('Profile');
  2474. realnameQuery.equalTo('realname', employeeName);
  2475. const nameQuery = new Parse.Query('Profile');
  2476. nameQuery.equalTo('name', employeeName);
  2477. // 使用 or 查询
  2478. const profileQuery = Parse.Query.or(realnameQuery, nameQuery);
  2479. profileQuery.limit(1);
  2480. const profileResults = await profileQuery.find();
  2481. console.log(`🔍 查找员工 ${employeeName},找到 ${profileResults.length} 个结果`);
  2482. if (profileResults.length > 0) {
  2483. const profile = profileResults[0];
  2484. profileId = profile.id;
  2485. surveyCompleted = profile.get('surveyCompleted') || false;
  2486. console.log(`📋 Profile ID: ${profileId}, surveyCompleted: ${surveyCompleted}`);
  2487. // 如果已完成问卷,加载问卷答案
  2488. if (surveyCompleted) {
  2489. const surveyQuery = new Parse.Query('SurveyLog');
  2490. surveyQuery.equalTo('profile', profile.toPointer());
  2491. surveyQuery.equalTo('type', 'survey-profile');
  2492. surveyQuery.descending('createdAt');
  2493. surveyQuery.limit(1);
  2494. const surveyResults = await surveyQuery.find();
  2495. console.log(`📝 找到 ${surveyResults.length} 条问卷记录`);
  2496. if (surveyResults.length > 0) {
  2497. const survey = surveyResults[0];
  2498. surveyData = {
  2499. answers: survey.get('answers') || [],
  2500. createdAt: survey.get('createdAt'),
  2501. updatedAt: survey.get('updatedAt')
  2502. };
  2503. console.log(`✅ 加载问卷数据成功,共 ${surveyData.answers.length} 道题`);
  2504. }
  2505. }
  2506. } else {
  2507. console.warn(`⚠️ 未找到员工 ${employeeName} 的 Profile`);
  2508. }
  2509. console.log(`📋 员工 ${employeeName} 问卷状态:`, surveyCompleted ? '已完成' : '未完成');
  2510. } catch (error) {
  2511. console.error(`❌ 加载员工 ${employeeName} 问卷数据失败:`, error);
  2512. }
  2513. return {
  2514. name: employeeName,
  2515. currentProjects,
  2516. projectNames,
  2517. projectData,
  2518. leaveRecords: employeeLeaveRecords,
  2519. redMarkExplanation,
  2520. calendarData,
  2521. // 新增字段
  2522. surveyCompleted,
  2523. surveyData,
  2524. profileId
  2525. };
  2526. }
  2527. /**
  2528. * 生成员工日历数据(支持指定月份)
  2529. */
  2530. private generateEmployeeCalendar(employeeName: string, employeeProjects: any[], targetMonth?: Date): EmployeeCalendarData {
  2531. const currentMonth = targetMonth || new Date();
  2532. const year = currentMonth.getFullYear();
  2533. const month = currentMonth.getMonth();
  2534. // 获取当月天数
  2535. const daysInMonth = new Date(year, month + 1, 0).getDate();
  2536. const days: EmployeeCalendarDay[] = [];
  2537. const today = new Date();
  2538. today.setHours(0, 0, 0, 0);
  2539. // 生成当月每一天的数据
  2540. for (let day = 1; day <= daysInMonth; day++) {
  2541. const date = new Date(year, month, day);
  2542. const dateStr = date.toISOString().split('T')[0];
  2543. // 找出该日期相关的项目(项目进行中且在当天范围内)
  2544. const dayProjects = employeeProjects.filter(p => {
  2545. // 处理 Parse Date 对象:检查是否有 toDate 方法
  2546. const getDate = (dateValue: any) => {
  2547. if (!dateValue) return null;
  2548. if (dateValue.toDate && typeof dateValue.toDate === 'function') {
  2549. return dateValue.toDate(); // Parse Date对象
  2550. }
  2551. if (dateValue instanceof Date) {
  2552. return dateValue;
  2553. }
  2554. return new Date(dateValue); // 字符串或时间戳
  2555. };
  2556. const deadlineDate = getDate(p.deadline);
  2557. const createdDate = p.createdAt ? getDate(p.createdAt) : null;
  2558. // 如果项目既没有 deadline 也没有 createdAt,则跳过
  2559. if (!deadlineDate && !createdDate) {
  2560. return false;
  2561. }
  2562. // 智能处理日期范围
  2563. let startDate: Date;
  2564. let endDate: Date;
  2565. if (deadlineDate && createdDate) {
  2566. // 情况1:两个日期都有
  2567. startDate = createdDate;
  2568. endDate = deadlineDate;
  2569. } else if (deadlineDate) {
  2570. // 情况2:只有deadline,往前推30天
  2571. startDate = new Date(deadlineDate.getTime() - 30 * 24 * 60 * 60 * 1000);
  2572. endDate = deadlineDate;
  2573. } else {
  2574. // 情况3:只有createdAt,往后推30天
  2575. startDate = createdDate!;
  2576. endDate = new Date(createdDate!.getTime() + 30 * 24 * 60 * 60 * 1000);
  2577. }
  2578. startDate.setHours(0, 0, 0, 0);
  2579. endDate.setHours(0, 0, 0, 0);
  2580. const inRange = date >= startDate && date <= endDate;
  2581. return inRange;
  2582. }).map(p => {
  2583. const getDate = (dateValue: any) => {
  2584. if (!dateValue) return undefined;
  2585. if (dateValue.toDate && typeof dateValue.toDate === 'function') {
  2586. return dateValue.toDate();
  2587. }
  2588. if (dateValue instanceof Date) {
  2589. return dateValue;
  2590. }
  2591. return new Date(dateValue);
  2592. };
  2593. return {
  2594. id: p.id,
  2595. name: p.name,
  2596. deadline: getDate(p.deadline)
  2597. };
  2598. });
  2599. days.push({
  2600. date,
  2601. projectCount: dayProjects.length,
  2602. projects: dayProjects,
  2603. isToday: date.getTime() === today.getTime(),
  2604. isCurrentMonth: true
  2605. });
  2606. }
  2607. // 补齐前后的日期(保证从周日开始)
  2608. const firstDay = new Date(year, month, 1);
  2609. const firstDayOfWeek = firstDay.getDay(); // 0=周日
  2610. // 前置补齐(上个月的日期)
  2611. for (let i = firstDayOfWeek - 1; i >= 0; i--) {
  2612. const date = new Date(year, month, -i);
  2613. days.unshift({
  2614. date,
  2615. projectCount: 0,
  2616. projects: [],
  2617. isToday: false,
  2618. isCurrentMonth: false
  2619. });
  2620. }
  2621. // 后置补齐(下个月的日期,保证总数是7的倍数)
  2622. const remainder = days.length % 7;
  2623. if (remainder !== 0) {
  2624. const needed = 7 - remainder;
  2625. for (let i = 1; i <= needed; i++) {
  2626. const date = new Date(year, month + 1, i);
  2627. days.push({
  2628. date,
  2629. projectCount: 0,
  2630. projects: [],
  2631. isToday: false,
  2632. isCurrentMonth: false
  2633. });
  2634. }
  2635. }
  2636. return {
  2637. currentMonth: new Date(year, month, 1),
  2638. days
  2639. };
  2640. }
  2641. /**
  2642. * 处理日历日期点击
  2643. */
  2644. onCalendarDayClick(day: EmployeeCalendarDay): void {
  2645. if (!day.isCurrentMonth || day.projectCount === 0) {
  2646. return;
  2647. }
  2648. this.selectedDate = day.date;
  2649. this.selectedDayProjects = day.projects;
  2650. this.showCalendarProjectList = true;
  2651. }
  2652. /**
  2653. * 切换员工日历月份
  2654. * @param direction -1=上月, 1=下月
  2655. */
  2656. changeEmployeeCalendarMonth(direction: number): void {
  2657. if (!this.selectedEmployeeDetail?.calendarData) {
  2658. return;
  2659. }
  2660. const currentMonth = this.selectedEmployeeDetail.calendarData.currentMonth;
  2661. const newMonth = new Date(currentMonth);
  2662. newMonth.setMonth(newMonth.getMonth() + direction);
  2663. // 重新生成日历数据
  2664. const newCalendarData = this.generateEmployeeCalendar(
  2665. this.currentEmployeeName,
  2666. this.currentEmployeeProjects,
  2667. newMonth
  2668. );
  2669. // 更新员工详情中的日历数据
  2670. this.selectedEmployeeDetail = {
  2671. ...this.selectedEmployeeDetail,
  2672. calendarData: newCalendarData
  2673. };
  2674. }
  2675. /**
  2676. * 关闭项目列表弹窗
  2677. */
  2678. closeCalendarProjectList(): void {
  2679. this.showCalendarProjectList = false;
  2680. this.selectedDate = null;
  2681. this.selectedDayProjects = [];
  2682. }
  2683. // 生成红色标记说明
  2684. private generateRedMarkExplanation(employeeName: string, leaveRecords: LeaveRecord[], projectCount: number): string {
  2685. const explanations: string[] = [];
  2686. // 检查请假情况
  2687. const leaveDays = leaveRecords.filter(record => record.isLeave);
  2688. if (leaveDays.length > 0) {
  2689. leaveDays.forEach(leave => {
  2690. const date = new Date(leave.date);
  2691. const dateStr = `${date.getMonth() + 1}月${date.getDate()}日`;
  2692. explanations.push(`${dateStr}(${leave.reason || '请假'})`);
  2693. });
  2694. }
  2695. // 检查项目繁忙情况
  2696. if (projectCount >= 3) {
  2697. const today = new Date();
  2698. const dateStr = `${today.getMonth() + 1}月${today.getDate()}日`;
  2699. explanations.push(`${dateStr}(${projectCount}个项目繁忙)`);
  2700. }
  2701. if (explanations.length === 0) {
  2702. return '当前无红色标记时段';
  2703. }
  2704. return `甘特图中红色时段说明:${explanations.map((exp, index) => `${index + 1}${exp}`).join(';')}`;
  2705. }
  2706. // 关闭员工详情面板
  2707. closeEmployeeDetailPanel(): void {
  2708. this.showEmployeeDetailPanel = false;
  2709. this.selectedEmployeeDetail = null;
  2710. this.showFullSurvey = false; // 重置问卷显示状态
  2711. }
  2712. /**
  2713. * 刷新员工问卷状态
  2714. */
  2715. async refreshEmployeeSurvey(): Promise<void> {
  2716. if (this.refreshingSurvey || !this.selectedEmployeeDetail) {
  2717. return;
  2718. }
  2719. try {
  2720. this.refreshingSurvey = true;
  2721. console.log('🔄 刷新问卷状态...');
  2722. const employeeName = this.selectedEmployeeDetail.name;
  2723. // 重新加载员工详情数据
  2724. const updatedDetail = await this.generateEmployeeDetail(employeeName);
  2725. // 更新当前显示的员工详情
  2726. this.selectedEmployeeDetail = updatedDetail;
  2727. console.log('✅ 问卷状态刷新成功');
  2728. } catch (error) {
  2729. console.error('❌ 刷新问卷状态失败:', error);
  2730. } finally {
  2731. this.refreshingSurvey = false;
  2732. }
  2733. }
  2734. /**
  2735. * 切换问卷显示模式
  2736. */
  2737. toggleSurveyDisplay(): void {
  2738. this.showFullSurvey = !this.showFullSurvey;
  2739. }
  2740. /**
  2741. * 获取能力画像摘要
  2742. */
  2743. getCapabilitySummary(answers: any[]): any {
  2744. const findAnswer = (questionId: string) => {
  2745. const item = answers.find(a => a.questionId === questionId);
  2746. return item?.answer;
  2747. };
  2748. const formatArray = (value: any): string => {
  2749. if (Array.isArray(value)) {
  2750. return value.join('、');
  2751. }
  2752. return value || '未填写';
  2753. };
  2754. return {
  2755. styles: formatArray(findAnswer('q1_expertise_styles')),
  2756. spaces: formatArray(findAnswer('q2_expertise_spaces')),
  2757. advantages: formatArray(findAnswer('q3_technical_advantages')),
  2758. difficulty: findAnswer('q5_project_difficulty') || '未填写',
  2759. capacity: findAnswer('q7_weekly_capacity') || '未填写',
  2760. urgent: findAnswer('q8_urgent_willingness') || '未填写',
  2761. urgentLimit: findAnswer('q8_urgent_limit') || '',
  2762. feedback: findAnswer('q9_progress_feedback') || '未填写',
  2763. communication: formatArray(findAnswer('q12_communication_methods'))
  2764. };
  2765. }
  2766. // 从员工详情面板跳转到项目详情
  2767. navigateToProjectFromPanel(projectId: string): void {
  2768. if (!projectId) {
  2769. return;
  2770. }
  2771. // 关闭员工详情面板
  2772. this.closeEmployeeDetailPanel();
  2773. // 跳转到项目详情页(使用纯净的wxwork路由)
  2774. const cid = localStorage.getItem('company') || 'cDL6R1hgSi';
  2775. this.router.navigate(['/wxwork', cid, 'project', projectId, 'order']);
  2776. }
  2777. // 获取请假类型显示文本
  2778. getLeaveTypeText(leaveType?: string): string {
  2779. const typeMap: Record<string, string> = {
  2780. 'sick': '病假',
  2781. 'personal': '事假',
  2782. 'annual': '年假',
  2783. 'other': '其他'
  2784. };
  2785. return typeMap[leaveType || ''] || '请假';
  2786. }
  2787. // 生成请假覆盖层数据
  2788. private generateLeaveOverlayData(categories: string[], xMin: number, xMax: number): any[] {
  2789. const DAY = 24 * 60 * 60 * 1000;
  2790. const overlayData: any[] = [];
  2791. categories.forEach((employeeName, yIndex) => {
  2792. // 获取该员工在时间范围内的请假记录
  2793. const employeeLeaves = this.leaveRecords.filter(record => {
  2794. if (record.employeeName !== employeeName || !record.isLeave) {
  2795. return false;
  2796. }
  2797. const recordDate = new Date(record.date).getTime();
  2798. return recordDate >= xMin && recordDate <= xMax;
  2799. });
  2800. // 为每个请假日期创建覆盖层
  2801. employeeLeaves.forEach(leave => {
  2802. const leaveDate = new Date(leave.date);
  2803. const startOfDay = new Date(leaveDate.getFullYear(), leaveDate.getMonth(), leaveDate.getDate()).getTime();
  2804. const endOfDay = startOfDay + DAY - 1;
  2805. overlayData.push({
  2806. name: `${employeeName} - ${this.getLeaveTypeText(leave.leaveType)}`,
  2807. value: [yIndex, startOfDay, endOfDay, employeeName, leave.leaveType, leave.reason],
  2808. itemStyle: {
  2809. color: 'rgba(239, 68, 68, 0.6)', // 半透明红色
  2810. borderColor: '#ef4444',
  2811. borderWidth: 1
  2812. }
  2813. });
  2814. });
  2815. // 检查项目繁忙情况,如果项目数>=3,也添加红色标记
  2816. const employeeProjects = this.designerWorkloadMap.get(employeeName) || [];
  2817. if (employeeProjects.length >= 3) {
  2818. // 在当前日期添加繁忙标记
  2819. const today = new Date();
  2820. const startOfToday = new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime();
  2821. const endOfToday = startOfToday + DAY - 1;
  2822. if (startOfToday >= xMin && startOfToday <= xMax) {
  2823. overlayData.push({
  2824. name: `${employeeName} - 项目繁忙(${employeeProjects.length}个项目)`,
  2825. value: [yIndex, startOfToday, endOfToday, employeeName, 'busy', `负责${employeeProjects.length}个项目`],
  2826. itemStyle: {
  2827. color: 'rgba(239, 68, 68, 0.4)', // 稍微透明的红色
  2828. borderColor: '#ef4444',
  2829. borderWidth: 1,
  2830. borderType: 'dashed' // 虚线边框区分请假和繁忙
  2831. }
  2832. });
  2833. }
  2834. }
  2835. });
  2836. return overlayData;
  2837. }
  2838. /**
  2839. * 加载用户Profile信息
  2840. */
  2841. async loadUserProfile(): Promise<void> {
  2842. try {
  2843. const cid = localStorage.getItem("company");
  2844. if (!cid) {
  2845. console.warn('未找到公司ID,使用默认用户信息');
  2846. return;
  2847. }
  2848. const wwAuth = new WxworkAuth({ cid });
  2849. const profile = await wwAuth.currentProfile();
  2850. if (profile) {
  2851. const name = profile.get("name") || profile.get("mobile") || '组长';
  2852. const avatar = profile.get("avatar");
  2853. const roleName = profile.get("roleName") || '组长';
  2854. this.currentUser = {
  2855. name,
  2856. avatar: avatar || this.generateDefaultAvatar(name),
  2857. roleName
  2858. };
  2859. console.log('用户Profile加载成功:', this.currentUser);
  2860. }
  2861. } catch (error) {
  2862. console.error('加载用户Profile失败:', error);
  2863. // 保持默认值
  2864. }
  2865. }
  2866. /**
  2867. * 生成默认头像(SVG格式)
  2868. * @param name 用户名
  2869. * @returns Base64编码的SVG数据URL
  2870. */
  2871. generateDefaultAvatar(name: string): string {
  2872. const initial = name ? name.substring(0, 2).toUpperCase() : '组长';
  2873. const bgColor = '#CCFFCC';
  2874. const textColor = '#555555';
  2875. const svg = `<svg width='40' height='40' xmlns='http://www.w3.org/2000/svg'>
  2876. <rect width='100%' height='100%' fill='${bgColor}'/>
  2877. <text x='50%' y='50%' font-family='Arial' font-size='13.333333333333334' font-weight='bold' text-anchor='middle' fill='${textColor}' dy='0.3em'>${initial}</text>
  2878. </svg>`;
  2879. return `data:image/svg+xml,${encodeURIComponent(svg)}`;
  2880. }
  2881. // ==================== 新增:待办任务相关方法 ====================
  2882. /**
  2883. * 从问题板块加载待办任务
  2884. */
  2885. async loadTodoTasksFromIssues(): Promise<void> {
  2886. this.loadingTodoTasks = true;
  2887. this.todoTaskError = '';
  2888. try {
  2889. const Parse: any = FmodeParse.with('nova');
  2890. const query = new Parse.Query('ProjectIssue');
  2891. // 筛选条件:待处理 + 处理中
  2892. query.containedIn('status', ['待处理', '处理中']);
  2893. query.notEqualTo('isDeleted', true);
  2894. // 关联数据
  2895. query.include(['project', 'creator', 'assignee']);
  2896. // 排序:更新时间倒序
  2897. query.descending('updatedAt');
  2898. // 限制数量
  2899. query.limit(50);
  2900. const results = await query.find();
  2901. console.log(`📥 查询到 ${results.length} 条问题记录`);
  2902. // 数据转换(异步处理以支持 fetch)
  2903. const tasks = await Promise.all(results.map(async (obj: any) => {
  2904. let project = obj.get('project');
  2905. const assignee = obj.get('assignee');
  2906. const creator = obj.get('creator');
  2907. const data = obj.get('data') || {};
  2908. let projectName = '未知项目';
  2909. let projectId = '';
  2910. // 如果 project 存在,尝试获取完整数据
  2911. if (project) {
  2912. projectId = project.id;
  2913. // 尝试从已加载的对象获取 name
  2914. projectName = project.get('name');
  2915. // 如果 name 为空,使用 Parse.Query 查询项目
  2916. if (!projectName && projectId) {
  2917. try {
  2918. console.log(`🔄 查询项目数据: ${projectId}`);
  2919. const projectQuery = new Parse.Query('Project');
  2920. const fetchedProject = await projectQuery.get(projectId);
  2921. projectName = fetchedProject.get('name') || fetchedProject.get('title') || '未知项目';
  2922. console.log(`✅ 项目名称: ${projectName}`);
  2923. } catch (error) {
  2924. console.warn(`⚠️ 无法加载项目 ${projectId}:`, error);
  2925. projectName = `项目-${projectId.slice(0, 6)}`;
  2926. }
  2927. }
  2928. } else {
  2929. console.warn('⚠️ 问题缺少关联项目:', {
  2930. issueId: obj.id,
  2931. title: obj.get('title')
  2932. });
  2933. }
  2934. return {
  2935. id: obj.id,
  2936. title: obj.get('title') || obj.get('description')?.slice(0, 40) || '未命名问题',
  2937. description: obj.get('description'),
  2938. priority: obj.get('priority') as IssuePriority || 'medium',
  2939. type: obj.get('issueType') as IssueType || 'task',
  2940. status: this.zh2enStatus(obj.get('status')) as IssueStatus,
  2941. projectId,
  2942. projectName,
  2943. relatedSpace: obj.get('relatedSpace') || data.relatedSpace,
  2944. relatedStage: obj.get('relatedStage') || data.relatedStage,
  2945. assigneeName: assignee?.get('name') || assignee?.get('realname') || '未指派',
  2946. creatorName: creator?.get('name') || creator?.get('realname') || '未知',
  2947. createdAt: obj.createdAt || new Date(),
  2948. updatedAt: obj.updatedAt || new Date(),
  2949. dueDate: obj.get('dueDate'),
  2950. tags: (data.tags || []) as string[]
  2951. };
  2952. }));
  2953. this.todoTasksFromIssues = tasks;
  2954. // 排序:优先级 -> 时间
  2955. this.todoTasksFromIssues.sort((a, b) => {
  2956. const priorityA = this.getPriorityOrder(a.priority);
  2957. const priorityB = this.getPriorityOrder(b.priority);
  2958. if (priorityA !== priorityB) {
  2959. return priorityA - priorityB;
  2960. }
  2961. return +new Date(b.updatedAt) - +new Date(a.updatedAt);
  2962. });
  2963. console.log(`✅ 加载待办任务成功,共 ${this.todoTasksFromIssues.length} 条`);
  2964. } catch (error) {
  2965. console.error('❌ 加载待办任务失败:', error);
  2966. this.todoTaskError = '加载失败,请稍后重试';
  2967. } finally {
  2968. this.loadingTodoTasks = false;
  2969. }
  2970. }
  2971. /**
  2972. * 启动自动刷新(每5分钟)
  2973. */
  2974. startAutoRefresh(): void {
  2975. this.todoTaskRefreshTimer = setInterval(() => {
  2976. console.log('🔄 自动刷新待办任务...');
  2977. this.loadTodoTasksFromIssues();
  2978. }, 5 * 60 * 1000); // 5分钟
  2979. }
  2980. /**
  2981. * 手动刷新待办任务
  2982. */
  2983. refreshTodoTasks(): void {
  2984. console.log('🔄 手动刷新待办任务...');
  2985. this.loadTodoTasksFromIssues();
  2986. }
  2987. /**
  2988. * 跳转到项目问题详情
  2989. */
  2990. navigateToIssue(task: TodoTaskFromIssue): void {
  2991. const cid = localStorage.getItem('company') || 'cDL6R1hgSi';
  2992. // 跳转到项目详情页,并打开问题板块
  2993. this.router.navigate(
  2994. ['/wxwork', cid, 'project', task.projectId, 'order'],
  2995. {
  2996. queryParams: {
  2997. openIssues: 'true',
  2998. highlightIssue: task.id
  2999. }
  3000. }
  3001. );
  3002. }
  3003. /**
  3004. * 标记问题为已读
  3005. */
  3006. async markAsRead(task: TodoTaskFromIssue): Promise<void> {
  3007. try {
  3008. // 方式1: 本地隐藏(不修改数据库)
  3009. this.todoTasksFromIssues = this.todoTasksFromIssues.filter(t => t.id !== task.id);
  3010. console.log(`✅ 标记问题为已读: ${task.title}`);
  3011. } catch (error) {
  3012. console.error('❌ 标记已读失败:', error);
  3013. }
  3014. }
  3015. /**
  3016. * 获取优先级配置
  3017. */
  3018. getPriorityConfig(priority: IssuePriority): { label: string; icon: string; color: string; order: number } {
  3019. const config: Record<IssuePriority, { label: string; icon: string; color: string; order: number }> = {
  3020. urgent: { label: '紧急', icon: '🔴', color: '#dc2626', order: 0 },
  3021. critical: { label: '紧急', icon: '🔴', color: '#dc2626', order: 0 },
  3022. high: { label: '高', icon: '🟠', color: '#ea580c', order: 1 },
  3023. medium: { label: '中', icon: '🟡', color: '#ca8a04', order: 2 },
  3024. low: { label: '低', icon: '⚪', color: '#9ca3af', order: 3 }
  3025. };
  3026. return config[priority] || config.medium;
  3027. }
  3028. getPriorityOrder(priority: IssuePriority): number {
  3029. return this.getPriorityConfig(priority).order;
  3030. }
  3031. /**
  3032. * 获取问题类型中文名
  3033. */
  3034. getIssueTypeLabel(type: IssueType): string {
  3035. const map: Record<IssueType, string> = {
  3036. bug: '问题',
  3037. task: '任务',
  3038. feedback: '反馈',
  3039. risk: '风险',
  3040. feature: '需求'
  3041. };
  3042. return map[type] || '任务';
  3043. }
  3044. /**
  3045. * 格式化相对时间(精确到秒)
  3046. */
  3047. formatRelativeTime(date: Date | string): string {
  3048. if (!date) {
  3049. return '未知时间';
  3050. }
  3051. try {
  3052. const targetDate = new Date(date);
  3053. const now = new Date();
  3054. const diff = now.getTime() - targetDate.getTime();
  3055. const seconds = Math.floor(diff / 1000);
  3056. const minutes = Math.floor(seconds / 60);
  3057. const hours = Math.floor(minutes / 60);
  3058. const days = Math.floor(hours / 24);
  3059. if (seconds < 10) {
  3060. return '刚刚';
  3061. } else if (seconds < 60) {
  3062. return `${seconds}秒前`;
  3063. } else if (minutes < 60) {
  3064. return `${minutes}分钟前`;
  3065. } else if (hours < 24) {
  3066. return `${hours}小时前`;
  3067. } else if (days < 7) {
  3068. return `${days}天前`;
  3069. } else {
  3070. return targetDate.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
  3071. }
  3072. } catch (error) {
  3073. console.error('❌ formatRelativeTime 错误:', error, 'date:', date);
  3074. return '时间格式错误';
  3075. }
  3076. }
  3077. /**
  3078. * 格式化精确时间(用于 tooltip)
  3079. * 格式:YYYY-MM-DD HH:mm:ss
  3080. */
  3081. formatExactTime(date: Date | string): string {
  3082. if (!date) {
  3083. return '未知时间';
  3084. }
  3085. try {
  3086. const d = new Date(date);
  3087. const year = d.getFullYear();
  3088. const month = String(d.getMonth() + 1).padStart(2, '0');
  3089. const day = String(d.getDate()).padStart(2, '0');
  3090. const hours = String(d.getHours()).padStart(2, '0');
  3091. const minutes = String(d.getMinutes()).padStart(2, '0');
  3092. const seconds = String(d.getSeconds()).padStart(2, '0');
  3093. return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  3094. } catch (error) {
  3095. console.error('❌ formatExactTime 错误:', error, 'date:', date);
  3096. return '时间格式错误';
  3097. }
  3098. }
  3099. /**
  3100. * 状态映射(中文 -> 英文)
  3101. */
  3102. private zh2enStatus(status: string): IssueStatus {
  3103. const map: Record<string, IssueStatus> = {
  3104. '待处理': 'open',
  3105. '处理中': 'in_progress',
  3106. '已解决': 'resolved',
  3107. '已关闭': 'closed'
  3108. };
  3109. return map[status] || 'open';
  3110. }
  3111. }