| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152 |
- import { CommonModule } from '@angular/common';
- import { FormsModule } from '@angular/forms';
- import { Router, RouterModule } from '@angular/router';
- import { Component, OnInit, OnDestroy, ElementRef, ViewChild } from '@angular/core';
- import { ProjectService } from '../../../services/project.service';
- import { DesignerService } from '../services/designer.service';
- import { WxworkAuth } from 'fmode-ng/core';
- // 项目阶段定义
- interface ProjectStage {
- id: string;
- name: string;
- order: number;
- }
- interface ProjectPhase {
- name: string;
- percentage: number;
- startPercentage: number;
- isCompleted: boolean;
- isCurrent: boolean;
- }
- interface Project {
- id: string;
- name: string;
- type: 'soft' | 'hard';
- memberType: 'vip' | 'normal';
- designerName: string;
- status: string;
- expectedEndDate: Date; // TODO: 兼容旧字段,后续可移除
- deadline: Date; // 真实截止时间字段
- createdAt?: Date; // 真实开始时间字段(可选)
- isOverdue: boolean;
- overdueDays: number;
- dueSoon: boolean;
- urgency: 'high' | 'medium' | 'low';
- phases: ProjectPhase[];
- currentStage: string; // 新增:当前项目阶段
- // 新增:质量评级
- qualityRating?: 'excellent' | 'qualified' | 'unqualified' | 'pending';
- lastCustomerFeedback?: string;
- // 预构建的搜索索引,减少重复 toLowerCase 与拼接
- searchIndex?: string;
- }
- interface TodoTask {
- id: string;
- title: string;
- description: string;
- deadline: Date;
- priority: 'high' | 'medium' | 'low';
- type: 'review' | 'assign' | 'performance';
- targetId: string;
- }
- // 员工请假记录接口
- interface LeaveRecord {
- id: string;
- employeeName: string;
- date: string; // YYYY-MM-DD 格式
- isLeave: boolean;
- leaveType?: 'sick' | 'personal' | 'annual' | 'other'; // 请假类型
- reason?: string; // 请假原因
- }
- // 员工详情面板数据接口
- interface EmployeeDetail {
- name: string;
- currentProjects: number; // 当前负责项目数
- projectNames: string[]; // 项目名称列表(用于显示)
- projectData: Array<{ id: string; name: string }>; // 项目数据(包含ID和名称,用于跳转)
- leaveRecords: LeaveRecord[]; // 未来7天请假记录
- redMarkExplanation: string; // 红色标记说明
- calendarData?: EmployeeCalendarData; // 负载日历数据
- // 新增:问卷相关
- surveyCompleted?: boolean; // 是否完成问卷
- surveyData?: any; // 问卷答案数据
- profileId?: string; // Profile ID
- }
- // 员工日历数据接口
- interface EmployeeCalendarData {
- currentMonth: Date;
- days: EmployeeCalendarDay[];
- }
- // 日历日期数据
- interface EmployeeCalendarDay {
- date: Date;
- projectCount: number; // 当天项目数量
- projects: Array<{ id: string; name: string; deadline?: Date }>; // 项目列表
- isToday: boolean;
- isCurrentMonth: boolean;
- }
- declare const echarts: any;
- @Component({
- selector: 'app-dashboard',
- standalone: true,
- imports: [CommonModule, FormsModule, RouterModule],
- templateUrl: './dashboard.html',
- styleUrl: './dashboard.scss'
- })
- export class Dashboard implements OnInit, OnDestroy {
- // 暴露 Array 给模板使用
- Array = Array;
-
- projects: Project[] = [];
- filteredProjects: Project[] = [];
- todoTasks: TodoTask[] = [];
- urgentPinnedProjects: Project[] = [];
- showAlert: boolean = false;
- selectedProjectId: string = '';
-
- // 新增:当前用户信息
- currentUser = {
- name: '组长',
- 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",
- roleName: '组长'
- };
- currentDate = new Date();
-
- // 真实设计师数据(从fmode-ng获取)
- realDesigners: any[] = [];
-
- // 设计师工作量映射(从 ProjectTeam 表)
- designerWorkloadMap: Map<string, any[]> = new Map(); // designerId/name -> projects[]
-
- // 智能推荐相关
- showSmartMatch: boolean = false;
- selectedProject: any = null;
- recommendations: any[] = [];
- // 新增:关键词搜索
- searchTerm: string = '';
- searchSuggestions: Project[] = [];
- showSuggestions: boolean = false;
- private hideSuggestionsTimer: any;
-
- // 搜索性能与交互控制
- private searchDebounceTimer: any;
- private readonly SEARCH_DEBOUNCE_MS = 200; // 防抖时长(毫秒)
- private readonly MIN_SEARCH_LEN = 2; // 最小触发建议长度
- private readonly MAX_SUGGESTIONS = 8; // 建议最大条数
- private isSearchFocused: boolean = false; // 是否处于输入聚焦态
- // 新增:临期项目与筛选状态
- selectedType: 'all' | 'soft' | 'hard' = 'all';
- selectedUrgency: 'all' | 'high' | 'medium' | 'low' = 'all';
- selectedStatus: 'all' | 'progress' | 'completed' | 'overdue' | 'pendingApproval' | 'pendingAssignment' | 'dueSoon' = 'all';
- selectedDesigner: string = 'all';
- selectedMemberType: 'all' | 'vip' | 'normal' = 'all';
- // 新增:时间窗筛选
- selectedTimeWindow: 'all' | 'today' | 'threeDays' | 'sevenDays' = 'all';
- designers: string[] = [];
- // 新增:四大板块筛选
- selectedCorePhase: 'all' | 'order' | 'requirements' | 'delivery' | 'aftercare' = 'all';
-
- // 设计师画像(从fmode-ng动态获取,保留此字段作为兼容)
- designerProfiles: any[] = [];
- // 10个项目阶段
- projectStages: ProjectStage[] = [
- { id: 'pendingApproval', name: '待确认', order: 1 },
- { id: 'pendingAssignment', name: '待分配', order: 2 },
- { id: 'requirement', name: '需求沟通', order: 3 },
- { id: 'planning', name: '方案规划', order: 4 },
- { id: 'modeling', name: '建模阶段', order: 5 },
- { id: 'rendering', name: '渲染阶段', order: 6 },
- { id: 'postProduction', name: '后期处理', order: 7 },
- { id: 'review', name: '方案评审', order: 8 },
- { id: 'revision', name: '方案修改', order: 9 },
- { id: 'delivery', name: '交付完成', order: 10 }
- ];
- // 5大核心阶段(聚合展示)
- corePhases: ProjectStage[] = [
- { id: 'order', name: '订单分配', order: 1 }, // 待确认、待分配
- { id: 'requirements', name: '确认需求', order: 2 }, // 需求沟通、方案规划
- { id: 'delivery', name: '交付执行', order: 3 }, // 建模、渲染、后期/评审/修改
- { id: 'aftercare', name: '售后', order: 4 } // 交付完成 → 售后
- ];
- // 甘特视图开关与实例引用
- showGanttView: boolean = false;
- private ganttChart: any | null = null;
- @ViewChild('ganttChartRef', { static: false }) ganttChartRef!: ElementRef<HTMLDivElement>;
- // 工作负载甘特图引用
- @ViewChild('workloadGanttContainer', { static: false }) workloadGanttContainer!: ElementRef<HTMLDivElement>;
- private workloadGanttChart: any | null = null;
- workloadGanttScale: 'week' | 'month' = 'week';
- // 甘特时间尺度:仅周/月
- ganttScale: 'day' | 'week' | 'month' = 'week';
- // 新增:甘特模式(项目 / 设计师排班)
- ganttMode: 'project' | 'designer' = 'project';
- // 个人详情面板相关属性
- showEmployeeDetailPanel: boolean = false;
- selectedEmployeeDetail: EmployeeDetail | null = null;
- refreshingSurvey: boolean = false; // 新增:刷新问卷状态
- showFullSurvey: boolean = false; // 新增:是否显示完整问卷
-
- // 日历项目列表弹窗
- showCalendarProjectList: boolean = false;
- selectedDayProjects: Array<{ id: string; name: string; deadline?: Date }> = [];
- selectedDate: Date | null = null;
-
- // 员工请假数据(模拟数据)
- private leaveRecords: LeaveRecord[] = [
- { id: '1', employeeName: '张三', date: '2024-01-20', isLeave: true, leaveType: 'personal', reason: '事假' },
- { id: '2', employeeName: '张三', date: '2024-01-21', isLeave: false },
- { id: '3', employeeName: '张三', date: '2024-01-22', isLeave: false },
- { id: '4', employeeName: '张三', date: '2024-01-23', isLeave: false },
- { id: '5', employeeName: '张三', date: '2024-01-24', isLeave: false },
- { id: '6', employeeName: '张三', date: '2024-01-25', isLeave: false },
- { id: '7', employeeName: '张三', date: '2024-01-26', isLeave: false },
-
- { id: '8', employeeName: '李四', date: '2024-01-20', isLeave: false },
- { id: '9', employeeName: '李四', date: '2024-01-21', isLeave: true, leaveType: 'sick', reason: '病假' },
- { id: '10', employeeName: '李四', date: '2024-01-22', isLeave: true, leaveType: 'sick', reason: '病假' },
- { id: '11', employeeName: '李四', date: '2024-01-23', isLeave: false },
- { id: '12', employeeName: '李四', date: '2024-01-24', isLeave: false },
- { id: '13', employeeName: '李四', date: '2024-01-25', isLeave: false },
- { id: '14', employeeName: '李四', date: '2024-01-26', isLeave: false },
-
- { id: '15', employeeName: '王五', date: '2024-01-20', isLeave: false },
- { id: '16', employeeName: '王五', date: '2024-01-21', isLeave: false },
- { id: '17', employeeName: '王五', date: '2024-01-22', isLeave: false },
- { id: '18', employeeName: '王五', date: '2024-01-23', isLeave: true, leaveType: 'annual', reason: '年假' },
- { id: '19', employeeName: '王五', date: '2024-01-24', isLeave: false },
- { id: '20', employeeName: '王五', date: '2024-01-25', isLeave: false },
- { id: '21', employeeName: '王五', date: '2024-01-26', isLeave: false },
-
- { id: '22', employeeName: '赵六', date: '2024-01-20', isLeave: false },
- { id: '23', employeeName: '赵六', date: '2024-01-21', isLeave: false },
- { id: '24', employeeName: '赵六', date: '2024-01-22', isLeave: false },
- { id: '25', employeeName: '赵六', date: '2024-01-23', isLeave: false },
- { id: '26', employeeName: '赵六', date: '2024-01-24', isLeave: false },
- { id: '27', employeeName: '赵六', date: '2024-01-25', isLeave: false },
- { id: '28', employeeName: '赵六', date: '2024-01-26', isLeave: false }
- ];
- constructor(
- private projectService: ProjectService,
- private router: Router,
- private designerService: DesignerService
- ) {}
- async ngOnInit(): Promise<void> {
- // 新增:加载用户Profile信息
- await this.loadUserProfile();
-
- await this.loadProjects();
- await this.loadDesigners();
- this.loadTodoTasks();
- // 首次微任务后尝试初始化一次,确保容器已渲染
- setTimeout(() => this.updateWorkloadGantt(), 0);
- }
- /**
- * 从fmode-ng加载真实设计师数据
- */
- async loadDesigners(): Promise<void> {
- try {
- this.realDesigners = await this.designerService.getDesigners();
- // 更新设计师列表(用于筛选下拉框)
- this.designers = this.realDesigners.map(d => d.name);
- // 同时更新designerProfiles以保持兼容性
- this.designerProfiles = this.realDesigners.map(d => ({
- id: d.id,
- name: d.name,
- skills: d.tags.expertise.styles || [],
- workload: 0, // 后续动态计算
- avgRating: d.tags.history.avgRating || 0,
- experience: 0 // 暂无此字段
- }));
-
- // 加载设计师的实际工作量
- await this.loadDesignerWorkload();
- } catch (error) {
- console.error('加载设计师数据失败:', error);
- }
- }
-
- /**
- * 🔧 从 ProjectTeam 表加载每个设计师的实际工作量
- */
- async loadDesignerWorkload(): Promise<void> {
- try {
- const Parse = await import('fmode-ng/parse').then(m => m.FmodeParse.with('nova'));
-
- // 查询所有 ProjectTeam 记录
- const cid = localStorage.getItem('company') || 'cDL6R1hgSi';
-
- // 先查询当前公司的所有项目
- const projectQuery = new Parse.Query('Project');
- projectQuery.equalTo('company', cid);
- projectQuery.notEqualTo('isDeleted', true);
-
- // 查询当前公司项目的 ProjectTeam
- const teamQuery = new Parse.Query('ProjectTeam');
- teamQuery.matchesQuery('project', projectQuery);
- teamQuery.notEqualTo('isDeleted', true);
- teamQuery.include('project');
- teamQuery.include('profile');
- teamQuery.limit(1000);
-
- const teamRecords = await teamQuery.find();
-
- // 如果 ProjectTeam 表为空,使用降级方案
- if (teamRecords.length === 0) {
- await this.loadDesignerWorkloadFromProjects();
- return;
- }
-
- // 构建设计师工作量映射
- this.designerWorkloadMap.clear();
-
- teamRecords.forEach((record: any) => {
- const profile = record.get('profile');
- const project = record.get('project');
-
- if (!profile || !project) {
- return;
- }
-
- const profileId = profile.id;
- const profileName = profile.get('name') || profile.get('user')?.get?.('name') || `设计师-${profileId.slice(-4)}`;
-
- // 提取项目信息
- // 优先获取各个日期字段
- const createdAtValue = project.get('createdAt');
- const updatedAtValue = project.get('updatedAt');
- const deadlineValue = project.get('deadline');
- const deliveryDateValue = project.get('deliveryDate');
- const expectedDeliveryDateValue = project.get('expectedDeliveryDate');
-
- // 🔧 如果 get() 方法都返回假值,尝试从 createdAt/updatedAt 属性直接获取
- // Parse 对象的 createdAt/updatedAt 是内置属性
- let finalCreatedAt = createdAtValue || updatedAtValue;
- if (!finalCreatedAt && project.createdAt) {
- finalCreatedAt = project.createdAt; // Parse 内置属性
- }
- if (!finalCreatedAt && project.updatedAt) {
- finalCreatedAt = project.updatedAt; // Parse 内置属性
- }
-
- const projectData = {
- id: project.id,
- name: project.get('title') || '未命名项目',
- status: project.get('status') || '进行中',
- currentStage: project.get('currentStage') || '未知阶段',
- deadline: deadlineValue || deliveryDateValue || expectedDeliveryDateValue,
- createdAt: finalCreatedAt,
- designerName: profileName
- };
-
- // 添加到映射 (by ID)
- if (!this.designerWorkloadMap.has(profileId)) {
- this.designerWorkloadMap.set(profileId, []);
- }
- this.designerWorkloadMap.get(profileId)!.push(projectData);
-
- // 同时建立 name -> projects 的映射(用于甘特图)
- if (!this.designerWorkloadMap.has(profileName)) {
- this.designerWorkloadMap.set(profileName, []);
- }
- this.designerWorkloadMap.get(profileName)!.push(projectData);
- });
-
- } catch (error) {
- console.error('加载设计师工作量失败:', error);
- }
- }
-
- /**
- * 🔧 降级方案:从 Project.assignee 统计工作量
- * 当 ProjectTeam 表为空时使用
- */
- async loadDesignerWorkloadFromProjects(): Promise<void> {
- try {
- const Parse = await import('fmode-ng/parse').then(m => m.FmodeParse.with('nova'));
- const cid = localStorage.getItem('company') || 'cDL6R1hgSi';
-
- // 查询所有项目
- const projectQuery = new Parse.Query('Project');
- projectQuery.equalTo('company', cid);
- projectQuery.equalTo('isDeleted', false);
- projectQuery.include('assignee');
- projectQuery.include('department');
- projectQuery.limit(1000);
-
- const projects = await projectQuery.find();
-
- // 构建设计师工作量映射
- this.designerWorkloadMap.clear();
-
- projects.forEach((project: any) => {
- const assignee = project.get('assignee');
- if (!assignee) return;
-
- // 只统计组员角色的项目
- const assigneeRole = assignee.get('roleName');
- if (assigneeRole !== '组员') {
- return;
- }
-
- const assigneeName = assignee.get('name') || assignee.get('user')?.get?.('name') || `设计师-${assignee.id.slice(-4)}`;
-
- // 提取项目信息
- // 优先获取各个日期字段
- const createdAtValue = project.get('createdAt');
- const updatedAtValue = project.get('updatedAt');
- const deadlineValue = project.get('deadline');
- const deliveryDateValue = project.get('deliveryDate');
- const expectedDeliveryDateValue = project.get('expectedDeliveryDate');
-
- // 🔧 如果 get() 方法都返回假值,尝试从 createdAt/updatedAt 属性直接获取
- let finalCreatedAt = createdAtValue || updatedAtValue;
- if (!finalCreatedAt && project.createdAt) {
- finalCreatedAt = project.createdAt;
- }
- if (!finalCreatedAt && project.updatedAt) {
- finalCreatedAt = project.updatedAt;
- }
-
- const projectData = {
- id: project.id,
- name: project.get('title') || '未命名项目',
- status: project.get('status') || '进行中',
- currentStage: project.get('currentStage') || '未知阶段',
- deadline: deadlineValue || deliveryDateValue || expectedDeliveryDateValue,
- createdAt: finalCreatedAt,
- designerName: assigneeName
- };
-
- // 添加到映射
- if (!this.designerWorkloadMap.has(assigneeName)) {
- this.designerWorkloadMap.set(assigneeName, []);
- }
- this.designerWorkloadMap.get(assigneeName)!.push(projectData);
- });
-
- } catch (error) {
- console.error('[降级方案] 加载工作量失败:', error);
- }
- }
- /**
- * 从fmode-ng加载真实项目数据
- */
- async loadProjects(): Promise<void> {
- try {
- const realProjects = await this.designerService.getProjects();
-
- // 如果有真实数据,使用真实数据
- if (realProjects && realProjects.length > 0) {
- this.projects = realProjects;
- } else {
- // 如果没有真实数据,使用模拟数据
- this.projects = this.getMockProjects();
- }
- } catch (error) {
- console.error('加载项目数据失败:', error);
- this.projects = this.getMockProjects();
- }
-
- // 应用筛选
- this.applyFilters();
- }
-
- /**
- * 构建搜索索引(如果需要)
- */
- private buildSearchIndexes(): void {
- this.projects.forEach(p => {
- if (!p.searchIndex) {
- p.searchIndex = `${p.name}|${p.designerName}`.toLowerCase();
- }
- });
- }
- /**
- * 模拟项目数据(作为备用)
- */
- private getMockProjects(): Project[] {
- return [
- {
- id: 'proj-001',
- name: '现代风格客厅设计',
- type: 'soft',
- memberType: 'vip',
- designerName: '张三',
- status: '进行中',
- expectedEndDate: new Date(2023, 9, 15),
- deadline: new Date(2023, 9, 15),
- isOverdue: true,
- overdueDays: 2,
- dueSoon: false,
- urgency: 'high',
- currentStage: 'rendering',
- phases: [
- { name: '建模', percentage: 15, startPercentage: 0, isCompleted: true, isCurrent: false },
- { name: '渲染', percentage: 20, startPercentage: 15, isCompleted: false, isCurrent: true },
- { name: '后期', percentage: 15, startPercentage: 35, isCompleted: false, isCurrent: false },
- { name: '交付', percentage: 50, startPercentage: 50, isCompleted: false, isCurrent: false }
- ]
- },
- {
- id: 'proj-002',
- name: '北欧风格卧室设计',
- type: 'soft',
- memberType: 'normal',
- designerName: '李四',
- status: '进行中',
- expectedEndDate: new Date(2023, 9, 20),
- deadline: new Date(2023, 9, 20),
- isOverdue: false,
- overdueDays: 0,
- dueSoon: false,
- urgency: 'medium',
- currentStage: 'postProduction',
- phases: [
- { name: '建模', percentage: 15, startPercentage: 0, isCompleted: true, isCurrent: false },
- { name: '渲染', percentage: 20, startPercentage: 15, isCompleted: true, isCurrent: false },
- { name: '后期', percentage: 15, startPercentage: 35, isCompleted: false, isCurrent: true },
- { name: '交付', percentage: 50, startPercentage: 50, isCompleted: false, isCurrent: false }
- ]
- },
- {
- id: 'proj-003',
- name: '新中式餐厅设计',
- type: 'hard',
- memberType: 'normal',
- designerName: '王五',
- status: '进行中',
- expectedEndDate: new Date(2023, 9, 25),
- deadline: new Date(2023, 9, 25),
- isOverdue: false,
- overdueDays: 0,
- dueSoon: false,
- urgency: 'low',
- currentStage: 'modeling',
- phases: [
- { name: '建模', percentage: 15, startPercentage: 0, isCompleted: false, isCurrent: true },
- { name: '渲染', percentage: 20, startPercentage: 15, isCompleted: false, isCurrent: false },
- { name: '后期', percentage: 15, startPercentage: 35, isCompleted: false, isCurrent: false },
- { name: '交付', percentage: 50, startPercentage: 50, isCompleted: false, isCurrent: false }
- ]
- },
- {
- id: 'proj-004',
- name: '工业风办公室设计',
- type: 'hard',
- memberType: 'normal',
- designerName: '赵六',
- status: '进行中',
- expectedEndDate: new Date(2023, 9, 10),
- deadline: new Date(2023, 9, 10),
- isOverdue: true,
- overdueDays: 7,
- dueSoon: false,
- urgency: 'high',
- currentStage: 'review',
- phases: [
- { name: '建模', percentage: 15, startPercentage: 0, isCompleted: true, isCurrent: false },
- { name: '渲染', percentage: 20, startPercentage: 15, isCompleted: true, isCurrent: false },
- { name: '后期', percentage: 15, startPercentage: 35, isCompleted: false, isCurrent: false },
- { name: '交付', percentage: 50, startPercentage: 50, isCompleted: false, isCurrent: false }
- ]
- },
- // 添加更多不同阶段的项目
- {
- id: 'proj-005',
- name: '现代简约厨房设计',
- type: 'soft',
- memberType: 'normal',
- designerName: '',
- status: '待分配',
- expectedEndDate: new Date(2023, 10, 5),
- deadline: new Date(2023, 10, 5),
- isOverdue: false,
- overdueDays: 0,
- dueSoon: false,
- urgency: 'medium',
- currentStage: 'pendingAssignment',
- phases: []
- },
- {
- id: 'proj-006',
- name: '日式风格书房设计',
- type: 'hard',
- memberType: 'normal',
- designerName: '',
- status: '待确认',
- expectedEndDate: new Date(2023, 10, 10),
- deadline: new Date(2023, 10, 10),
- isOverdue: false,
- overdueDays: 0,
- dueSoon: false,
- urgency: 'low',
- currentStage: 'pendingApproval',
- phases: []
- },
- {
- id: 'proj-007',
- name: '轻奢风格浴室设计',
- type: 'soft',
- memberType: 'normal',
- designerName: '钱七',
- status: '已完成',
- expectedEndDate: new Date(2023, 9, 5),
- deadline: new Date(2023, 9, 5),
- isOverdue: false,
- overdueDays: 0,
- dueSoon: false,
- urgency: 'medium',
- currentStage: 'delivery',
- phases: []
- }
- ];
- // ===== 追加生成示例数据:保证总量达到100条 =====
- const stageIds = this.projectStages.map(s => s.id);
- const designers = ['张三','李四','王五','赵六','孙七','周八','吴九','陈十'];
- const statusMap: Record<string, string> = {
- pendingApproval: '待确认',
- pendingAssignment: '待分配',
- requirement: '进行中',
- planning: '进行中',
- modeling: '进行中',
- rendering: '进行中',
- postProduction: '进行中',
- review: '进行中',
- revision: '进行中',
- delivery: '已完成'
- };
- // 为有项目的设计师分配项目
- const busyDesigners = ['张三', '王五', '吴九']; // 高负荷设计师
- const moderateDesigners = ['孙七']; // 中等负荷设计师
- const idleDesigners = ['李四', '赵六', '周八', '陈十']; // 空闲设计师
- // 为忙碌的设计师分配更多项目
- for (let i = 8; i <= 30; i++) {
- const designerIndex = (i - 8) % busyDesigners.length;
- const designerName = busyDesigners[designerIndex];
- const stageIndex = (i - 1) % 7 + 3; // 主要在进行中的阶段
- const currentStage = stageIds[stageIndex];
- const type: 'soft' | 'hard' = i % 2 === 0 ? 'soft' : 'hard';
- const urgency: 'high' | 'medium' | 'low' = i % 4 === 0 ? 'high' : (i % 3 === 0 ? 'medium' : 'low');
- const isOverdue = i % 8 === 0;
- const overdueDays = isOverdue ? (i % 5) + 1 : 0;
- const status = statusMap[currentStage] || '进行中';
- const expectedEndDate = new Date();
- const daysOffset = isOverdue ? -(overdueDays + (i % 3)) : ((i % 15) + 5);
- expectedEndDate.setDate(expectedEndDate.getDate() + daysOffset);
- const daysToDeadline = Math.ceil((expectedEndDate.getTime() - Date.now()) / (1000 * 60 * 60 * 24));
- const dueSoon = !isOverdue && daysToDeadline >= 0 && daysToDeadline <= 3;
- const memberType: 'vip' | 'normal' = i % 5 === 0 ? 'vip' : 'normal';
- this.projects.push({
- id: `proj-${String(i).padStart(3, '0')}`,
- name: `${designerName}负责的${type === 'soft' ? '软装' : '硬装'}项目 ${i}`,
- type,
- memberType,
- designerName,
- status,
- expectedEndDate,
- deadline: expectedEndDate,
- isOverdue,
- overdueDays,
- dueSoon,
- urgency,
- currentStage,
- phases: []
- });
- }
- // 为中等负荷设计师分配少量项目
- for (let i = 31; i <= 35; i++) {
- const designerName = moderateDesigners[0];
- const stageIndex = (i - 1) % 5 + 4; // 中间阶段
- const currentStage = stageIds[stageIndex];
- const type: 'soft' | 'hard' = i % 2 === 0 ? 'soft' : 'hard';
- const urgency: 'high' | 'medium' | 'low' = 'medium';
- const status = statusMap[currentStage] || '进行中';
- const expectedEndDate = new Date();
- expectedEndDate.setDate(expectedEndDate.getDate() + (i % 10) + 7);
- const memberType: 'vip' | 'normal' = 'normal';
- this.projects.push({
- id: `proj-${String(i).padStart(3, '0')}`,
- name: `${designerName}负责的${type === 'soft' ? '软装' : '硬装'}项目 ${i}`,
- type,
- memberType,
- designerName,
- status,
- expectedEndDate,
- deadline: expectedEndDate,
- isOverdue: false,
- overdueDays: 0,
- dueSoon: false,
- urgency,
- currentStage,
- phases: []
- });
- }
- // 空闲设计师不分配项目,或只分配很少的已完成项目
- for (let i = 36; i <= 40; i++) {
- const designerIndex = (i - 36) % idleDesigners.length;
- const designerName = idleDesigners[designerIndex];
- const currentStage = 'delivery'; // 已完成的项目
- const type: 'soft' | 'hard' = i % 2 === 0 ? 'soft' : 'hard';
- const urgency: 'high' | 'medium' | 'low' = 'low';
- const status = '已完成';
- const expectedEndDate = new Date();
- expectedEndDate.setDate(expectedEndDate.getDate() - (i % 10) - 5); // 过去的日期
- const memberType: 'vip' | 'normal' = 'normal';
- this.projects.push({
- id: `proj-${String(i).padStart(3, '0')}`,
- name: `${designerName}已完成的${type === 'soft' ? '软装' : '硬装'}项目 ${i}`,
- type,
- memberType,
- designerName,
- status,
- expectedEndDate,
- deadline: expectedEndDate,
- isOverdue: false,
- overdueDays: 0,
- dueSoon: false,
- urgency,
- currentStage,
- phases: []
- });
- }
- // ===== 示例数据生成结束 =====
- // 统一补齐真实时间字段(deadline/createdAt),以真实字段贯通筛选与甘特
- const DAY = 24 * 60 * 60 * 1000;
- this.projects = this.projects.map(p => {
- const deadline = p.deadline || p.expectedEndDate;
- const baseDays = p.type === 'hard' ? 30 : 14;
- const createdAt = p.createdAt || new Date(new Date(deadline).getTime() - baseDays * DAY);
- return { ...p, deadline, createdAt } as Project;
- });
- // 筛选结果初始化为全部项目
- this.filteredProjects = [...this.projects];
- // 供筛选用的设计师列表
- this.designers = Array.from(new Set(this.projects.map(p => p.designerName).filter(n => !!n)));
- // 显示超期提醒(使用 getter)
- if (this.overdueProjects.length > 0) {
- this.showAlert = true;
- }
- }
- loadTodoTasks(): void {
- // 模拟待办任务数据
- this.todoTasks = [
- {
- id: 'todo-001',
- title: '待评审效果图',
- description: '现代风格客厅设计项目需要进行效果图评审',
- deadline: new Date(2023, 9, 18, 15, 0),
- priority: 'high',
- type: 'review',
- targetId: 'proj-001'
- },
- {
- id: 'todo-002',
- title: '待分配项目',
- description: '新中式厨房设计项目需要分配给合适的设计师',
- deadline: new Date(2023, 9, 19, 10, 0),
- priority: 'high',
- type: 'assign',
- targetId: 'proj-new'
- },
- {
- id: 'todo-003',
- title: '待确认绩效',
- description: '9月份团队绩效需要进行审核确认',
- deadline: new Date(2023, 9, 22, 18, 0),
- priority: 'medium',
- type: 'performance',
- targetId: 'sep-2023'
- },
- {
- id: 'todo-004',
- title: '待处理客户反馈',
- description: '北欧风格卧室设计项目有客户反馈需要处理',
- deadline: new Date(2023, 9, 20, 14, 0),
- priority: 'medium',
- type: 'review',
- targetId: 'proj-002'
- },
- {
- id: 'todo-005',
- title: '团队会议',
- description: '每周团队进度沟通会议',
- deadline: new Date(2023, 9, 18, 10, 0),
- priority: 'low',
- type: 'performance',
- targetId: 'weekly-meeting'
- }
- ];
- // 按优先级排序:紧急且重要 > 重要不紧急 > 紧急不重要
- this.todoTasks.sort((a, b) => {
- const priorityOrder = {
- 'high': 3,
- 'medium': 2,
- 'low': 1
- };
- return priorityOrder[b.priority] - priorityOrder[a.priority];
- });
- }
- // 筛选项目类型
- filterProjects(event: Event): void {
- const target = event.target as HTMLSelectElement;
- this.selectedType = (target && target.value ? target.value : 'all') as any;
- this.applyFilters();
- }
- // 筛选紧急程度
- filterByUrgency(event: Event): void {
- const target = event.target as HTMLSelectElement;
- this.selectedUrgency = (target && target.value ? target.value : 'all') as any;
- this.applyFilters();
- }
- // 筛选项目状态
- filterByStatus(status: string): void {
- // 点击同一状态时,切换回“全部”,以便恢复全量项目列表
- const next = (this.selectedStatus === status) ? 'all' : (status && status.length ? status : 'all');
- this.selectedStatus = next as any;
- this.applyFilters();
- }
-
- // 处理状态筛选下拉框变化
- onStatusChange(event: Event): void {
- const target = event.target as HTMLSelectElement;
- this.selectedStatus = (target && target.value ? target.value : 'all') as any;
- this.applyFilters();
- }
- // 新增:设计师筛选下拉事件处理
- onDesignerChange(event: Event): void {
- const target = event.target as HTMLSelectElement;
- this.selectedDesigner = (target && target.value ? target.value : 'all');
- this.applyFilters();
- }
- // 新增:会员类型筛选下拉事件处理
- onMemberTypeChange(event: Event): void {
- const select = event.target as HTMLSelectElement;
- this.selectedMemberType = select.value as any;
- this.applyFilters();
- }
- // 新增:四大板块改变
- onCorePhaseChange(event: Event): void {
- const select = event.target as HTMLSelectElement;
- this.selectedCorePhase = select.value as any;
- this.applyFilters();
- }
- // 时间窗快捷筛选(供UI按钮触发)
- filterByTimeWindow(timeWindow: 'all' | 'today' | 'threeDays' | 'sevenDays'): void {
- this.selectedTimeWindow = timeWindow;
- this.applyFilters();
- }
- // 新增:搜索输入变化
- onSearchChange(): void {
- if (this.searchDebounceTimer) clearTimeout(this.searchDebounceTimer);
- this.searchDebounceTimer = setTimeout(() => {
- this.updateSearchSuggestions();
- this.applyFilters();
- }, this.SEARCH_DEBOUNCE_MS);
- }
- // 新增:搜索框聚焦/失焦控制建议显隐
- onSearchFocus(): void {
- if (this.hideSuggestionsTimer) clearTimeout(this.hideSuggestionsTimer);
- this.isSearchFocused = true;
- this.updateSearchSuggestions();
- }
- onSearchBlur(): void {
- // 延迟隐藏以允许选择项的 mousedown 触发
- this.isSearchFocused = false;
- this.hideSuggestionsTimer = setTimeout(() => {
- this.showSuggestions = false;
- }, 150);
- }
- // 新增:更新搜索建议(不叠加其它筛选,仅基于关键字)
- private updateSearchSuggestions(): void {
- const q = (this.searchTerm || '').trim().toLowerCase();
- if (q.length < this.MIN_SEARCH_LEN) {
- this.searchSuggestions = [];
- this.showSuggestions = false;
- return;
- }
- const scored = this.projects
- .filter(p => (p.searchIndex || `${(p.name || '')}|${(p.designerName || '')}`.toLowerCase()).includes(q))
- .map(p => {
- const dl = p.deadline || p.expectedEndDate;
- const dlTime = dl ? new Date(dl).getTime() : NaN;
- const daysToDl = Math.ceil(((isNaN(dlTime) ? 0 : dlTime) - Date.now()) / (1000 * 60 * 60 * 24));
- const urgencyScore = p.urgency === 'high' ? 3 : p.urgency === 'medium' ? 2 : 1;
- const overdueScore = p.isOverdue ? 10 : 0;
- const score = overdueScore + (4 - urgencyScore) * 2 - (isNaN(daysToDl) ? 0 : daysToDl);
- return { p, score };
- })
- .sort((a, b) => b.score - a.score)
- .slice(0, this.MAX_SUGGESTIONS)
- .map(x => x.p);
- this.searchSuggestions = scored;
- this.showSuggestions = this.isSearchFocused && this.searchSuggestions.length > 0;
- }
- // 新增:选择建议项
- selectSuggestion(project: Project): void {
- this.searchTerm = project.name;
- this.showSuggestions = false;
- this.viewProjectDetails(project.id);
- }
- // 统一筛选
- private applyFilters(): void {
- let result = [...this.projects];
- // 新增:关键词搜索(项目名 / 设计师名 / 含风格关键词的项目名)
- const q = (this.searchTerm || '').trim().toLowerCase();
- if (q) {
- result = result.filter(p => (p.searchIndex || `${(p.name || '')}|${(p.designerName || '')}`.toLowerCase()).includes(q));
- }
- // 类型筛选
- if (this.selectedType !== 'all') {
- result = result.filter(p => p.type === this.selectedType);
- }
- // 紧急程度筛选
- if (this.selectedUrgency !== 'all') {
- result = result.filter(p => p.urgency === this.selectedUrgency);
- }
- // 项目状态筛选
- if (this.selectedStatus !== 'all') {
- if (this.selectedStatus === 'overdue') {
- result = result.filter(p => p.isOverdue);
- } else if (this.selectedStatus === 'dueSoon') {
- result = result.filter(p => p.dueSoon && !p.isOverdue);
- } else if (this.selectedStatus === 'pendingApproval') {
- result = result.filter(p => p.currentStage === 'pendingApproval');
- } else if (this.selectedStatus === 'pendingAssignment') {
- result = result.filter(p => p.currentStage === 'pendingAssignment');
- } else if (this.selectedStatus === 'progress') {
- const progressStages = ['requirement','planning','modeling','rendering','postProduction','review','revision'];
- result = result.filter(p => progressStages.includes(p.currentStage));
- } else if (this.selectedStatus === 'completed') {
- result = result.filter(p => p.currentStage === 'delivery');
- }
- }
- // 新增:四大板块筛选
- if (this.selectedCorePhase !== 'all') {
- result = result.filter(p => this.mapStageToCorePhase(p.currentStage) === this.selectedCorePhase);
- }
- // 设计师筛选
- if (this.selectedDesigner !== 'all') {
- result = result.filter(p => p.designerName === this.selectedDesigner);
- }
- // 会员类型筛选
- if (this.selectedMemberType !== 'all') {
- result = result.filter(p => p.memberType === this.selectedMemberType);
- }
- // 新增:时间窗筛选
- if (this.selectedTimeWindow !== 'all') {
- const now = new Date();
- const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
-
- result = result.filter(p => {
- const projectDeadline = new Date(p.deadline);
- const timeDiff = projectDeadline.getTime() - today.getTime();
- const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
-
- switch (this.selectedTimeWindow) {
- case 'today':
- return daysDiff <= 1 && daysDiff >= 0;
- case 'threeDays':
- return daysDiff <= 3 && daysDiff >= 0;
- case 'sevenDays':
- return daysDiff <= 7 && daysDiff >= 0;
- default:
- return true;
- }
- });
- }
- this.filteredProjects = result;
- // 新增:计算紧急任务固定区(超期 + 高紧急),与筛选联动
- this.urgentPinnedProjects = this.filteredProjects
- .filter(p => p.isOverdue && p.urgency === 'high')
- .sort((a, b) => (b.overdueDays - a.overdueDays) || a.name.localeCompare(b.name, 'zh-Hans-CN'));
- // 当显示甘特卡片时,同步刷新甘特图
- if (this.showGanttView) {
- this.updateGantt();
- }
- // 同步刷新工作负载甘特图
- setTimeout(() => this.updateWorkloadGantt(), 0);
- }
- /**
- * 计算项目加权值
- */
- calculateWorkloadWeight(project: any): number {
- return this.designerService.calculateProjectWeight(project);
- }
- /**
- * 获取设计师加权工作量
- */
- getDesignerWeightedWorkload(designerName: string): {
- weightedTotal: number;
- projectCount: number;
- overdueCount: number;
- loadRate: number;
- } {
- const designerProjects = this.filteredProjects.filter(p => p.designerName === designerName);
- const weightedTotal = designerProjects.reduce((sum, p) => sum + this.calculateWorkloadWeight(p), 0);
- const overdueCount = designerProjects.filter(p => p.isOverdue).length;
-
- // 从realDesigners获取设计师的单周处理量
- const designer = this.realDesigners.find(d => d.name === designerName);
- const weeklyCapacity = designer?.tags?.capacity?.weeklyProjects || 3;
- const loadRate = weeklyCapacity > 0 ? (weightedTotal / weeklyCapacity) * 100 : 0;
-
- return {
- weightedTotal,
- projectCount: designerProjects.length,
- overdueCount,
- loadRate
- };
- }
- /**
- * 工作量卡片数据(替代ECharts)
- */
- get designerWorkloadCards(): Array<{
- name: string;
- loadRate: number;
- weightedValue: number;
- projectCount: number;
- overdueCount: number;
- status: 'overload' | 'busy' | 'idle';
- }> {
- const designers = Array.from(new Set(this.filteredProjects.map(p => p.designerName).filter(n => n && n !== '未分配')));
-
- return designers.map(name => {
- const workload = this.getDesignerWeightedWorkload(name);
- let status: 'overload' | 'busy' | 'idle' = 'idle';
- if (workload.loadRate > 80) status = 'overload';
- else if (workload.loadRate > 50) status = 'busy';
-
- return {
- name,
- loadRate: workload.loadRate,
- weightedValue: workload.weightedTotal,
- projectCount: workload.projectCount,
- overdueCount: workload.overdueCount,
- status
- };
- }).sort((a, b) => b.loadRate - a.loadRate); // 按负载率降序
- }
- /**
- * 获取超负荷设计师数量
- */
- get overloadedDesignersCount(): number {
- return this.designerWorkloadCards.filter(d => d.status === 'overload').length;
- }
- /**
- * 获取平均负载率
- */
- get averageWorkloadRate(): number {
- const cards = this.designerWorkloadCards;
- if (cards.length === 0) return 0;
- const sum = cards.reduce((acc, card) => acc + card.loadRate, 0);
- return sum / cards.length;
- }
- /**
- * 获取预警汇总数据
- */
- getAlertSummary(): {
- totalAlerts: number;
- overdueHighRisk: Project[];
- overloadedDesigners: any[];
- dueSoonProjects: Project[];
- } {
- // 1. 超期高危项目(超期>=5天 或 高紧急度超期)
- const overdueHighRisk = this.filteredProjects
- .filter(p => p.isOverdue && (p.overdueDays >= 5 || p.urgency === 'high'))
- .sort((a, b) => b.overdueDays - a.overdueDays)
- .slice(0, 5);
-
- // 2. 超负荷设计师
- const overloadedDesigners = this.designerWorkloadCards
- .filter(d => d.loadRate > 80)
- .sort((a, b) => b.loadRate - a.loadRate)
- .slice(0, 5);
-
- // 3. 即将到期项目(1-2天内)
- const now = new Date();
- const dueSoonProjects = this.filteredProjects
- .filter(p => {
- if (p.isOverdue) return false;
- const daysLeft = Math.ceil((p.deadline.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
- return daysLeft >= 1 && daysLeft <= 2;
- })
- .sort((a, b) => a.deadline.getTime() - b.deadline.getTime())
- .slice(0, 5);
-
- const totalAlerts = overdueHighRisk.length + overloadedDesigners.length + dueSoonProjects.length;
-
- return {
- totalAlerts,
- overdueHighRisk,
- overloadedDesigners,
- dueSoonProjects
- };
- }
- /**
- * 打开智能推荐弹窗
- */
- async openSmartMatch(project: any): Promise<void> {
- this.selectedProject = project;
- this.showSmartMatch = true;
-
- try {
- this.recommendations = await this.designerService.getRecommendedDesigners(project, this.realDesigners);
- } catch (error) {
- console.error('智能推荐失败:', error);
- this.recommendations = [];
- }
- }
- /**
- * 关闭智能推荐弹窗
- */
- closeSmartMatch(): void {
- this.showSmartMatch = false;
- this.selectedProject = null;
- this.recommendations = [];
- }
- /**
- * 分配项目给设计师
- */
- async assignToDesigner(designerId: string): Promise<void> {
- if (!this.selectedProject) return;
-
- try {
- const success = await this.designerService.assignProject(this.selectedProject.id, designerId);
- if (success) {
- this.closeSmartMatch();
- await this.loadProjects(); // 重新加载项目数据
- }
- } catch (error) {
- console.error('❌ 分配项目失败:', error);
- window?.fmode?.alert('分配失败,请重试');
- }
- }
- /**
- * 获取紧急度标签
- */
- getUrgencyLabel(urgency: string): string {
- const labels: Record<string, string> = {
- 'high': '高',
- 'medium': '中',
- 'low': '低'
- };
- return labels[urgency] || '未知';
- }
- // 切换项目看板/负载日历(甘特)视图
- toggleView(): void {
- this.showGanttView = !this.showGanttView;
- if (this.showGanttView) {
- setTimeout(() => this.initOrUpdateGantt(), 0);
- } else {
- if (this.ganttChart) {
- this.ganttChart.dispose();
- this.ganttChart = null;
- }
- }
- }
- // 设置甘特时间尺度
- setGanttScale(scale: 'day' | 'week' | 'month'): void {
- if (this.ganttScale !== scale) {
- this.ganttScale = scale;
- this.updateGantt();
- }
- }
- // 工作负载甘特图时间尺度切换
- setWorkloadGanttScale(scale: 'week' | 'month'): void {
- if (this.workloadGanttScale !== scale) {
- this.workloadGanttScale = scale;
- this.updateWorkloadGantt();
- }
- }
- // 新增:切换甘特模式
- setGanttMode(mode: 'project' | 'designer'): void {
- if (this.ganttMode !== mode) {
- this.ganttMode = mode;
- this.updateGantt();
- }
- }
- private initOrUpdateGantt(): void {
- if (!this.ganttChartRef) return;
- const el = this.ganttChartRef.nativeElement;
- if (!this.ganttChart) {
- this.ganttChart = echarts.init(el);
-
- // 添加点击事件监听器
- this.ganttChart.on('click', (params: any) => {
- if (params.componentType === 'series' && params.seriesType === 'custom') {
- // 获取点击的员工名称(从y轴类目数据中获取)
- const yAxisData = this.ganttChart.getOption().yAxis[0].data;
- if (yAxisData && params.dataIndex !== undefined) {
- const employeeName = yAxisData[params.value[0]];
- if (employeeName && employeeName !== '未分配') {
- this.onEmployeeClick(employeeName);
- }
- }
- }
- });
-
- window.addEventListener('resize', () => {
- this.ganttChart && this.ganttChart.resize();
- });
- }
- this.updateGantt();
- }
- private updateGantt(): void {
- if (!this.ganttChart) return;
- if (this.ganttMode === 'designer') {
- this.updateGanttDesigner();
- return;
- }
- // 按紧急程度从上到下排序(高->中->低),同级按到期时间升序
- const urgencyRank: Record<'high'|'medium'|'low', number> = { high: 0, medium: 1, low: 2 };
- const projects = [...this.filteredProjects]
- .sort((a, b) => {
- const u = urgencyRank[a.urgency] - urgencyRank[b.urgency];
- if (u !== 0) return u;
- // 二级排序:临期优先(到期更近)> 已分配人员 > VIP客户 > 其他
- const endDiff = new Date(a.deadline).getTime() - new Date(b.deadline).getTime();
- if (endDiff !== 0) return endDiff;
- const assignedA = !!a.designerName;
- const assignedB = !!b.designerName;
- if (assignedA !== assignedB) return assignedA ? -1 : 1; // 已分配在前
- const vipA = a.memberType === 'vip';
- const vipB = b.memberType === 'vip';
- if (vipA !== vipB) return vipA ? -1 : 1; // VIP在前
- return a.name.localeCompare(b.name, 'zh-CN');
- });
- const categories = projects.map(p => p.name);
- const urgencyMap: Record<string, 'high'|'medium'|'low'> = Object.fromEntries(projects.map(p => [p.name, p.urgency])) as any;
- const colorByUrgency: Record<'high'|'medium'|'low', string> = {
- high: '#ef4444',
- medium: '#f59e0b',
- low: '#22c55e'
- } as const;
- const DAY = 24 * 60 * 60 * 1000;
- const data = projects.map((p, idx) => {
- const end = new Date(p.deadline).getTime();
- const baseDays = p.type === 'hard' ? 30 : 14;
- const start = p.createdAt ? new Date(p.createdAt).getTime() : end - baseDays * DAY;
- const color = colorByUrgency[p.urgency] || '#60a5fa';
- return {
- name: p.name,
- value: [idx, start, end, p.designerName, p.urgency, p.memberType, p.currentStage],
- itemStyle: { color }
- };
- });
- // 计算时间范围(仅周/月)
- const now = new Date();
- const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
- const todayTs = today.getTime();
- let xMin: number;
- let xMax: number;
- let xSplitNumber: number;
- let xLabelFormatter: (value: number) => string;
- if (this.ganttScale === 'week') {
- const day = today.getDay(); // 0=周日
- const diffToMonday = (day === 0 ? 6 : day - 1);
- const startOfWeek = new Date(today.getTime() - diffToMonday * DAY);
- const endOfWeek = new Date(startOfWeek.getTime() + 7 * DAY - 1);
- xMin = startOfWeek.getTime();
- xMax = endOfWeek.getTime();
- xSplitNumber = 7;
- const WEEK_LABELS = ['周日','周一','周二','周三','周四','周五','周六'];
- xLabelFormatter = (val) => {
- const d = new Date(val);
- return WEEK_LABELS[d.getDay()];
- };
- } else { // month
- const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
- const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0, 23, 59, 59, 999);
- xMin = startOfMonth.getTime();
- xMax = endOfMonth.getTime();
- xSplitNumber = 4;
- xLabelFormatter = (val) => {
- const d = new Date(val);
- const weekOfMonth = Math.ceil(d.getDate() / 7);
- return `第${weekOfMonth}周`;
- };
- }
- // 计算默认可视区,并尝试保留上一次的滚动/缩放位置
- const total = categories.length;
- const visible = Math.min(total, 15); // 默认首屏展开15条
- const defaultEndPercent = total > 0 ? Math.min(100, (visible / total) * 100) : 100;
- const prevOpt: any = (this.ganttChart as any).getOption ? (this.ganttChart as any).getOption() : null;
- const preservedStart = typeof prevOpt?.dataZoom?.[0]?.start === 'number' ? prevOpt.dataZoom[0].start : 0;
- const preservedEnd = typeof prevOpt?.dataZoom?.[0]?.end === 'number' ? prevOpt.dataZoom[0].end : defaultEndPercent;
- // 生成请假覆盖层数据
- const leaveOverlayData = this.generateLeaveOverlayData(categories, xMin, xMax);
- const option = {
- backgroundColor: 'transparent',
- tooltip: {
- trigger: 'item',
- formatter: (params: any) => {
- const v = params.value;
- const start = new Date(v[1]);
- const end = new Date(v[2]);
- return `项目:${params.name}<br/>负责人:${v[3] || '未分配'}<br/>阶段:${v[6]}<br/>起止:${start.toLocaleDateString()} ~ ${end.toLocaleDateString()}`;
- }
- },
- grid: { left: 100, right: 64, top: 30, bottom: 30 },
- xAxis: {
- type: 'time',
- min: xMin,
- max: xMax,
- splitNumber: xSplitNumber,
- axisLine: { lineStyle: { color: '#e5e7eb' } },
- axisLabel: { color: '#6b7280', formatter: (value: number) => xLabelFormatter(value) },
- splitLine: { lineStyle: { color: '#f1f5f9' } }
- },
- yAxis: {
- type: 'category',
- data: categories,
- inverse: true,
- axisLabel: {
- color: '#374151',
- margin: 8,
- formatter: (val: string) => {
- const u = urgencyMap[val] || 'low';
- const text = val.length > 16 ? val.slice(0, 16) + '…' : val;
- return `{${u}Dot|●} ${text}`;
- },
- rich: {
- highDot: { color: '#ef4444' },
- mediumDot: { color: '#f59e0b' },
- lowDot: { color: '#22c55e' }
- }
- },
- axisTick: { show: false },
- axisLine: { lineStyle: { color: '#e5e7eb' } }
- },
- dataZoom: [
- { type: 'slider', yAxisIndex: 0, orient: 'vertical', right: 6, width: 14, start: preservedStart, end: preservedEnd, zoomLock: false },
- { type: 'inside', yAxisIndex: 0, zoomOnMouseWheel: true, moveOnMouseMove: true, moveOnMouseWheel: true }
- ],
- series: [
- // 项目条形图系列
- {
- type: 'custom',
- name: '项目进度',
- renderItem: (params: any, api: any) => {
- const categoryIndex = api.value(0);
- const start = api.coord([api.value(1), categoryIndex]);
- const end = api.coord([api.value(2), categoryIndex]);
- const height = Math.max(api.size([0, 1])[1] * 0.5, 8);
- const rectShape = echarts.graphic.clipRectByRect({
- x: start[0],
- y: start[1] - height / 2,
- width: Math.max(end[0] - start[0], 2),
- height
- }, {
- x: params.coordSys.x,
- y: params.coordSys.y,
- width: params.coordSys.width,
- height: params.coordSys.height
- });
- return rectShape ? { type: 'rect', shape: rectShape, style: api.style() } : undefined;
- },
- encode: { x: [1, 2], y: 0 },
- data,
- itemStyle: { borderRadius: 4 },
- emphasis: { focus: 'self' },
- markLine: {
- silent: true,
- symbol: 'none',
- lineStyle: { color: '#ef4444', type: 'dashed', width: 1 },
- label: { formatter: '今日', color: '#ef4444', fontSize: 10, position: 'end' },
- data: [ { xAxis: todayTs } ]
- }
- },
- // 请假覆盖层系列
- {
- type: 'custom',
- name: '请假/繁忙标记',
- renderItem: (params: any, api: any) => {
- const categoryIndex = api.value(0);
- const start = api.coord([api.value(1), categoryIndex]);
- const end = api.coord([api.value(2), categoryIndex]);
- const height = Math.max(api.size([0, 1])[1] * 0.8, 12); // 稍微高一点,覆盖项目条
- const rectShape = echarts.graphic.clipRectByRect({
- x: start[0],
- y: start[1] - height / 2,
- width: Math.max(end[0] - start[0], 2),
- height
- }, {
- x: params.coordSys.x,
- y: params.coordSys.y,
- width: params.coordSys.width,
- height: params.coordSys.height
- });
- return rectShape ? { type: 'rect', shape: rectShape, style: api.style() } : undefined;
- },
- encode: { x: [1, 2], y: 0 },
- data: leaveOverlayData,
- itemStyle: { borderRadius: 4 },
- emphasis: { focus: 'self' },
- z: 10 // 确保覆盖层在项目条之上
- }
- ]
- };
- // 强制刷新,避免缓存导致坐标轴不更新
- this.ganttChart.clear();
- this.ganttChart.setOption(option, true);
- this.ganttChart.resize();
- }
- // 新增:设计师排班甘特
- private updateGanttDesigner(): void {
- if (!this.ganttChart) return;
- const DAY = 24 * 60 * 60 * 1000;
- const now = new Date();
- const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
- const todayTs = today.getTime();
- // 时间轴按当前周/月/日
- let xMin: number;
- let xMax: number;
- let xSplitNumber: number;
- let xLabelFormatter: (value: number) => string;
- if (this.ganttScale === 'day') {
- // 日视图:显示今日24小时
- const startOfDay = new Date(today.getTime());
- const endOfDay = new Date(today.getTime() + DAY - 1);
- xMin = startOfDay.getTime();
- xMax = endOfDay.getTime();
- xSplitNumber = 24;
- xLabelFormatter = (val) => `${new Date(val).getHours()}:00`;
- } else if (this.ganttScale === 'week') {
- // 周视图:从今天开始显示未来7天的具体日期
- const startOfWeek = new Date(today.getTime());
- const endOfWeek = new Date(today.getTime() + 7 * DAY - 1);
- xMin = startOfWeek.getTime();
- xMax = endOfWeek.getTime();
- xSplitNumber = 7;
- xLabelFormatter = (val) => {
- const date = new Date(val);
- const month = date.getMonth() + 1;
- const day = date.getDate();
- return `${month}月${day}日`;
- };
- } else {
- // 月视图:从当前月份开始显示未来几个月
- const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
- const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 3, 0, 23, 59, 59, 999); // 显示未来3个月
- xMin = startOfMonth.getTime();
- xMax = endOfMonth.getTime();
- xSplitNumber = 3;
- xLabelFormatter = (val) => {
- const date = new Date(val);
- const year = date.getFullYear();
- const month = date.getMonth() + 1;
- return `${year}年${month}月`;
- };
- }
- // 仅统计已分配项目
- const assigned = this.filteredProjects.filter(p => !!p.designerName);
- const designers = Array.from(new Set(assigned.map(p => p.designerName)));
- const byDesigner: Record<string, typeof assigned> = {} as any;
- designers.forEach(n => byDesigner[n] = [] as any);
- assigned.forEach(p => byDesigner[p.designerName].push(p));
- const busyCountMap: Record<string, number> = Object.fromEntries(designers.map(n => [n, byDesigner[n].length]));
- const sortedDesigners = designers.sort((a, b) => {
- const diff = (busyCountMap[b] || 0) - (busyCountMap[a] || 0);
- return diff !== 0 ? diff : a.localeCompare(b, 'zh-CN');
- });
- const categories = sortedDesigners;
- // 工作量等级(用于左侧小圆点颜色和负荷状态判断)
- const workloadLevelMap: Record<string, 'high'|'medium'|'low'> = {} as any;
- const workloadStatusMap: Record<string, 'overloaded'|'busy'|'available'> = {} as any;
- categories.forEach(name => {
- const cnt = busyCountMap[name] || 0;
- if (cnt >= 5) {
- workloadLevelMap[name] = 'high';
- workloadStatusMap[name] = 'overloaded'; // 不宜派单
- } else if (cnt >= 3) {
- workloadLevelMap[name] = 'medium';
- workloadStatusMap[name] = 'busy'; // 适度忙碌
- } else {
- workloadLevelMap[name] = 'low';
- workloadStatusMap[name] = 'available'; // 可接单
- }
- });
- // 条形颜色按项目紧急度,增强高负荷时段的视觉效果
- const colorByUrgency: Record<'high'|'medium'|'low', string> = {
- high: '#dc2626', // 更深的红色,突出高紧急度
- medium: '#ea580c', // 更深的橙色
- low: '#16a34a' // 更深的绿色
- } as const;
- const data = assigned.flatMap(p => {
- const end = new Date(p.deadline).getTime();
- const baseDays = p.type === 'hard' ? 30 : 14;
- const start = p.createdAt ? new Date(p.createdAt).getTime() : end - baseDays * DAY;
- const yIndex = categories.indexOf(p.designerName);
- if (yIndex === -1) return [] as any[];
-
- // 根据设计师工作负荷状态调整项目条的视觉效果
- const workloadStatus = workloadStatusMap[p.designerName];
- let color = colorByUrgency[p.urgency] || '#60a5fa';
- let borderWidth = 1;
- let borderColor = 'transparent';
-
- // 高负荷时段增强视觉效果
- if (workloadStatus === 'overloaded') {
- borderWidth = 3;
- borderColor = '#991b1b'; // 深红色边框
- // 对于超负荷状态,使用更深的红色调
- if (p.urgency === 'high') {
- color = '#7f1d1d'; // 深红色
- } else if (p.urgency === 'medium') {
- color = '#c2410c'; // 深橙色
- } else {
- color = '#dc2626'; // 红色(即使是低紧急度也用红色表示超负荷)
- }
- }
-
- return [{
- name: p.name,
- value: [yIndex, start, end, p.designerName, p.urgency, p.memberType, p.currentStage, workloadStatus],
- itemStyle: {
- color,
- borderWidth,
- borderColor,
- opacity: workloadStatus === 'overloaded' ? 0.9 : 1.0
- }
- }];
- });
- // 生成空闲时段背景数据 - 只在真正空闲的时间段显示
- const idleBackgroundData: any[] = [];
-
- categories.forEach((designerName, yIndex) => {
- const designerProjects = byDesigner[designerName] || [];
- const workloadStatus = workloadStatusMap[designerName];
-
- // 获取该设计师的所有项目时间段
- const projectTimeRanges = designerProjects.map(p => {
- const end = new Date(p.deadline).getTime();
- const baseDays = p.type === 'hard' ? 30 : 14;
- const start = p.createdAt ? new Date(p.createdAt).getTime() : end - baseDays * DAY;
- return { start, end };
- }).sort((a, b) => a.start - b.start);
-
- // 找出空闲时间段
- const idleTimeRanges: { start: number; end: number }[] = [];
-
- if (projectTimeRanges.length === 0) {
- // 完全没有项目,整个时间轴都是空闲
- idleTimeRanges.push({ start: xMin, end: xMax });
- } else {
- // 检查项目之间的空隙
- let currentTime = xMin;
-
- for (const range of projectTimeRanges) {
- if (currentTime < range.start) {
- // 在项目开始前有空闲时间
- idleTimeRanges.push({ start: currentTime, end: range.start });
- }
- currentTime = Math.max(currentTime, range.end);
- }
-
- // 检查最后一个项目后是否还有空闲时间
- if (currentTime < xMax) {
- idleTimeRanges.push({ start: currentTime, end: xMax });
- }
- }
-
- // 为每个空闲时间段创建背景数据
- idleTimeRanges.forEach((idleRange, index) => {
- // 只有当空闲时间段足够长时才显示(至少1天)
- if (idleRange.end - idleRange.start >= DAY) {
- let backgroundColor = 'transparent';
-
- if (workloadStatus === 'available') {
- backgroundColor = 'rgba(34, 197, 94, 0.15)'; // 淡绿色背景表示空闲可接单
- } else if (workloadStatus === 'overloaded') {
- backgroundColor = 'rgba(239, 68, 68, 0.1)'; // 淡红色背景表示超负荷
- }
-
- if (backgroundColor !== 'transparent') {
- idleBackgroundData.push({
- name: `${designerName}-空闲${index + 1}`,
- value: [yIndex, idleRange.start, idleRange.end, designerName, 'background', workloadStatus],
- itemStyle: {
- color: backgroundColor,
- borderWidth: 0
- }
- });
- }
- }
- });
- });
- const prevOpt: any = (this.ganttChart as any).getOption ? (this.ganttChart as any).getOption() : null;
- const total = categories.length || 1;
- const visible = Math.min(total, 30);
- const defaultEndPercent = Math.min(100, (visible / total) * 100);
- const preservedStart = typeof prevOpt?.dataZoom?.[0]?.start === 'number' ? prevOpt.dataZoom[0].start : 0;
- const preservedEnd = typeof prevOpt?.dataZoom?.[0]?.end === 'number' ? prevOpt.dataZoom[0].end : defaultEndPercent;
- const option = {
- backgroundColor: 'transparent',
- tooltip: {
- trigger: 'item',
- backgroundColor: 'rgba(255, 255, 255, 0.95)',
- borderColor: '#e5e7eb',
- borderWidth: 1,
- padding: [12, 16],
- textStyle: { color: '#374151', fontSize: 13 },
- formatter: (params: any) => {
- const v = params.value;
- if (v[4] === 'background') {
- const workloadStatus = v[5];
- const statusText = workloadStatus === 'available' ? '空闲可接单' :
- workloadStatus === 'overloaded' ? '超负荷不宜派单' : '适度忙碌';
- return `<div style="padding: 4px 0;">
- <div style="font-weight: 600; margin-bottom: 6px;">👤 ${v[3]}</div>
- <div style="color: #6b7280;">状态:${statusText}</div>
- </div>`;
- }
- const start = new Date(v[1]);
- const end = new Date(v[2]);
- const urgency = v[4];
- const memberType = v[5];
- const currentStage = v[6];
- const workloadStatus = v[7];
-
- // 紧急度标识
- const urgencyBadge = urgency === 'high' ? '<span style="background:#dc2626;color:white;padding:2px 6px;border-radius:3px;font-size:11px;">🔥 高紧急</span>' :
- urgency === 'medium' ? '<span style="background:#ea580c;color:white;padding:2px 6px;border-radius:3px;font-size:11px;">⚡ 中紧急</span>' :
- '<span style="background:#16a34a;color:white;padding:2px 6px;border-radius:3px;font-size:11px;">✓ 正常</span>';
-
- // VIP标识
- const vipBadge = memberType === 'vip' ? '<span style="background:#f59e0b;color:white;padding:2px 6px;border-radius:3px;font-size:11px;margin-left:4px;">⭐ VIP</span>' : '';
-
- // 负载状态
- const statusIcon = workloadStatus === 'available' ? '🟢' :
- workloadStatus === 'overloaded' ? '🔴' : '🟡';
- const statusText = workloadStatus === 'available' ? '可接单' :
- workloadStatus === 'overloaded' ? '超负荷' : '适度忙碌';
-
- // 计算项目持续天数
- const durationDays = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
-
- // 剩余天数
- const now = new Date();
- const remainingDays = Math.ceil((end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
- const remainingText = remainingDays > 0 ? `剩余${remainingDays}天` :
- remainingDays === 0 ? '今天截止' :
- `已超期${Math.abs(remainingDays)}天`;
- const remainingColor = remainingDays > 7 ? '#16a34a' :
- remainingDays > 0 ? '#ea580c' : '#dc2626';
-
- return `<div style="min-width: 280px;">
- <div style="font-weight: 600; margin-bottom: 8px; font-size: 14px; display: flex; align-items: center; gap: 6px;">
- 🎨 ${params.name}
- </div>
- <div style="display: flex; gap: 4px; margin-bottom: 8px;">
- ${urgencyBadge}${vipBadge}
- </div>
- <div style="border-top: 1px solid #e5e7eb; padding-top: 8px; margin-top: 4px;">
- <div style="margin-bottom: 4px;">👤 设计师:<strong>${v[3]}</strong> ${statusIcon} <span style="color: #6b7280;">${statusText}</span></div>
- <div style="margin-bottom: 4px;">📋 阶段:<span style="color: #6b7280;">${currentStage}</span></div>
- <div style="margin-bottom: 4px;">📅 周期:<span style="color: #6b7280;">${start.toLocaleDateString()} ~ ${end.toLocaleDateString()}</span> (${durationDays}天)</div>
- <div style="margin-bottom: 4px;">⏱️ 状态:<span style="color: ${remainingColor}; font-weight: 600;">${remainingText}</span></div>
- </div>
- <div style="border-top: 1px solid #e5e7eb; padding-top: 6px; margin-top: 6px; color: #9ca3af; font-size: 11px;">
- 💡 点击条形可查看项目详情
- </div>
- </div>`;
- }
- },
- title: {
- text: this.ganttScale === 'week' ? '本周项目排期' : '本月项目排期',
- subtext: '每个条形代表一个项目,颜色越深紧急度越高',
- left: 'center',
- top: 10,
- textStyle: { fontSize: 15, color: '#374151', fontWeight: 600 },
- subtextStyle: { fontSize: 12, color: '#6b7280' }
- },
- legend: {
- data: ['🔥 高紧急', '⚡ 中紧急', '✓ 正常', '🟢 可接单', '🟡 忙碌', '🔴 超负荷'],
- bottom: 10,
- itemGap: 20,
- textStyle: { fontSize: 12, color: '#6b7280' }
- },
- grid: { left: 150, right: 70, top: 60, bottom: 70 },
- xAxis: {
- type: 'time',
- min: xMin,
- max: xMax,
- splitNumber: xSplitNumber,
- axisLine: { lineStyle: { color: '#e5e7eb' } },
- axisLabel: { color: '#6b7280', formatter: (value: number) => xLabelFormatter(value) },
- splitLine: { lineStyle: { color: '#f1f5f9' } }
- },
- yAxis: {
- type: 'category',
- data: categories,
- inverse: true,
- axisLabel: {
- color: '#374151',
- margin: 10,
- fontSize: 13,
- fontWeight: 500,
- formatter: (val: string) => {
- const lvl = workloadLevelMap[val] || 'low';
- const count = busyCountMap[val] || 0;
- const status = workloadStatusMap[val] || 'available';
- const text = val.length > 6 ? val.slice(0, 6) + '…' : val;
-
- // 根据负载状态选择图标和颜色
- const statusIcon = status === 'available' ? '○' :
- status === 'overloaded' ? '🔥' : '⚡';
-
- // 项目数量的视觉强化
- const countDisplay = count >= 5 ? `{highCount|${count}}` :
- count >= 3 ? `{mediumCount|${count}}` :
- count >= 1 ? `{lowCount|${count}}` :
- `{idleCount|${count}}`;
-
- return `${statusIcon} {name|${text}} ${countDisplay}`;
- },
- rich: {
- name: {
- color: '#374151',
- fontSize: 13,
- fontWeight: 500,
- padding: [0, 4, 0, 2]
- },
- highCount: {
- color: '#dc2626',
- fontSize: 12,
- fontWeight: 700,
- backgroundColor: '#fee2e2',
- padding: [2, 6],
- borderRadius: 3
- },
- mediumCount: {
- color: '#ea580c',
- fontSize: 12,
- fontWeight: 700,
- backgroundColor: '#ffedd5',
- padding: [2, 6],
- borderRadius: 3
- },
- lowCount: {
- color: '#16a34a',
- fontSize: 12,
- fontWeight: 600,
- backgroundColor: '#dcfce7',
- padding: [2, 6],
- borderRadius: 3
- },
- idleCount: {
- color: '#9ca3af',
- fontSize: 12,
- fontWeight: 500,
- backgroundColor: '#f3f4f6',
- padding: [2, 6],
- borderRadius: 3
- }
- }
- },
- axisTick: { show: false },
- axisLine: { lineStyle: { color: '#e5e7eb' } }
- },
- dataZoom: [
- { type: 'slider', yAxisIndex: 0, orient: 'vertical', right: 6, start: preservedStart, end: preservedEnd, zoomLock: false },
- { type: 'inside', yAxisIndex: 0, zoomOnMouseWheel: true, moveOnMouseMove: true, moveOnMouseWheel: true }
- ],
- series: [
- // 背景层 - 显示空闲时段
- {
- type: 'custom',
- name: '工作负荷背景',
- renderItem: (params: any, api: any) => {
- const categoryIndex = api.value(0);
- const start = api.coord([api.value(1), categoryIndex]);
- const end = api.coord([api.value(2), categoryIndex]);
- const height = api.size([0, 1])[1] * 0.8;
- const rectShape = echarts.graphic.clipRectByRect({
- x: start[0],
- y: start[1] - height / 2,
- width: Math.max(end[0] - start[0], 2),
- height
- }, {
- x: params.coordSys.x,
- y: params.coordSys.y,
- width: params.coordSys.width,
- height: params.coordSys.height
- });
- return rectShape ? { type: 'rect', shape: rectShape, style: api.style() } : undefined;
- },
- encode: { x: [1, 2], y: 0 },
- data: idleBackgroundData,
- z: 1
- },
- // 项目条层
- {
- type: 'custom',
- name: '项目进度',
- renderItem: (params: any, api: any) => {
- const categoryIndex = api.value(0);
- const start = api.coord([api.value(1), categoryIndex]);
- const end = api.coord([api.value(2), categoryIndex]);
- // 增加条形高度,让项目更明显
- const height = Math.max(api.size([0, 1])[1] * 0.6, 16);
- const width = Math.max(end[0] - start[0], 2);
-
- const rectShape = echarts.graphic.clipRectByRect({
- x: start[0],
- y: start[1] - height / 2,
- width,
- height
- }, {
- x: params.coordSys.x,
- y: params.coordSys.y,
- width: params.coordSys.width,
- height: params.coordSys.height
- });
-
- if (!rectShape) return undefined;
-
- // 获取项目数据
- const urgency = api.value(4);
- const workloadStatus = api.value(7);
-
- // 基础矩形样式
- const rectStyle = api.style();
-
- // 根据负载状态添加额外的视觉效果
- if (workloadStatus === 'overloaded') {
- rectStyle.shadowBlur = 8;
- rectStyle.shadowColor = 'rgba(220, 38, 38, 0.4)';
- rectStyle.shadowOffsetY = 2;
- }
-
- const rect = {
- type: 'rect',
- shape: rectShape,
- style: rectStyle
- };
-
- // 项目名称和紧急度标识
- const projectName = params.name || '';
- const minWidthForText = 50; // 降低最小宽度要求
-
- if (width >= minWidthForText && projectName) {
- // 紧急度图标
- const urgencyIcon = urgency === 'high' ? '🔥' :
- urgency === 'medium' ? '⚡' : '✓';
-
- // 截断过长的项目名称
- const maxChars = Math.floor(width / 9); // 估算能显示的字符数
- const displayName = projectName.length > maxChars ?
- projectName.slice(0, maxChars - 2) + '…' :
- projectName;
-
- const fullText = `${urgencyIcon} ${displayName}`;
-
- // 返回组合图形:矩形 + 文本
- return {
- type: 'group',
- children: [
- rect,
- {
- type: 'text',
- style: {
- text: fullText,
- x: rectShape.x + 8,
- y: rectShape.y + rectShape.height / 2,
- textVerticalAlign: 'middle',
- fontSize: 12,
- fontWeight: 600,
- fill: '#ffffff',
- stroke: 'rgba(0, 0, 0, 0.4)',
- lineWidth: 0.8,
- textShadowColor: 'rgba(0, 0, 0, 0.5)',
- textShadowBlur: 3,
- textShadowOffsetX: 0,
- textShadowOffsetY: 1
- }
- }
- ]
- };
- } else if (width >= 30) {
- // 如果空间太小,只显示紧急度图标
- const urgencyIcon = urgency === 'high' ? '🔥' :
- urgency === 'medium' ? '⚡' : '✓';
-
- return {
- type: 'group',
- children: [
- rect,
- {
- type: 'text',
- style: {
- text: urgencyIcon,
- x: rectShape.x + width / 2,
- y: rectShape.y + rectShape.height / 2,
- textAlign: 'center',
- textVerticalAlign: 'middle',
- fontSize: 12
- }
- }
- ]
- };
- }
-
- return rect;
- },
- encode: { x: [1, 2], y: 0 },
- data,
- itemStyle: { borderRadius: 4 },
- emphasis: {
- focus: 'self',
- itemStyle: {
- borderWidth: 2,
- borderColor: '#374151',
- shadowBlur: 8,
- shadowColor: 'rgba(0, 0, 0, 0.3)'
- }
- },
- z: 2,
- markLine: {
- silent: true,
- symbol: 'none',
- lineStyle: { color: '#ef4444', type: 'dashed', width: 2 },
- label: {
- formatter: '今日',
- color: '#ef4444',
- fontSize: 11,
- fontWeight: 600,
- position: 'end',
- backgroundColor: '#ffffff',
- padding: [2, 6],
- borderRadius: 3
- },
- data: [ { xAxis: todayTs } ]
- }
- }
- ]
- } as any;
- this.ganttChart.clear();
- this.ganttChart.setOption(option, true);
- this.ganttChart.resize();
- }
- /**
- * 工作负载甘特图:显示设计师在周/月内的工作状态
- */
- private updateWorkloadGantt(): void {
- if (!this.workloadGanttContainer?.nativeElement) {
- setTimeout(() => this.updateWorkloadGantt(), 100);
- return;
- }
- if (!this.workloadGanttChart) {
- this.workloadGanttChart = echarts.init(this.workloadGanttContainer.nativeElement);
- }
- const DAY = 24 * 60 * 60 * 1000;
- const now = new Date();
- const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
- const todayTs = today.getTime();
- // 时间范围
- let xMin: number;
- let xMax: number;
- let xSplitNumber: number;
- let xLabelFormatter: (value: number) => string;
- if (this.workloadGanttScale === 'week') {
- // 周视图:显示未来7天
- xMin = todayTs;
- xMax = todayTs + 7 * DAY;
- xSplitNumber = 7;
- xLabelFormatter = (val: any) => {
- const date = new Date(val);
- const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
- return `${date.getMonth() + 1}/${date.getDate()}\n${weekDays[date.getDay()]}`;
- };
- } else {
- // 月视图:显示未来30天
- xMin = todayTs;
- xMax = todayTs + 30 * DAY;
- xSplitNumber = 30;
- xLabelFormatter = (val: any) => {
- const date = new Date(val);
- return `${date.getMonth() + 1}/${date.getDate()}`;
- };
- }
- // 获取所有真实设计师
- let designers: string[] = [];
-
- if (this.realDesigners && this.realDesigners.length > 0) {
- designers = this.realDesigners.map(d => d.name);
- } else {
- // 降级:从已分配的项目中提取设计师
- const assigned = this.filteredProjects.filter(p => p.designerName && p.designerName !== '未分配');
- designers = Array.from(new Set(assigned.map(p => p.designerName)));
- }
-
- if (designers.length === 0) {
- // 没有设计师数据,显示空状态
- const emptyOption = {
- title: {
- text: '暂无组员数据',
- subtext: '请先在系统中添加设计师(组员角色)',
- left: 'center',
- top: 'center',
- textStyle: { fontSize: 16, color: '#9ca3af' },
- subtextStyle: { fontSize: 13, color: '#d1d5db' }
- }
- };
- this.workloadGanttChart.setOption(emptyOption, true);
- return;
- }
-
- // 🔧 使用 ProjectTeam 表的数据(实际执行人)
- const workloadByDesigner: Record<string, any[]> = {};
- designers.forEach(name => {
- workloadByDesigner[name] = [];
- });
- // 计算每个设计师的总负载(用于排序)
- const designerTotalLoad: Record<string, number> = {};
- designers.forEach(name => {
- const projects = this.designerWorkloadMap.get(name) || [];
- designerTotalLoad[name] = projects.length;
- });
-
- // 按总负载从高到低排序设计师
- const sortedDesigners = designers.sort((a, b) => {
- return designerTotalLoad[b] - designerTotalLoad[a];
- });
-
- // 为每个设计师生成时间段数据
- sortedDesigners.forEach((designerName, yIndex) => {
- const designerProjects = this.designerWorkloadMap.get(designerName) || [];
-
- // 计算每一天的状态
- const days = this.workloadGanttScale === 'week' ? 7 : 30;
- for (let i = 0; i < days; i++) {
- const dayStart = todayTs + i * DAY;
- const dayEnd = dayStart + DAY - 1;
-
- // 查找该天有哪些项目
- const dayProjects = designerProjects.filter(p => {
- // 如果项目没有 deadline,则认为项目一直在进行中
- if (!p.deadline) {
- return true; // 没有截止日期的项目始终显示
- }
-
- const pEnd = new Date(p.deadline).getTime();
-
- // 检查时间是否有效
- if (isNaN(pEnd)) {
- return true; // 如果截止日期无效,认为项目在进行中
- }
-
- // 🔧 修复:对于进行中的项目(状态不是"已完成"),即使过期也显示
- // 这样可以在甘特图中看到超期的项目
- const isCompleted = p.status === '已完成' || p.status === '已交付';
- if (!isCompleted) {
- // 进行中的项目:只要截止日期还没到很久之前(比如30天前),就显示
- const thirtyDaysAgo = todayTs - 30 * DAY;
- if (pEnd >= thirtyDaysAgo) {
- return true; // 30天内的项目都显示
- }
- }
-
- // 已完成的项目:正常时间范围判断
- const pStart = p.createdAt ? new Date(p.createdAt).getTime() : dayStart;
- return !(pEnd < dayStart || pStart > dayEnd);
- });
- let status: 'idle' | 'busy' | 'overload' | 'leave' = 'idle';
- let color = '#d1fae5'; // 空闲-浅绿色
-
- const projectCount = dayProjects.length;
-
- // TODO: 检查请假记录,如果该天请假则标记为leave
- // const isOnLeave = this.checkLeave(designerName, dayStart, dayEnd);
- // if (isOnLeave) {
- // status = 'leave';
- // color = '#e5e7eb'; // 请假-灰色
- // }
-
- if (projectCount === 0) {
- status = 'idle';
- color = '#d1fae5'; // 空闲-浅绿色(0个项目)
- } else if (projectCount >= 3) {
- status = 'overload';
- color = '#fecaca'; // 超负荷-浅红色(≥3个项目)
- } else {
- status = 'busy';
- color = '#bfdbfe'; // 忙碌-浅蓝色(1-2个项目)
- }
- workloadByDesigner[designerName].push({
- name: `${designerName}-${i}`,
- value: [yIndex, dayStart, dayEnd, designerName, status, projectCount, dayProjects.map(p => p.name)],
- itemStyle: { color }
- });
- }
- });
- // 合并所有数据
- const data = Object.values(workloadByDesigner).flat();
- const option = {
- backgroundColor: '#fff',
- title: {
- text: this.workloadGanttScale === 'week' ? '未来7天工作状态' : '未来30天工作状态',
- subtext: '🟢空闲 🔵忙碌 🔴超负荷',
- left: 'center',
- textStyle: { fontSize: 14, color: '#374151', fontWeight: 600 },
- subtextStyle: { fontSize: 12, color: '#6b7280' }
- },
- tooltip: {
- formatter: (params: any) => {
- const [yIndex, start, end, name, status, projectCount, projectNames = []] = params.value;
- const startDate = new Date(start);
- const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
-
- let statusText = '';
- let statusColor = '';
- let statusBadge = '';
-
- if (status === 'leave') {
- statusText = '请假';
- statusColor = '#6b7280';
- statusBadge = '<span style="background:#e5e7eb;color:#374151;padding:2px 8px;border-radius:4px;font-size:11px;">请假</span>';
- } else if (projectCount === 0) {
- statusText = '空闲';
- statusColor = '#10b981';
- statusBadge = '<span style="background:#d1fae5;color:#059669;padding:2px 8px;border-radius:4px;font-size:11px;">🟢 空闲</span>';
- } else if (projectCount >= 3) {
- statusText = '超负荷';
- statusColor = '#dc2626';
- statusBadge = '<span style="background:#fecaca;color:#dc2626;padding:2px 8px;border-radius:4px;font-size:11px;">🔴 超负荷</span>';
- } else {
- statusText = '忙碌';
- statusColor = '#3b82f6';
- statusBadge = '<span style="background:#bfdbfe;color:#1d4ed8;padding:2px 8px;border-radius:4px;font-size:11px;">🔵 忙碌</span>';
- }
-
- let projectListHtml = '';
- if (projectNames && projectNames.length > 0) {
- projectListHtml = `
- <div style="margin-top: 8px; padding-top: 8px; border-top: 1px dashed #e5e7eb;">
- <div style="font-size: 12px; color: #6b7280; margin-bottom: 4px;">项目列表:</div>
- ${projectNames.slice(0, 5).map((pName: string, idx: number) =>
- `<div style="font-size: 12px; color: #374151; margin-left: 8px;">
- ${idx + 1}. ${pName.length > 20 ? pName.substring(0, 20) + '...' : pName}
- </div>`
- ).join('')}
- ${projectNames.length > 5 ? `<div style="font-size: 12px; color: #6b7280; margin-left: 8px;">...及${projectNames.length - 5}个其他项目</div>` : ''}
- </div>
- `;
- }
-
- return `<div style="padding: 12px; min-width: 220px;">
- <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
- <strong style="font-size: 15px; color: #1f2937;">${name}</strong>
- ${statusBadge}
- </div>
- <div style="color: #6b7280; font-size: 13px;">
- 📅 ${startDate.getMonth() + 1}月${startDate.getDate()}日 ${weekDays[startDate.getDay()]}<br/>
- 📊 项目数量: <span style="font-weight: 600; color: ${statusColor};">${projectCount}个</span>
- </div>
- ${projectListHtml}
- <div style="margin-top: 10px; padding-top: 8px; border-top: 1px solid #e5e7eb; color: #6b7280; font-size: 11px; text-align: center;">
- 💡 点击查看设计师详细信息
- </div>
- </div>`;
- }
- },
- grid: {
- left: 100,
- right: 50,
- top: 60,
- bottom: 60
- },
- xAxis: {
- type: 'time',
- min: xMin,
- max: xMax,
- boundaryGap: false,
- axisLine: { lineStyle: { color: '#e5e7eb' } },
- axisLabel: {
- color: '#6b7280',
- formatter: xLabelFormatter,
- interval: 0,
- rotate: this.workloadGanttScale === 'week' ? 0 : 45,
- showMinLabel: true,
- showMaxLabel: true
- },
- axisTick: {
- alignWithLabel: true,
- interval: 0
- },
- splitLine: {
- show: true,
- lineStyle: { color: '#f1f5f9' }
- },
- splitNumber: xSplitNumber,
- minInterval: DAY
- },
- yAxis: {
- type: 'category',
- data: sortedDesigners,
- inverse: true,
- axisLabel: {
- color: '#374151',
- margin: 8,
- fontSize: 13,
- fontWeight: 500,
- formatter: (value: string) => {
- const totalProjects = designerTotalLoad[value] || 0;
- const icon = totalProjects >= 3 ? '🔥' : totalProjects >= 2 ? '⚡' : totalProjects >= 1 ? '✓' : '○';
- return `${icon} ${value} (${totalProjects})`;
- }
- },
- axisTick: { show: false },
- axisLine: { lineStyle: { color: '#e5e7eb' } }
- },
- series: [
- {
- type: 'custom',
- name: '工作负载',
- renderItem: (params: any, api: any) => {
- const categoryIndex = api.value(0);
- const start = api.coord([api.value(1), categoryIndex]);
- const end = api.coord([api.value(2), categoryIndex]);
- const height = api.size([0, 1])[1] * 0.6;
- const rectShape = echarts.graphic.clipRectByRect({
- x: start[0],
- y: start[1] - height / 2,
- width: Math.max(end[0] - start[0], 2),
- height
- }, {
- x: params.coordSys.x,
- y: params.coordSys.y,
- width: params.coordSys.width,
- height: params.coordSys.height
- });
- return rectShape ? {
- type: 'rect',
- shape: rectShape,
- style: api.style()
- } : undefined;
- },
- encode: { x: [1, 2], y: 0 },
- data,
- z: 2
- }
- ]
- } as any;
- this.workloadGanttChart.setOption(option, true);
-
- // 添加点击事件:点击设计师行时显示详情
- this.workloadGanttChart.on('click', (params: any) => {
- if (params.componentType === 'series' && params.seriesType === 'custom') {
- const designerName = params.value[3]; // value[3]是设计师名称
- if (designerName && designerName !== '未分配') {
- this.onEmployeeClick(designerName);
- }
- }
- });
- }
- ngOnDestroy(): void {
- if (this.ganttChart) {
- this.ganttChart.dispose();
- this.ganttChart = null;
- }
- if (this.workloadGanttChart) {
- this.workloadGanttChart.dispose();
- this.workloadGanttChart = null;
- }
- }
- // 选择单个项目
- selectProject(): void {
- if (this.selectedProjectId) {
- this.router.navigate(['/team-leader/project-detail', this.selectedProjectId]);
- }
- }
- // 获取特定阶段的项目
- getProjectsByStage(stageId: string): Project[] {
- return this.filteredProjects.filter(project => project.currentStage === stageId);
- }
- // 新增:阶段到核心阶段的映射
- private mapStageToCorePhase(stageId: string): 'order' | 'requirements' | 'delivery' | 'aftercare' {
- if (!stageId) return 'order'; // 空值默认为订单分配
-
- // 标准化阶段名称(去除空格,转小写)
- const normalizedStage = stageId.trim().toLowerCase();
-
- // 1. 订单分配阶段(英文ID + 中文名称)
- if (normalizedStage === 'order' ||
- normalizedStage === 'pendingapproval' ||
- normalizedStage === 'pendingassignment' ||
- normalizedStage === '订单分配' ||
- normalizedStage === '待审批' ||
- normalizedStage === '待分配') {
- return 'order';
- }
-
- // 2. 确认需求阶段(英文ID + 中文名称)
- if (normalizedStage === 'requirements' ||
- normalizedStage === 'requirement' ||
- normalizedStage === 'planning' ||
- normalizedStage === '确认需求' ||
- normalizedStage === '需求沟通' ||
- normalizedStage === '方案规划') {
- return 'requirements';
- }
-
- // 3. 交付执行阶段(英文ID + 中文名称)
- if (normalizedStage === 'delivery' ||
- normalizedStage === 'modeling' ||
- normalizedStage === 'rendering' ||
- normalizedStage === 'postproduction' ||
- normalizedStage === 'review' ||
- normalizedStage === 'revision' ||
- normalizedStage === '交付执行' ||
- normalizedStage === '建模' ||
- normalizedStage === '建模阶段' ||
- normalizedStage === '渲染' ||
- normalizedStage === '渲染阶段' ||
- normalizedStage === '后期制作' ||
- normalizedStage === '评审' ||
- normalizedStage === '修改' ||
- normalizedStage === '修订') {
- return 'delivery';
- }
-
- // 4. 售后归档阶段(英文ID + 中文名称)
- if (normalizedStage === 'aftercare' ||
- normalizedStage === 'completed' ||
- normalizedStage === 'archived' ||
- normalizedStage === '售后归档' ||
- normalizedStage === '售后' ||
- normalizedStage === '归档' ||
- normalizedStage === '已完成' ||
- normalizedStage === '已交付') {
- return 'aftercare';
- }
-
- // 未匹配的阶段:默认为交付执行(因为大部分时间项目都在执行中)
- console.warn(`⚠️ 未识别的阶段: "${stageId}" → 默认归类为交付执行`);
- return 'delivery';
- }
- // 新增:获取核心阶段的项目
- getProjectsByCorePhase(coreId: string): Project[] {
- return this.filteredProjects.filter(p => this.mapStageToCorePhase(p.currentStage) === coreId);
- }
- // 新增:获取核心阶段的项目数量
- getProjectCountByCorePhase(coreId: string): number {
- return this.getProjectsByCorePhase(coreId).length;
- }
- // 获取特定阶段的项目数量
- getProjectCountByStage(stageId: string): number {
- return this.getProjectsByStage(stageId).length;
- }
- // 🔥 已延期项目
- get overdueProjects(): Project[] {
- return this.projects.filter(p => p.isOverdue);
- }
- // ⏳ 临期项目(3天内)
- get dueSoonProjects(): Project[] {
- return this.projects.filter(p => p.dueSoon && !p.isOverdue);
- }
- // 📋 待审批项目(支持中文和英文阶段名称)
- get pendingApprovalProjects(): Project[] {
- return this.projects.filter(p => {
- const stage = (p.currentStage || '').trim();
- const data = (p as any).data || {};
- const approvalStatus = data.approvalStatus;
-
- // 1. 阶段为"订单分配"且审批状态为 pending
- // 2. 或者阶段为"待确认"/"待审批"(兼容旧数据)
- return (stage === '订单分配' && approvalStatus === 'pending') ||
- stage === '待审批' ||
- stage === '待确认';
- });
- }
- // 检查项目是否待审批
- isPendingApproval(project: Project): boolean {
- const stage = (project.currentStage || '').trim();
- const data = (project as any).data || {};
- return stage === '订单分配' && data.approvalStatus === 'pending';
- }
- // 🎯 待分配项目(支持中文和英文阶段名称)
- get pendingAssignmentProjects(): Project[] {
- return this.projects.filter(p => {
- const stage = (p.currentStage || '').trim().toLowerCase();
- return stage === 'pendingassignment' ||
- stage === '待分配' ||
- stage === '订单分配';
- });
- }
- // 智能推荐设计师
- private getRecommendedDesigner(projectType: 'soft' | 'hard') {
- if (!this.designerProfiles || !this.designerProfiles.length) return null;
- const scoreOf = (p: any) => {
- const workloadScore = 100 - (p.workload ?? 0); // 负载越低越好
- const ratingScore = (p.avgRating ?? 0) * 10; // 评分越高越好
- const expScore = (p.experience ?? 0) * 5; // 经验越高越好
- return workloadScore * 0.5 + ratingScore * 0.3 + expScore * 0.2;
- };
- const sorted = [...this.designerProfiles].sort((a, b) => scoreOf(b) - scoreOf(a));
- return sorted[0] || null;
- }
- // 质量评审
- reviewProjectQuality(projectId: string, rating: 'excellent' | 'qualified' | 'unqualified'): void {
- const project = this.projects.find(p => p.id === projectId);
- if (!project) return;
- project.qualityRating = rating;
- if (rating === 'unqualified') {
- // 不合格:回退到修改阶段
- project.currentStage = 'revision';
- }
- this.applyFilters();
- window?.fmode?.alert('质量评审已提交');
- }
- // 查看绩效预警(占位:跳转到团队管理)
- viewPerformanceDetails(): void {
- this.router.navigate(['/team-leader/team-management']);
- }
- // 打开负载日历(占位:跳转到团队管理)
- navigateToWorkloadCalendar(): void {
- this.router.navigate(['/team-leader/workload-calendar']);
- }
- // 查看项目详情 - 跳转到纯净的项目详情页(无管理端UI)
- viewProjectDetails(projectId: string): void {
- if (!projectId) {
- return;
- }
-
- // 获取公司ID
- const cid = localStorage.getItem('company') || 'cDL6R1hgSi';
-
- // 跳转到组长端项目详情页(包含审批功能)
- this.router.navigate(['/wxwork', cid, 'team-leader', 'project-detail', projectId]);
- }
- // 快速分配项目(增强:加入智能推荐)
- async quickAssignProject(projectId: string): Promise<void> {
- const project = this.projects.find(p => p.id === projectId);
- if (!project) {
- window?.fmode?.alert('未找到对应项目');
- return;
- }
- const recommended = this.getRecommendedDesigner(project.type);
- if (recommended) {
- const reassigning = !!project.designerName;
- const message = `推荐设计师:${recommended.name}(工作负载:${recommended.workload}%,评分:${recommended.avgRating}分)` +
- (reassigning ? `\n\n该项目当前已由「${project.designerName}」负责,是否改为分配给「${recommended.name}」?` : '\n\n是否确认分配?');
- const confirmAssign = await window?.fmode?.confirm(message);
- if (confirmAssign) {
- project.designerName = recommended.name;
- if (project.currentStage === 'pendingAssignment' || project.currentStage === 'pendingApproval') {
- project.currentStage = 'requirement';
- }
- project.status = '进行中';
- // 更新设计师筛选列表
- this.designers = Array.from(new Set(this.projects.map(p => p.designerName).filter(n => !!n)));
- this.applyFilters();
- window?.fmode?.alert(`项目已${reassigning ? '重新' : ''}分配给 ${recommended.name}`);
- return;
- }
- }
- // 无推荐或用户取消,跳转到详细分配页面
- // 改为跳转到复用详情(组长视图),通过 query 参数标记 assign 模式
- this.router.navigate(['/team-leader/project-detail', projectId], { queryParams: { mode: 'assign' } });
- }
- // 导航到待办任务
- navigateToTask(task: TodoTask): void {
- switch (task.type) {
- case 'review':
- this.router.navigate(['team-leader/quality-management', task.targetId]);
- break;
- case 'assign':
- this.router.navigate(['/team-leader/dashboard']);
- break;
- case 'performance':
- this.router.navigate(['team-leader/team-management']);
- break;
- }
- }
- // 获取优先级标签
- getPriorityLabel(priority: 'high' | 'medium' | 'low'): string {
- const labels: Record<'high' | 'medium' | 'low', string> = {
- 'high': '紧急且重要',
- 'medium': '重要不紧急',
- 'low': '紧急不重要'
- };
- return labels[priority];
- }
- // 导航到团队管理
- navigateToTeamManagement(): void {
- this.router.navigate(['/team-leader/team-management']);
- }
- // 导航到项目评审
- navigateToProjectReview(): void {
- // 统一入口:跳转到项目列表/看板,而非旧评审页
- this.router.navigate(['/team-leader/dashboard']);
- }
- // 导航到质量管理
- navigateToQualityManagement(): void {
- this.router.navigate(['/team-leader/quality-management']);
- }
- // 打开工作量预估工具(已迁移)
- openWorkloadEstimator(): void {
- // 工具迁移至详情页:引导前往当前选中项目详情
- if (this.selectedProjectId) {
- this.router.navigate(['/team-leader/project-detail', this.selectedProjectId], { queryParams: { tool: 'estimator' } });
- } else {
- this.router.navigate(['/team-leader/dashboard']);
- }
- window?.fmode?.alert('工作量预估工具已迁移至项目详情页,您可以在建模阶段之前使用该工具进行工作量计算。');
- }
- // 查看所有超期项目
- viewAllOverdueProjects(): void {
- this.filterByStatus('overdue');
- this.closeAlert();
- }
- // 关闭提醒
- closeAlert(): void {
- this.showAlert = false;
- }
- resetStatusFilter(): void {
- this.selectedStatus = 'all';
- this.applyFilters();
- }
- // 处理甘特图员工点击事件
- async onEmployeeClick(employeeName: string): Promise<void> {
- if (!employeeName || employeeName === '未分配') {
- return;
- }
-
- // 生成员工详情数据
- this.selectedEmployeeDetail = await this.generateEmployeeDetail(employeeName);
- this.showEmployeeDetailPanel = true;
- }
- // 生成员工详情数据
- private async generateEmployeeDetail(employeeName: string): Promise<EmployeeDetail> {
- // 从 ProjectTeam 表获取该员工负责的项目
- const employeeProjects = this.designerWorkloadMap.get(employeeName) || [];
- const currentProjects = employeeProjects.length;
-
- // 保存完整的项目数据(最多显示3个)
- const projectData = employeeProjects.slice(0, 3).map(p => ({
- id: p.id,
- name: p.name
- }));
-
- const projectNames = projectData.map(p => p.name); // 项目名称列表
-
- // 获取该员工的请假记录(未来7天)
- const today = new Date();
- const next7Days = Array.from({ length: 7 }, (_, i) => {
- const date = new Date(today);
- date.setDate(today.getDate() + i);
- return date.toISOString().split('T')[0]; // YYYY-MM-DD 格式
- });
-
- const employeeLeaveRecords = this.leaveRecords.filter(record =>
- record.employeeName === employeeName && next7Days.includes(record.date)
- );
-
- // 生成红色标记说明
- const redMarkExplanation = this.generateRedMarkExplanation(employeeName, employeeLeaveRecords, currentProjects);
-
- // 生成日历数据
- const calendarData = this.generateEmployeeCalendar(employeeName, employeeProjects);
-
- // 新增:加载问卷数据
- let surveyCompleted = false;
- let surveyData = null;
- let profileId = '';
-
- try {
- const Parse = await import('fmode-ng/parse').then(m => m.FmodeParse.with('nova'));
-
- // 通过员工名字查找Profile(同时查询 realname 和 name 字段)
- const realnameQuery = new Parse.Query('Profile');
- realnameQuery.equalTo('realname', employeeName);
-
- const nameQuery = new Parse.Query('Profile');
- nameQuery.equalTo('name', employeeName);
-
- // 使用 or 查询
- const profileQuery = Parse.Query.or(realnameQuery, nameQuery);
- profileQuery.limit(1);
-
- const profileResults = await profileQuery.find();
-
- console.log(`🔍 查找员工 ${employeeName},找到 ${profileResults.length} 个结果`);
-
- if (profileResults.length > 0) {
- const profile = profileResults[0];
- profileId = profile.id;
- surveyCompleted = profile.get('surveyCompleted') || false;
-
- console.log(`📋 Profile ID: ${profileId}, surveyCompleted: ${surveyCompleted}`);
-
- // 如果已完成问卷,加载问卷答案
- if (surveyCompleted) {
- const surveyQuery = new Parse.Query('SurveyLog');
- surveyQuery.equalTo('profile', profile.toPointer());
- surveyQuery.equalTo('type', 'survey-profile');
- surveyQuery.descending('createdAt');
- surveyQuery.limit(1);
-
- const surveyResults = await surveyQuery.find();
- console.log(`📝 找到 ${surveyResults.length} 条问卷记录`);
-
- if (surveyResults.length > 0) {
- const survey = surveyResults[0];
- surveyData = {
- answers: survey.get('answers') || [],
- createdAt: survey.get('createdAt'),
- updatedAt: survey.get('updatedAt')
- };
- console.log(`✅ 加载问卷数据成功,共 ${surveyData.answers.length} 道题`);
- }
- }
- } else {
- console.warn(`⚠️ 未找到员工 ${employeeName} 的 Profile`);
- }
-
- console.log(`📋 员工 ${employeeName} 问卷状态:`, surveyCompleted ? '已完成' : '未完成');
- } catch (error) {
- console.error(`❌ 加载员工 ${employeeName} 问卷数据失败:`, error);
- }
-
- return {
- name: employeeName,
- currentProjects,
- projectNames,
- projectData,
- leaveRecords: employeeLeaveRecords,
- redMarkExplanation,
- calendarData,
- // 新增字段
- surveyCompleted,
- surveyData,
- profileId
- };
- }
-
- /**
- * 生成员工日历数据(当前月份)
- */
- private generateEmployeeCalendar(employeeName: string, employeeProjects: any[]): EmployeeCalendarData {
- const currentMonth = new Date();
- const year = currentMonth.getFullYear();
- const month = currentMonth.getMonth();
-
- // 获取当月天数
- const daysInMonth = new Date(year, month + 1, 0).getDate();
- const days: EmployeeCalendarDay[] = [];
- const today = new Date();
- today.setHours(0, 0, 0, 0);
-
- // 生成当月每一天的数据
- for (let day = 1; day <= daysInMonth; day++) {
- const date = new Date(year, month, day);
- const dateStr = date.toISOString().split('T')[0];
-
- // 找出该日期相关的项目(项目进行中且在当天范围内)
- const dayProjects = employeeProjects.filter(p => {
- // 处理 Parse Date 对象:检查是否有 toDate 方法
- const getDate = (dateValue: any) => {
- if (!dateValue) return null;
- if (dateValue.toDate && typeof dateValue.toDate === 'function') {
- return dateValue.toDate(); // Parse Date对象
- }
- if (dateValue instanceof Date) {
- return dateValue;
- }
- return new Date(dateValue); // 字符串或时间戳
- };
-
- const deadlineDate = getDate(p.deadline);
- const createdDate = p.createdAt ? getDate(p.createdAt) : null;
-
- // 如果项目既没有 deadline 也没有 createdAt,则跳过
- if (!deadlineDate && !createdDate) {
- return false;
- }
-
- // 智能处理日期范围
- let startDate: Date;
- let endDate: Date;
-
- if (deadlineDate && createdDate) {
- // 情况1:两个日期都有
- startDate = createdDate;
- endDate = deadlineDate;
- } else if (deadlineDate) {
- // 情况2:只有deadline,往前推30天
- startDate = new Date(deadlineDate.getTime() - 30 * 24 * 60 * 60 * 1000);
- endDate = deadlineDate;
- } else {
- // 情况3:只有createdAt,往后推30天
- startDate = createdDate!;
- endDate = new Date(createdDate!.getTime() + 30 * 24 * 60 * 60 * 1000);
- }
-
- startDate.setHours(0, 0, 0, 0);
- endDate.setHours(0, 0, 0, 0);
-
- const inRange = date >= startDate && date <= endDate;
-
- return inRange;
- }).map(p => {
- const getDate = (dateValue: any) => {
- if (!dateValue) return undefined;
- if (dateValue.toDate && typeof dateValue.toDate === 'function') {
- return dateValue.toDate();
- }
- if (dateValue instanceof Date) {
- return dateValue;
- }
- return new Date(dateValue);
- };
-
- return {
- id: p.id,
- name: p.name,
- deadline: getDate(p.deadline)
- };
- });
-
- days.push({
- date,
- projectCount: dayProjects.length,
- projects: dayProjects,
- isToday: date.getTime() === today.getTime(),
- isCurrentMonth: true
- });
- }
-
- // 补齐前后的日期(保证从周日开始)
- const firstDay = new Date(year, month, 1);
- const firstDayOfWeek = firstDay.getDay(); // 0=周日
-
- // 前置补齐(上个月的日期)
- for (let i = firstDayOfWeek - 1; i >= 0; i--) {
- const date = new Date(year, month, -i);
- days.unshift({
- date,
- projectCount: 0,
- projects: [],
- isToday: false,
- isCurrentMonth: false
- });
- }
-
- // 后置补齐(下个月的日期,保证总数是7的倍数)
- const remainder = days.length % 7;
- if (remainder !== 0) {
- const needed = 7 - remainder;
- for (let i = 1; i <= needed; i++) {
- const date = new Date(year, month + 1, i);
- days.push({
- date,
- projectCount: 0,
- projects: [],
- isToday: false,
- isCurrentMonth: false
- });
- }
- }
-
- return {
- currentMonth: new Date(year, month, 1),
- days
- };
- }
-
- /**
- * 处理日历日期点击
- */
- onCalendarDayClick(day: EmployeeCalendarDay): void {
- if (!day.isCurrentMonth || day.projectCount === 0) {
- return;
- }
-
- this.selectedDate = day.date;
- this.selectedDayProjects = day.projects;
- this.showCalendarProjectList = true;
- }
-
- /**
- * 关闭项目列表弹窗
- */
- closeCalendarProjectList(): void {
- this.showCalendarProjectList = false;
- this.selectedDate = null;
- this.selectedDayProjects = [];
- }
- // 生成红色标记说明
- private generateRedMarkExplanation(employeeName: string, leaveRecords: LeaveRecord[], projectCount: number): string {
- const explanations: string[] = [];
-
- // 检查请假情况
- const leaveDays = leaveRecords.filter(record => record.isLeave);
- if (leaveDays.length > 0) {
- leaveDays.forEach(leave => {
- const date = new Date(leave.date);
- const dateStr = `${date.getMonth() + 1}月${date.getDate()}日`;
- explanations.push(`${dateStr}(${leave.reason || '请假'})`);
- });
- }
-
- // 检查项目繁忙情况
- if (projectCount >= 3) {
- const today = new Date();
- const dateStr = `${today.getMonth() + 1}月${today.getDate()}日`;
- explanations.push(`${dateStr}(${projectCount}个项目繁忙)`);
- }
-
- if (explanations.length === 0) {
- return '当前无红色标记时段';
- }
-
- return `甘特图中红色时段说明:${explanations.map((exp, index) => `${index + 1}${exp}`).join(';')}`;
- }
- // 关闭员工详情面板
- closeEmployeeDetailPanel(): void {
- this.showEmployeeDetailPanel = false;
- this.selectedEmployeeDetail = null;
- this.showFullSurvey = false; // 重置问卷显示状态
- }
- /**
- * 刷新员工问卷状态
- */
- async refreshEmployeeSurvey(): Promise<void> {
- if (this.refreshingSurvey || !this.selectedEmployeeDetail) {
- return;
- }
- try {
- this.refreshingSurvey = true;
- console.log('🔄 刷新问卷状态...');
- const employeeName = this.selectedEmployeeDetail.name;
-
- // 重新加载员工详情数据
- const updatedDetail = await this.generateEmployeeDetail(employeeName);
-
- // 更新当前显示的员工详情
- this.selectedEmployeeDetail = updatedDetail;
-
- console.log('✅ 问卷状态刷新成功');
-
- } catch (error) {
- console.error('❌ 刷新问卷状态失败:', error);
- } finally {
- this.refreshingSurvey = false;
- }
- }
- /**
- * 切换问卷显示模式
- */
- toggleSurveyDisplay(): void {
- this.showFullSurvey = !this.showFullSurvey;
- }
- /**
- * 获取能力画像摘要
- */
- getCapabilitySummary(answers: any[]): any {
- const findAnswer = (questionId: string) => {
- const item = answers.find(a => a.questionId === questionId);
- return item?.answer;
- };
- const formatArray = (value: any): string => {
- if (Array.isArray(value)) {
- return value.join('、');
- }
- return value || '未填写';
- };
- return {
- styles: formatArray(findAnswer('q1_expertise_styles')),
- spaces: formatArray(findAnswer('q2_expertise_spaces')),
- advantages: formatArray(findAnswer('q3_technical_advantages')),
- difficulty: findAnswer('q5_project_difficulty') || '未填写',
- capacity: findAnswer('q7_weekly_capacity') || '未填写',
- urgent: findAnswer('q8_urgent_willingness') || '未填写',
- urgentLimit: findAnswer('q8_urgent_limit') || '',
- feedback: findAnswer('q9_progress_feedback') || '未填写',
- communication: formatArray(findAnswer('q12_communication_methods'))
- };
- }
- // 从员工详情面板跳转到项目详情
- navigateToProjectFromPanel(projectId: string): void {
- if (!projectId) {
- return;
- }
-
- // 关闭员工详情面板
- this.closeEmployeeDetailPanel();
-
- // 跳转到项目详情页(使用纯净的wxwork路由)
- const cid = localStorage.getItem('company') || 'cDL6R1hgSi';
- this.router.navigate(['/wxwork', cid, 'project', projectId, 'order']);
- }
- // 获取请假类型显示文本
- getLeaveTypeText(leaveType?: string): string {
- const typeMap: Record<string, string> = {
- 'sick': '病假',
- 'personal': '事假',
- 'annual': '年假',
- 'other': '其他'
- };
- return typeMap[leaveType || ''] || '请假';
- }
- // 生成请假覆盖层数据
- private generateLeaveOverlayData(categories: string[], xMin: number, xMax: number): any[] {
- const DAY = 24 * 60 * 60 * 1000;
- const overlayData: any[] = [];
- categories.forEach((employeeName, yIndex) => {
- // 获取该员工在时间范围内的请假记录
- const employeeLeaves = this.leaveRecords.filter(record => {
- if (record.employeeName !== employeeName || !record.isLeave) {
- return false;
- }
-
- const recordDate = new Date(record.date).getTime();
- return recordDate >= xMin && recordDate <= xMax;
- });
- // 为每个请假日期创建覆盖层
- employeeLeaves.forEach(leave => {
- const leaveDate = new Date(leave.date);
- const startOfDay = new Date(leaveDate.getFullYear(), leaveDate.getMonth(), leaveDate.getDate()).getTime();
- const endOfDay = startOfDay + DAY - 1;
- overlayData.push({
- name: `${employeeName} - ${this.getLeaveTypeText(leave.leaveType)}`,
- value: [yIndex, startOfDay, endOfDay, employeeName, leave.leaveType, leave.reason],
- itemStyle: {
- color: 'rgba(239, 68, 68, 0.6)', // 半透明红色
- borderColor: '#ef4444',
- borderWidth: 1
- }
- });
- });
- // 检查项目繁忙情况,如果项目数>=3,也添加红色标记
- const employeeProjects = this.designerWorkloadMap.get(employeeName) || [];
- if (employeeProjects.length >= 3) {
- // 在当前日期添加繁忙标记
- const today = new Date();
- const startOfToday = new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime();
- const endOfToday = startOfToday + DAY - 1;
- if (startOfToday >= xMin && startOfToday <= xMax) {
- overlayData.push({
- name: `${employeeName} - 项目繁忙(${employeeProjects.length}个项目)`,
- value: [yIndex, startOfToday, endOfToday, employeeName, 'busy', `负责${employeeProjects.length}个项目`],
- itemStyle: {
- color: 'rgba(239, 68, 68, 0.4)', // 稍微透明的红色
- borderColor: '#ef4444',
- borderWidth: 1,
- borderType: 'dashed' // 虚线边框区分请假和繁忙
- }
- });
- }
- }
- });
- return overlayData;
- }
- /**
- * 加载用户Profile信息
- */
- async loadUserProfile(): Promise<void> {
- try {
- const cid = localStorage.getItem("company");
- if (!cid) {
- console.warn('未找到公司ID,使用默认用户信息');
- return;
- }
- const wwAuth = new WxworkAuth({ cid });
- const profile = await wwAuth.currentProfile();
- if (profile) {
- const name = profile.get("name") || profile.get("mobile") || '组长';
- const avatar = profile.get("avatar");
- const roleName = profile.get("roleName") || '组长';
- this.currentUser = {
- name,
- avatar: avatar || this.generateDefaultAvatar(name),
- roleName
- };
- console.log('用户Profile加载成功:', this.currentUser);
- }
- } catch (error) {
- console.error('加载用户Profile失败:', error);
- // 保持默认值
- }
- }
- /**
- * 生成默认头像(SVG格式)
- * @param name 用户名
- * @returns Base64编码的SVG数据URL
- */
- generateDefaultAvatar(name: string): string {
- const initial = name ? name.substring(0, 2).toUpperCase() : '组长';
- const bgColor = '#CCFFCC';
- const textColor = '#555555';
-
- const svg = `<svg width='40' height='40' xmlns='http://www.w3.org/2000/svg'>
- <rect width='100%' height='100%' fill='${bgColor}'/>
- <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>
- </svg>`;
-
- return `data:image/svg+xml,${encodeURIComponent(svg)}`;
- }
- }
|