dashboard.ts 109 KB

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