index.vue 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224
  1. <template>
  2. <div class="ele-body factory-calendar">
  3. <el-card shadow="never" class="factory-calendar-card">
  4. <div class="factory-calendar-view-head">
  5. <div>
  6. <h3>多维日历视图</h3>
  7. <p>统一查看生产、设备维护、人员排班等日历维度</p>
  8. </div>
  9. <el-button size="small" icon="el-icon-refresh" @click="refreshRemoteView">
  10. 刷新视图
  11. </el-button>
  12. </div>
  13. <multi-calendar-view :vm="vm" />
  14. </el-card>
  15. <ele-modal
  16. :visible.sync="calendarDialogVisible"
  17. :title="calendarDialogTitle"
  18. width="900px"
  19. custom-class="ele-dialog-form factory-calendar-dialog"
  20. :close-on-click-modal="false"
  21. >
  22. <el-form
  23. ref="calendarForm"
  24. :model="calendarForm"
  25. :rules="calendarRules"
  26. label-width="110px"
  27. class="el-form-box"
  28. >
  29. <el-form-item label="日历编码">
  30. <el-input v-model="calendarForm.calendarCode" disabled />
  31. </el-form-item>
  32. <el-form-item label="日历名称" prop="calendarName">
  33. <el-input v-model="calendarForm.calendarName" maxlength="128" />
  34. </el-form-item>
  35. <el-form-item label="日历类型" prop="calendarType">
  36. <el-select
  37. v-model="calendarForm.calendarType"
  38. :disabled="!!calendarForm.id"
  39. style="width: 100%"
  40. >
  41. <el-option
  42. v-for="item in calendarTypeOptions"
  43. :key="item.value"
  44. :label="item.label"
  45. :value="item.value"
  46. />
  47. </el-select>
  48. </el-form-item>
  49. <el-form-item label="适用年份" prop="applyYear">
  50. <el-select v-model="calendarFormApplyYear" style="width: 100%">
  51. <el-option
  52. v-for="year in yearOptions"
  53. :key="year"
  54. :label="year"
  55. :value="year"
  56. />
  57. </el-select>
  58. </el-form-item>
  59. <el-form-item label="适用月份" prop="applyMonth">
  60. <el-select
  61. v-model="calendarForm.applyMonth"
  62. multiple
  63. style="width: 100%"
  64. @change="handleApplyMonthChange"
  65. >
  66. <el-option
  67. v-for="month in monthOptions"
  68. :key="month.value"
  69. :label="month.label"
  70. :value="month.value"
  71. />
  72. </el-select>
  73. </el-form-item>
  74. <el-form-item label="状态">
  75. <el-switch
  76. v-model="calendarForm.status"
  77. :active-value="1"
  78. :inactive-value="0"
  79. active-text="启用"
  80. inactive-text="禁用"
  81. />
  82. </el-form-item>
  83. <el-form-item label="周休设置">
  84. <div class="rest-rule-editor">
  85. <el-radio-group v-model="calendarForm.restMode">
  86. <el-radio-button
  87. v-for="item in restModeOptions"
  88. :key="item.value"
  89. :label="item.value"
  90. >
  91. {{ item.label }}
  92. </el-radio-button>
  93. </el-radio-group>
  94. <el-checkbox-group
  95. v-if="calendarForm.restMode === 'custom'"
  96. v-model="calendarForm.restWeekdays"
  97. class="custom-rest-weekdays"
  98. >
  99. <el-checkbox-button
  100. v-for="item in restWeekdayOptions"
  101. :key="item.value"
  102. :label="item.value"
  103. >
  104. {{ item.label }}
  105. </el-checkbox-button>
  106. </el-checkbox-group>
  107. <div class="rule-tip">
  108. 双休为周六周日休,单休为周日休,大小周为周日固定休且隔周周六休,自定义可勾选任意休息星期。
  109. </div>
  110. </div>
  111. </el-form-item>
  112. <el-form-item v-if="showLegalHolidaySection" label="法定节假日">
  113. <div class="legal-holiday-section">
  114. <div class="legal-holiday-header">
  115. <div>
  116. <div class="legal-holiday-title">法定节假日</div>
  117. <div class="legal-holiday-desc">
  118. 默认休息,点选日期后按上班处理
  119. </div>
  120. </div>
  121. <span class="legal-holiday-count">
  122. {{
  123. legalHolidayLoading
  124. ? '同步节假日中...'
  125. : `${legalHolidaySourceText},已设上班 ${legalHolidayVisibleWorkCount} 天`
  126. }}
  127. </span>
  128. </div>
  129. <div v-if="legalHolidayGroups.length" class="legal-holiday-list">
  130. <div
  131. v-for="group in legalHolidayGroups"
  132. :key="group.name"
  133. class="legal-holiday-group"
  134. >
  135. <div class="legal-holiday-group-head">
  136. <strong>{{ group.name }}</strong>
  137. <span>{{ group.dates.length }}天</span>
  138. </div>
  139. <div class="legal-holiday-dates">
  140. <button
  141. v-for="item in group.dates"
  142. :key="item.calendarDate"
  143. type="button"
  144. class="legal-holiday-date"
  145. :class="{
  146. 'is-work': calendarForm.legalHolidayWorkDates.includes(
  147. item.calendarDate
  148. )
  149. }"
  150. @click="toggleLegalHolidayWorkStatus(item.calendarDate)"
  151. >
  152. <span>{{ formatHolidayDate(item.calendarDate) }}</span>
  153. <em>
  154. {{
  155. calendarForm.legalHolidayWorkDates.includes(
  156. item.calendarDate
  157. )
  158. ? '上班'
  159. : '休息'
  160. }}
  161. </em>
  162. </button>
  163. </div>
  164. </div>
  165. </div>
  166. </div>
  167. </el-form-item>
  168. <el-form-item label="特殊日期">
  169. <div class="holiday-rule-editor">
  170. <div
  171. v-for="(rule, index) in calendarForm.holidayRules"
  172. :key="rule.id"
  173. class="holiday-rule-row"
  174. >
  175. <el-date-picker
  176. v-model="rule.calendarDate"
  177. type="date"
  178. value-format="yyyy-MM-dd"
  179. placeholder="选择日期"
  180. style="width: 160px"
  181. />
  182. <el-select
  183. v-model="rule.dateType"
  184. placeholder="日期类型"
  185. style="width: 130px"
  186. >
  187. <el-option label="上班" :value="1" />
  188. <el-option label="休息" :value="2" />
  189. <el-option label="法定节假日" :value="3" />
  190. </el-select>
  191. <el-input
  192. v-model="rule.remark"
  193. placeholder="备注"
  194. maxlength="80"
  195. style="flex: 1"
  196. />
  197. <el-button
  198. type="text"
  199. icon="el-icon-delete"
  200. class="danger-link"
  201. @click="removeHolidayRule(index)"
  202. >
  203. 删除
  204. </el-button>
  205. </div>
  206. <el-button size="small" icon="el-icon-plus" @click="addHolidayRule">
  207. 新增特殊日期
  208. </el-button>
  209. <div class="rule-tip">
  210. 特殊日期优先级高于周休设置,可把周末设为上班,也可把工作日设为休息或法定节假日。
  211. </div>
  212. </div>
  213. </el-form-item>
  214. <el-form-item label="备注">
  215. <el-input
  216. v-model="calendarForm.remark"
  217. type="textarea"
  218. :rows="3"
  219. maxlength="500"
  220. show-word-limit
  221. />
  222. </el-form-item>
  223. </el-form>
  224. <div slot="footer">
  225. <el-button type="primary" @click="saveCalendar">确定</el-button>
  226. <el-button @click="calendarDialogVisible = false">取消</el-button>
  227. </div>
  228. </ele-modal>
  229. <ele-modal
  230. :visible.sync="copyDialogVisible"
  231. title="复制日历配置"
  232. width="520px"
  233. custom-class="ele-dialog-form"
  234. >
  235. <el-form :model="copyForm" label-width="100px" class="el-form-box">
  236. <el-form-item label="源日历">
  237. <el-select v-model="copyForm.sourceId" style="width: 100%">
  238. <el-option
  239. v-for="item in calendars"
  240. :key="item.id"
  241. :label="item.calendarName"
  242. :value="item.id"
  243. />
  244. </el-select>
  245. </el-form-item>
  246. <el-form-item label="目标年份">
  247. <el-select v-model="copyForm.targetYear" style="width: 100%">
  248. <el-option
  249. v-for="year in yearOptions"
  250. :key="year"
  251. :label="year"
  252. :value="year"
  253. />
  254. </el-select>
  255. </el-form-item>
  256. </el-form>
  257. <div slot="footer">
  258. <el-button type="primary" @click="copyCalendar">确定</el-button>
  259. <el-button @click="copyDialogVisible = false">取消</el-button>
  260. </div>
  261. </ele-modal>
  262. <ele-modal
  263. :visible.sync="adjustDialogVisible"
  264. title="临时调整申请"
  265. width="720px"
  266. custom-class="ele-dialog-form"
  267. :close-on-click-modal="false"
  268. >
  269. <el-form
  270. ref="adjustForm"
  271. :model="adjustForm"
  272. :rules="adjustRules"
  273. label-width="120px"
  274. class="el-form-box"
  275. >
  276. <el-form-item label="关联日历" prop="calendarId">
  277. <el-select v-model="adjustForm.calendarId" style="width: 100%">
  278. <el-option
  279. v-for="item in enabledCalendars"
  280. :key="item.id"
  281. :label="item.calendarName"
  282. :value="item.id"
  283. />
  284. </el-select>
  285. </el-form-item>
  286. <el-form-item label="调整类型" prop="adjustType">
  287. <el-select v-model="adjustForm.adjustType" style="width: 100%">
  288. <el-option
  289. v-for="item in adjustTypeOptions"
  290. :key="item.value"
  291. :label="item.label"
  292. :value="item.value"
  293. />
  294. </el-select>
  295. </el-form-item>
  296. <el-form-item label="调整日期" prop="adjustDate">
  297. <el-date-picker
  298. v-model="adjustForm.adjustDate"
  299. type="date"
  300. value-format="yyyy-MM-dd"
  301. style="width: 100%"
  302. />
  303. </el-form-item>
  304. <el-form-item label="调整时段" required>
  305. <div class="inline-time">
  306. <el-time-select
  307. v-model="adjustForm.startTime"
  308. placeholder="开始时间"
  309. :picker-options="timePickerOptions"
  310. />
  311. <span>至</span>
  312. <el-time-select
  313. v-model="adjustForm.endTime"
  314. placeholder="结束时间"
  315. :picker-options="getTimePickerOptions(adjustForm.startTime)"
  316. />
  317. </div>
  318. </el-form-item>
  319. <el-form-item label="生效时间" prop="effectiveTime">
  320. <el-date-picker
  321. v-model="adjustForm.effectiveTime"
  322. type="datetime"
  323. value-format="yyyy-MM-dd HH:mm:ss"
  324. style="width: 100%"
  325. />
  326. </el-form-item>
  327. <el-form-item label="失效时间" prop="expireTime">
  328. <el-date-picker
  329. v-model="adjustForm.expireTime"
  330. type="datetime"
  331. value-format="yyyy-MM-dd HH:mm:ss"
  332. style="width: 100%"
  333. />
  334. </el-form-item>
  335. <el-form-item label="调整原因" prop="applyReason">
  336. <el-input
  337. v-model="adjustForm.applyReason"
  338. type="textarea"
  339. :rows="3"
  340. maxlength="500"
  341. show-word-limit
  342. />
  343. </el-form-item>
  344. </el-form>
  345. <div slot="footer">
  346. <el-button type="primary" @click="submitAdjust">提交审批</el-button>
  347. <el-button @click="adjustDialogVisible = false">取消</el-button>
  348. </div>
  349. </ele-modal>
  350. <el-drawer
  351. :visible.sync="dayDrawerVisible"
  352. :title="dayDrawerTitle"
  353. size="460px"
  354. append-to-body
  355. custom-class="calendar-day-drawer"
  356. >
  357. <div class="drawer-body" v-if="currentDay.date">
  358. <div class="drawer-summary">
  359. <div class="summary-date">
  360. <span>{{ drawerDateMonth }}</span>
  361. <strong>{{ drawerDateDay }}</strong>
  362. </div>
  363. <div class="summary-info">
  364. <div class="summary-title">
  365. {{ getDateTypeText(currentDay) }}
  366. <el-tag
  367. size="mini"
  368. :type="currentDay.scheduleStatus ? 'success' : 'info'"
  369. >
  370. {{ currentDay.scheduleStatus ? '已排班' : '未排班' }}
  371. </el-tag>
  372. </div>
  373. <p>{{ getRangeText(currentDay.details) }}</p>
  374. <div class="summary-tags">
  375. <el-tag v-if="currentDay.isRest" size="mini" type="info">
  376. 休息/节假日
  377. </el-tag>
  378. <el-tag v-if="currentDay.isTempAdjust" size="mini">
  379. 临时调整
  380. </el-tag>
  381. <el-tag v-if="currentDay.isConflict" size="mini" type="danger">
  382. 存在冲突
  383. </el-tag>
  384. <el-tag v-if="currentDay.planCount" size="mini" type="warning">
  385. {{ currentDay.planCount }} 个计划
  386. </el-tag>
  387. </div>
  388. </div>
  389. </div>
  390. <div class="drawer-section">
  391. <div class="drawer-title">
  392. <span>时段明细</span>
  393. <em>{{ currentDay.details.length }} 条</em>
  394. </div>
  395. <div class="detail-timeline">
  396. <div
  397. v-for="detail in currentDay.details"
  398. :key="detail.id"
  399. class="detail-item"
  400. >
  401. <div class="detail-time">
  402. <strong>{{ detail.startTime }} - {{ detail.endTime }}</strong>
  403. </div>
  404. <div class="detail-content">
  405. <div>
  406. <strong>{{
  407. detail.dutyName ||
  408. getLabel(dateTypeOptions, detail.dateType)
  409. }}</strong>
  410. <span>{{ detail.startTime }}-{{ detail.endTime }}</span>
  411. </div>
  412. <el-tag
  413. size="mini"
  414. :type="detail.scheduleStatus ? 'success' : 'info'"
  415. >
  416. {{ detail.scheduleStatus ? '已排班' : '未排班' }}
  417. </el-tag>
  418. <div
  419. v-if="
  420. detail.productionLineName ||
  421. detail.workStationName ||
  422. detail.productionShift ||
  423. detail.workingHours ||
  424. detail.restTime
  425. "
  426. class="detail-meta"
  427. >
  428. <span v-if="detail.productionLineName"
  429. >产线:{{ detail.productionLineName }}</span
  430. >
  431. <span v-if="detail.workStationName"
  432. >工位:{{ detail.workStationName }}</span
  433. >
  434. <span v-if="detail.productionShift"
  435. >班次:{{ detail.productionShift }}</span
  436. >
  437. <span v-if="detail.workingHours"
  438. >工时:{{ detail.workingHours }}分钟</span
  439. >
  440. <span v-if="detail.restTime"
  441. >休息:{{ detail.restTime }}分钟</span
  442. >
  443. </div>
  444. </div>
  445. </div>
  446. </div>
  447. </div>
  448. <div class="drawer-section">
  449. <div class="drawer-title">
  450. <span>{{ relatedSectionTitle }}</span>
  451. <em>{{ relatedPlans.length }} 条</em>
  452. </div>
  453. <div v-if="relatedPlans.length" class="plan-list">
  454. <el-tooltip
  455. v-for="plan in relatedPlans"
  456. :key="plan.id"
  457. placement="top"
  458. effect="light"
  459. >
  460. <div slot="content" class="plan-tooltip">
  461. <template v-if="isTeamQueueDrawer">
  462. <div>排班名称:{{ getRelatedQueueName(plan) }}</div>
  463. <div>人员:{{ getRelatedQueueUserName(plan) || '-' }}</div>
  464. </template>
  465. <template v-else>
  466. <div>
  467. {{ isEquipmentDrawer ? '设备编码' : '计划编号' }}:{{
  468. getRelatedPlanCode(plan)
  469. }}
  470. </div>
  471. <div>
  472. {{ isEquipmentDrawer ? '设备名称' : '计划名称' }}:{{
  473. getRelatedPlanName(plan)
  474. }}
  475. </div>
  476. <div v-if="!isEquipmentDrawer">
  477. 订单编号:{{ plan.orderNo || '-' }}
  478. </div>
  479. <div v-if="!isEquipmentDrawer">
  480. 计划数量:{{ plan.requiredFormingNum || '-' }}
  481. </div>
  482. <div>开始时间:{{ plan.displayStartTime || '-' }}</div>
  483. <div>结束时间:{{ plan.displayEndTime || '-' }}</div>
  484. </template>
  485. </div>
  486. <div
  487. class="plan-item"
  488. :class="{ 'team-queue-item': isTeamQueueDrawer }"
  489. >
  490. <div v-if="isTeamQueueDrawer" class="plan-main team-queue-plan">
  491. <div class="queue-avatar">
  492. <i class="el-icon-user-solid"></i>
  493. </div>
  494. <div class="queue-info">
  495. <div class="plan-name queue-name-only">
  496. <span class="queue-name-label">排班名称:</span>
  497. <span class="queue-name-text">
  498. {{ getRelatedQueueName(plan) }}
  499. </span>
  500. </div>
  501. <div class="queue-user-name">
  502. <i class="el-icon-user"></i>
  503. <span>人员:</span>
  504. <strong>
  505. {{ getRelatedQueueUserName(plan) || '-' }}
  506. </strong>
  507. </div>
  508. </div>
  509. <div class="queue-badge">排班</div>
  510. </div>
  511. <div v-else class="plan-main">
  512. <div class="plan-topline">
  513. <strong>{{ plan.planNo }}</strong>
  514. <span v-if="plan.orderNo">{{ plan.orderNo }}</span>
  515. </div>
  516. <div class="plan-name">{{ plan.taskName }}</div>
  517. <div class="plan-bottomline">
  518. <span class="plan-metrics">
  519. <em
  520. v-if="
  521. plan.requiredFormingNum !== undefined &&
  522. plan.requiredFormingNum !== null
  523. "
  524. >
  525. 数量 {{ plan.requiredFormingNum }}
  526. </em>
  527. <em v-if="plan.displayStartTime || plan.displayEndTime">
  528. {{ plan.displayStartTime || '-' }} -
  529. {{ plan.displayEndTime || '-' }}
  530. </em>
  531. </span>
  532. </div>
  533. </div>
  534. </div>
  535. </el-tooltip>
  536. </div>
  537. <el-empty
  538. v-else
  539. class="drawer-empty"
  540. description="暂无关联计划"
  541. :image-size="92"
  542. />
  543. </div>
  544. </div>
  545. <!-- <div class="drawer-actions" v-if="currentDay.date">
  546. <el-button
  547. size="small"
  548. icon="el-icon-check"
  549. @click="toggleScheduleStatus(1)"
  550. >
  551. 完成排班
  552. </el-button>
  553. <el-button
  554. size="small"
  555. icon="el-icon-refresh-left"
  556. @click="toggleScheduleStatus(0)"
  557. >
  558. 取消排班
  559. </el-button>
  560. <el-button
  561. size="small"
  562. type="primary"
  563. icon="el-icon-plus"
  564. @click="openAdjustDialog(currentDay)"
  565. >
  566. 临时调整
  567. </el-button>
  568. <el-button
  569. size="small"
  570. icon="el-icon-warning-outline"
  571. @click="checkSingleDay(currentDay)"
  572. >
  573. 实时检测
  574. </el-button>
  575. </div> -->
  576. </el-drawer>
  577. <ele-modal
  578. :visible.sync="approveDialogVisible"
  579. :title="approveForm.status === 1 ? '审批通过' : '审批驳回'"
  580. width="520px"
  581. custom-class="ele-dialog-form"
  582. :close-on-click-modal="false"
  583. >
  584. <el-form :model="approveForm" label-width="90px" class="el-form-box">
  585. <el-form-item label="审批意见">
  586. <el-input
  587. v-model="approveForm.opinion"
  588. type="textarea"
  589. :rows="4"
  590. maxlength="300"
  591. show-word-limit
  592. :placeholder="
  593. approveForm.status === 1 ? '请输入审批意见' : '请输入驳回原因'
  594. "
  595. />
  596. </el-form-item>
  597. </el-form>
  598. <div slot="footer">
  599. <el-button type="primary" @click="confirmApproveAdjust">确定</el-button>
  600. <el-button @click="approveDialogVisible = false">取消</el-button>
  601. </div>
  602. </ele-modal>
  603. <ele-modal
  604. :visible.sync="adjustDetailVisible"
  605. title="调整记录追溯"
  606. width="860px"
  607. custom-class="ele-dialog-form adjust-detail-dialog"
  608. >
  609. <div v-if="adjustDetail.id" class="adjust-detail-view">
  610. <div class="adjust-detail-grid">
  611. <div class="adjust-detail-field">
  612. <span>申请单号</span>
  613. <strong>{{ adjustDetail.applyNo || '-' }}</strong>
  614. </div>
  615. <div class="adjust-detail-field">
  616. <span>申请人</span>
  617. <strong>{{ getAdjustApplicantName(adjustDetail) }}</strong>
  618. </div>
  619. <div class="adjust-detail-field">
  620. <span>关联日历</span>
  621. <strong>{{ adjustDetail.calendarName || '-' }}</strong>
  622. </div>
  623. <div class="adjust-detail-field">
  624. <span>调整类型</span>
  625. <strong>{{
  626. getLabel(adjustTypeOptions, adjustDetail.adjustType)
  627. }}</strong>
  628. </div>
  629. <div class="adjust-detail-field">
  630. <span>审批状态</span>
  631. <el-tag
  632. size="mini"
  633. :type="approvalStatusTag(adjustDetail.applyStatus)"
  634. >
  635. {{ getLabel(approvalStatusOptions, adjustDetail.applyStatus) }}
  636. </el-tag>
  637. </div>
  638. <div class="adjust-detail-field">
  639. <span>调整日期</span>
  640. <strong>{{ adjustDetail.adjustDate || '-' }}</strong>
  641. </div>
  642. <div class="adjust-detail-field is-wide">
  643. <span>生效周期</span>
  644. <strong class="adjust-period-value">
  645. {{ adjustDetail.effectiveTime || '-' }} 至
  646. {{ adjustDetail.expireTime || '-' }}
  647. </strong>
  648. </div>
  649. </div>
  650. <div class="adjust-compare">
  651. <div class="adjust-data-card before">
  652. <span>调整前数据</span>
  653. <strong>{{ adjustDetail.oldContent || '-' }}</strong>
  654. </div>
  655. <div class="adjust-data-card after">
  656. <span>调整后数据</span>
  657. <strong>{{
  658. formatSegmentContent(adjustDetail.newContent, adjustDetail) || '-'
  659. }}</strong>
  660. </div>
  661. </div>
  662. <div class="adjust-detail-section">
  663. <div class="section-title">调整原因</div>
  664. <p>{{ adjustDetail.applyReason || '-' }}</p>
  665. </div>
  666. <div class="adjust-detail-section">
  667. <div class="section-title">审批节点</div>
  668. <div
  669. v-if="formatApproveNodes(adjustDetail.approveNode).length"
  670. class="approve-timeline"
  671. >
  672. <div
  673. v-for="(node, index) in formatApproveNodes(
  674. adjustDetail.approveNode
  675. )"
  676. :key="index"
  677. class="approve-node"
  678. >
  679. <div class="node-dot"></div>
  680. <div class="node-content">
  681. <div>
  682. <strong>{{ node.statusText }}</strong>
  683. <span>{{ node.approveTime || '-' }}</span>
  684. </div>
  685. <p>{{ node.approveOpinion || '-' }}</p>
  686. <em v-if="node.approveUserId"
  687. >审批人ID:{{ node.approveUserId }}</em
  688. >
  689. </div>
  690. </div>
  691. </div>
  692. <div v-else class="approve-empty">暂无审批记录</div>
  693. </div>
  694. </div>
  695. <div slot="footer">
  696. <!-- <el-button icon="el-icon-download" @click="exportAdjustRecord">
  697. 导出追溯
  698. </el-button> -->
  699. <el-button @click="adjustDetailVisible = false">关闭</el-button>
  700. </div>
  701. </ele-modal>
  702. </div>
  703. </template>
  704. <script>
  705. import dayjs from 'dayjs';
  706. import BaseManage from './components/BaseManage.vue';
  707. import MultiCalendarView from './components/MultiCalendarView.vue';
  708. import ConflictPanel from './components/ConflictPanel.vue';
  709. import AdjustApproval from './components/AdjustApproval.vue';
  710. import StatisticsView from './components/StatisticsView.vue';
  711. import {
  712. addCalendar,
  713. editCalendar,
  714. deleteCalendar,
  715. updateCalendarStatus,
  716. pageCalendar,
  717. copyCalendar,
  718. viewCalendar,
  719. saveCalendarDetail,
  720. checkCalendarConflict,
  721. checkAllCalendarConflict,
  722. applyCalendarAdjust,
  723. approveCalendarAdjust,
  724. pageCalendarAdjust,
  725. refreshCalendarPlan,
  726. getPublicLegalHolidays
  727. } from '@/api/productionScheduling/factoryCalendar';
  728. const currentYear = Number(dayjs().format('YYYY'));
  729. const solarToLunar = () => ({
  730. solarFestival: '',
  731. lunarFestival: '',
  732. term: ''
  733. });
  734. const calendarTypeOptions = [
  735. { label: '标准生产日历', value: 1 },
  736. { label: '设备维护日历', value: 2 },
  737. { label: '人员排班日历', value: 3 }
  738. ];
  739. const dateTypeOptions = [
  740. { label: '正常工作日', value: 1 },
  741. { label: '休息日', value: 2 },
  742. { label: '节假日', value: 3 },
  743. { label: '设备检修期', value: 4 },
  744. { label: '临时调整时段', value: 5 }
  745. ];
  746. const adjustTypeOptions = [
  747. { label: '临时加班', value: 1 },
  748. { label: '临时停工', value: 2 },
  749. { label: '临时设备检修', value: 3 },
  750. { label: '临时人员调班', value: 4 }
  751. ];
  752. const approvalStatusOptions = [
  753. { label: '待审批', value: 0 },
  754. { label: '审批通过', value: 1 },
  755. { label: '审批驳回', value: 2 },
  756. { label: '已失效', value: 3 }
  757. ];
  758. const legalHolidayKeywords = [
  759. { keyword: '元旦节', label: '元旦节' },
  760. { keyword: '春节', label: '春节' },
  761. { keyword: '清明', label: '清明节' },
  762. { keyword: '劳动节', label: '劳动节' },
  763. { keyword: '端午节', label: '端午节' },
  764. { keyword: '中秋节', label: '中秋节' },
  765. { keyword: '国庆节', label: '国庆节' }
  766. ];
  767. const officialHolidayRanges = {
  768. 2026: [
  769. { name: '元旦节', start: '2026-01-01', end: '2026-01-03' },
  770. { name: '春节', start: '2026-02-15', end: '2026-02-23' },
  771. { name: '清明节', start: '2026-04-04', end: '2026-04-06' },
  772. { name: '劳动节', start: '2026-05-01', end: '2026-05-05' },
  773. { name: '端午节', start: '2026-06-19', end: '2026-06-21' },
  774. { name: '中秋节', start: '2026-09-25', end: '2026-09-27' },
  775. { name: '国庆节', start: '2026-10-01', end: '2026-10-07' }
  776. ]
  777. };
  778. const inferredHolidayRules = {
  779. 元旦节: { before: 0, after: 2 },
  780. 春节: { before: 2, after: 6 },
  781. 清明节: { before: 1, after: 1 },
  782. 劳动节: { before: 0, after: 4 },
  783. 端午节: { before: 0, after: 2 },
  784. 中秋节: { before: 0, after: 2 },
  785. 国庆节: { before: 0, after: 6 }
  786. };
  787. const inferredHolidayRangeCache = {};
  788. function clone(data) {
  789. return JSON.parse(JSON.stringify(data));
  790. }
  791. function createCode(prefix) {
  792. return `${prefix}${dayjs().format('YYYYMMDD')}${String(
  793. Math.floor(Math.random() * 1000000)
  794. ).padStart(6, '0')}`;
  795. }
  796. function toMinute(time) {
  797. const [hour, minute] = time.split(':').map(Number);
  798. return hour * 60 + minute;
  799. }
  800. function isOverlap(aStart, aEnd, bStart, bEnd) {
  801. return (
  802. toMinute(aStart) < toMinute(bEnd) && toMinute(bStart) < toMinute(aEnd)
  803. );
  804. }
  805. function createHolidayRule(dateType = 3, calendarDate = '', remark = '') {
  806. return {
  807. id: Date.now() + Math.random(),
  808. calendarDate,
  809. dateType,
  810. remark
  811. };
  812. }
  813. function normalizePage(data) {
  814. const list =
  815. data?.records || data?.list || data?.rows || data?.data || data || [];
  816. const count =
  817. data?.total || data?.count || data?.totalCount || list.length || 0;
  818. return {
  819. list: Array.isArray(list) ? list : [],
  820. count
  821. };
  822. }
  823. function normalizeYearList(applyYear) {
  824. if (Array.isArray(applyYear)) {
  825. return applyYear.map(Number).filter(Boolean);
  826. }
  827. return String(applyYear || '')
  828. .split(',')
  829. .map((item) => Number(item.trim()))
  830. .filter(Boolean);
  831. }
  832. export default {
  833. name: 'FactoryCalendar',
  834. components: {
  835. BaseManage,
  836. MultiCalendarView,
  837. ConflictPanel,
  838. AdjustApproval,
  839. StatisticsView
  840. },
  841. data() {
  842. return {
  843. activeTab: 'view',
  844. query: {
  845. year: currentYear,
  846. month: '',
  847. calendarType: '',
  848. status: ''
  849. },
  850. viewQuery: {
  851. calendarType: 1,
  852. year: currentYear,
  853. month: Number(dayjs().format('M')),
  854. date: dayjs().format('YYYY-MM-DD'),
  855. viewType: 'month',
  856. statusFilter: ''
  857. },
  858. viewMonth: dayjs().format('YYYY-MM'),
  859. calendars: [],
  860. details: [],
  861. adjusts: [],
  862. plans: [],
  863. conflictList: [],
  864. filteredCalendars: [],
  865. legalHolidayLoading: false,
  866. legalHolidayCache: {},
  867. legalHolidayStatusMap: {},
  868. legalHolidayPromises: {},
  869. conflictCheckPromise: null,
  870. conflictDataKey: '',
  871. viewDataKey: '',
  872. viewDataPromise: null,
  873. planDataKey: '',
  874. planDataPromise: null,
  875. pageSize: this.$store.state.tablePageSize,
  876. tableResponse: {
  877. dataName: 'list',
  878. countName: 'count'
  879. },
  880. calendarDialogVisible: false,
  881. copyDialogVisible: false,
  882. adjustDialogVisible: false,
  883. dayDrawerVisible: false,
  884. approveDialogVisible: false,
  885. adjustDetailVisible: false,
  886. calendarForm: this.getDefaultCalendarForm(),
  887. copyForm: {
  888. sourceId: '',
  889. targetYear: currentYear + 1
  890. },
  891. adjustForm: this.getDefaultAdjustForm(),
  892. approveForm: {
  893. row: null,
  894. status: 1,
  895. opinion: ''
  896. },
  897. adjustDetail: {},
  898. currentDay: {},
  899. calendarTypeOptions,
  900. dateTypeOptions,
  901. adjustTypeOptions,
  902. approvalStatusOptions,
  903. yearOptions: [
  904. currentYear - 1,
  905. currentYear,
  906. currentYear + 1,
  907. currentYear + 2
  908. ],
  909. monthOptions: Array.from({ length: 12 }, (_, index) => ({
  910. label: `${index + 1}月`,
  911. value: index + 1
  912. })),
  913. weekNames: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
  914. restModeOptions: [
  915. { label: '双休', value: 'double' },
  916. { label: '单休', value: 'single' },
  917. { label: '大小周', value: 'alternate' },
  918. { label: '无休', value: 'none' },
  919. { label: '自定义', value: 'custom' }
  920. ],
  921. restWeekdayOptions: [
  922. { label: '周一', value: 1 },
  923. { label: '周二', value: 2 },
  924. { label: '周三', value: 3 },
  925. { label: '周四', value: 4 },
  926. { label: '周五', value: 5 },
  927. { label: '周六', value: 6 },
  928. { label: '周日', value: 0 }
  929. ],
  930. timePickerOptions: {
  931. start: '00:00',
  932. step: '00:30',
  933. end: '23:30'
  934. },
  935. statusFilterOptions: [
  936. { label: '已排班/已排产', value: 'scheduled' },
  937. { label: '未排班/空闲', value: 'idle' },
  938. { label: '休息日/节假日', value: 'rest' },
  939. { label: '设备检修期', value: 'maintenance' },
  940. { label: '临时调整时段', value: 'temp' },
  941. { label: '时间冲突时段', value: 'conflict' }
  942. ],
  943. legendList: [
  944. {
  945. key: 'scheduled',
  946. label: '已排班/已排产',
  947. desc: '已完成生产、维保或人员排班'
  948. },
  949. {
  950. key: 'idle',
  951. label: '未排班/空闲',
  952. desc: '有效工作时间,暂无计划'
  953. },
  954. {
  955. key: 'rest',
  956. label: '休息日/节假日',
  957. desc: '不支持排产排班'
  958. },
  959. {
  960. key: 'holiday',
  961. label: '法定节假日',
  962. desc: '未配置为上班时默认休息'
  963. },
  964. {
  965. key: 'maintenance',
  966. label: '设备检修期',
  967. desc: '设备不可用时段'
  968. },
  969. {
  970. key: 'temp',
  971. label: '临时调整时段',
  972. desc: '审批通过后的加班、停工、调班'
  973. },
  974. {
  975. key: 'conflict',
  976. label: '时间冲突时段',
  977. desc: '存在多维度时间冲突'
  978. }
  979. ],
  980. calendarColumns: [
  981. {
  982. width: 60,
  983. label: '序号',
  984. type: 'index',
  985. columnKey: 'index',
  986. align: 'center'
  987. },
  988. {
  989. minWidth: 170,
  990. prop: 'calendarCode',
  991. label: '日历编码',
  992. align: 'center',
  993. showOverflowTooltip: true
  994. },
  995. {
  996. minWidth: 180,
  997. prop: 'calendarName',
  998. label: '日历名称',
  999. align: 'center',
  1000. showOverflowTooltip: true
  1001. },
  1002. {
  1003. minWidth: 140,
  1004. prop: 'calendarType',
  1005. label: '日历类型',
  1006. align: 'center',
  1007. slot: 'calendarType'
  1008. },
  1009. {
  1010. minWidth: 130,
  1011. prop: 'applyYear',
  1012. label: '适用年份',
  1013. align: 'center',
  1014. formatter: (row) => row.applyYear.join(',')
  1015. },
  1016. // {
  1017. // minWidth: 240,
  1018. // prop: 'timeRanges',
  1019. // label: '每日时段配置',
  1020. // align: 'center',
  1021. // slot: 'timeRanges'
  1022. // },
  1023. // {
  1024. // minWidth: 150,
  1025. // prop: 'productionLineName',
  1026. // label: '产线名称',
  1027. // align: 'center',
  1028. // showOverflowTooltip: true
  1029. // },
  1030. // {
  1031. // minWidth: 140,
  1032. // prop: 'workStationName',
  1033. // label: '工位名称',
  1034. // align: 'center',
  1035. // showOverflowTooltip: true
  1036. // },
  1037. {
  1038. minWidth: 150,
  1039. prop: 'status',
  1040. label: '状态',
  1041. align: 'center',
  1042. slot: 'status'
  1043. },
  1044. {
  1045. minWidth: 130,
  1046. prop: 'createUserName',
  1047. label: '创建人',
  1048. align: 'center'
  1049. },
  1050. {
  1051. minWidth: 170,
  1052. prop: 'updateTime',
  1053. label: '创建时间',
  1054. align: 'center'
  1055. },
  1056. {
  1057. columnKey: 'action',
  1058. label: '操作',
  1059. width: 230,
  1060. align: 'center',
  1061. slot: 'action',
  1062. fixed: 'right'
  1063. }
  1064. ],
  1065. conflictColumns: [
  1066. { width: 60, label: '序号', type: 'index', align: 'center' },
  1067. {
  1068. minWidth: 130,
  1069. prop: 'calendarDate',
  1070. label: '冲突日期',
  1071. align: 'center'
  1072. },
  1073. {
  1074. minWidth: 150,
  1075. prop: 'timeRange',
  1076. label: '冲突时段',
  1077. align: 'center'
  1078. },
  1079. { minWidth: 180, prop: 'scene', label: '冲突场景', align: 'center' },
  1080. {
  1081. minWidth: 120,
  1082. prop: 'level',
  1083. label: '等级',
  1084. align: 'center',
  1085. slot: 'level'
  1086. },
  1087. {
  1088. minWidth: 300,
  1089. prop: 'message',
  1090. label: '提示信息',
  1091. align: 'center',
  1092. showOverflowTooltip: true
  1093. },
  1094. {
  1095. columnKey: 'action',
  1096. label: '操作',
  1097. width: 120,
  1098. align: 'center',
  1099. slot: 'action',
  1100. fixed: 'right'
  1101. }
  1102. ],
  1103. adjustColumns: [
  1104. { width: 60, label: '序号', type: 'index', align: 'center' },
  1105. {
  1106. minWidth: 160,
  1107. prop: 'applyNo',
  1108. label: '申请单号',
  1109. align: 'center'
  1110. },
  1111. {
  1112. minWidth: 180,
  1113. prop: 'calendarName',
  1114. label: '关联日历',
  1115. align: 'center',
  1116. showOverflowTooltip: true
  1117. },
  1118. {
  1119. minWidth: 130,
  1120. prop: 'adjustType',
  1121. label: '调整类型',
  1122. align: 'center',
  1123. slot: 'adjustType'
  1124. },
  1125. {
  1126. minWidth: 120,
  1127. prop: 'adjustDate',
  1128. label: '调整日期',
  1129. align: 'center'
  1130. },
  1131. {
  1132. minWidth: 220,
  1133. prop: 'newContent',
  1134. label: '调整后数据',
  1135. align: 'center',
  1136. slot: 'newContent',
  1137. showOverflowTooltip: true
  1138. },
  1139. {
  1140. minWidth: 130,
  1141. prop: 'applyStatus',
  1142. label: '审批状态',
  1143. align: 'center',
  1144. slot: 'applyStatus'
  1145. },
  1146. {
  1147. minWidth: 130,
  1148. prop: 'applyUserName',
  1149. label: '申请人',
  1150. align: 'center'
  1151. },
  1152. {
  1153. minWidth: 170,
  1154. prop: 'applyTime',
  1155. label: '申请时间',
  1156. align: 'center'
  1157. },
  1158. {
  1159. columnKey: 'action',
  1160. label: '操作',
  1161. width: 120,
  1162. align: 'center',
  1163. slot: 'action',
  1164. fixed: 'right'
  1165. }
  1166. ],
  1167. planColumns: [
  1168. { width: 60, label: '序号', type: 'index', align: 'center' },
  1169. { minWidth: 150, prop: 'planNo', label: '计划编号', align: 'center' },
  1170. {
  1171. minWidth: 150,
  1172. prop: 'orderNo',
  1173. label: '订单编号',
  1174. align: 'center'
  1175. },
  1176. {
  1177. minWidth: 180,
  1178. prop: 'taskName',
  1179. label: '任务名称',
  1180. align: 'center',
  1181. showOverflowTooltip: true
  1182. },
  1183. {
  1184. minWidth: 130,
  1185. prop: 'calendarDate',
  1186. label: '计划日期',
  1187. align: 'center'
  1188. },
  1189. {
  1190. minWidth: 150,
  1191. prop: 'timeRange',
  1192. label: '计划时段',
  1193. align: 'center',
  1194. formatter: (row) =>
  1195. row.timeRange || `${row.startTime}-${row.endTime}`
  1196. },
  1197. {
  1198. minWidth: 150,
  1199. prop: 'productionLineName',
  1200. label: '产线名称',
  1201. align: 'center',
  1202. showOverflowTooltip: true
  1203. },
  1204. {
  1205. minWidth: 140,
  1206. prop: 'workStationName',
  1207. label: '工位名称',
  1208. align: 'center',
  1209. showOverflowTooltip: true
  1210. },
  1211. {
  1212. minWidth: 120,
  1213. prop: 'workingHours',
  1214. label: '工时(分钟)',
  1215. align: 'center'
  1216. },
  1217. {
  1218. minWidth: 120,
  1219. prop: 'restTime',
  1220. label: '休息(分钟)',
  1221. align: 'center'
  1222. },
  1223. {
  1224. minWidth: 110,
  1225. prop: 'status',
  1226. label: '状态',
  1227. align: 'center',
  1228. slot: 'status'
  1229. },
  1230. {
  1231. columnKey: 'action',
  1232. label: '操作',
  1233. width: 120,
  1234. align: 'center',
  1235. slot: 'action',
  1236. fixed: 'right'
  1237. }
  1238. ],
  1239. calendarRules: {
  1240. calendarName: [
  1241. { required: true, message: '请输入日历名称', trigger: 'blur' }
  1242. ],
  1243. calendarType: [
  1244. { required: true, message: '请选择日历类型', trigger: 'change' }
  1245. ],
  1246. applyYear: [
  1247. { required: true, message: '请选择适用年份', trigger: 'change' }
  1248. ],
  1249. applyMonth: [
  1250. { required: true, message: '请选择适用月份', trigger: 'change' }
  1251. ]
  1252. },
  1253. adjustRules: {
  1254. calendarId: [
  1255. { required: true, message: '请选择关联日历', trigger: 'change' }
  1256. ],
  1257. adjustType: [
  1258. { required: true, message: '请选择调整类型', trigger: 'change' }
  1259. ],
  1260. adjustDate: [
  1261. { required: true, message: '请选择调整日期', trigger: 'change' }
  1262. ],
  1263. effectiveTime: [
  1264. { required: true, message: '请选择生效时间', trigger: 'change' }
  1265. ],
  1266. expireTime: [
  1267. { required: true, message: '请选择失效时间', trigger: 'change' }
  1268. ],
  1269. applyReason: [
  1270. { required: true, message: '请输入调整原因', trigger: 'blur' }
  1271. ]
  1272. }
  1273. };
  1274. },
  1275. computed: {
  1276. vm() {
  1277. return this;
  1278. },
  1279. enabledCalendars() {
  1280. return this.calendars.filter((item) => item.status === 1);
  1281. },
  1282. calendarDialogTitle() {
  1283. return this.calendarForm.id ? '编辑日历' : '新增日历';
  1284. },
  1285. calendarFormApplyYear: {
  1286. get() {
  1287. return normalizeYearList(this.calendarForm.applyYear)[0] || '';
  1288. },
  1289. set(value) {
  1290. this.calendarForm.applyYear = value ? [Number(value)] : [];
  1291. this.calendarForm.legalHolidayWorkDates = [];
  1292. this.loadLegalHolidaysByYears(this.calendarForm.applyYear);
  1293. }
  1294. },
  1295. showWeekHeader() {
  1296. return ['week', 'month'].includes(this.viewQuery.viewType);
  1297. },
  1298. calendarViewTitle() {
  1299. const date = dayjs(this.viewQuery.date);
  1300. if (this.viewQuery.viewType === 'day') {
  1301. return `${date.format('YYYY年MM月DD日')} 日视图`;
  1302. }
  1303. if (this.viewQuery.viewType === 'week') {
  1304. const start = date.startOf('week').add(1, 'day');
  1305. const end = start.add(6, 'day');
  1306. return `${start.format('YYYY年MM月DD日')} - ${end.format(
  1307. 'MM月DD日'
  1308. )} 周视图`;
  1309. }
  1310. if (this.viewQuery.viewType === 'quarter') {
  1311. const startMonth = Math.floor((this.viewQuery.month - 1) / 3) * 3 + 1;
  1312. const endMonth = startMonth + 2;
  1313. return `${this.viewQuery.year}年${startMonth}月 - ${endMonth}月 季视图`;
  1314. }
  1315. return `${this.viewQuery.year}年${this.viewQuery.month}月 月视图`;
  1316. },
  1317. calendarDateRange() {
  1318. const current = dayjs(this.viewQuery.date);
  1319. if (this.viewQuery.viewType === 'day') {
  1320. return [current];
  1321. }
  1322. if (this.viewQuery.viewType === 'week') {
  1323. const start = current.startOf('week').add(1, 'day');
  1324. return Array.from({ length: 7 }).map((_, index) =>
  1325. start.add(index, 'day')
  1326. );
  1327. }
  1328. if (this.viewQuery.viewType === 'quarter') {
  1329. const startMonth = Math.floor((this.viewQuery.month - 1) / 3) * 3 + 1;
  1330. const start = dayjs(
  1331. `${this.viewQuery.year}-${String(startMonth).padStart(2, '0')}-01`
  1332. );
  1333. const dates = [];
  1334. for (let i = 0; i < 3; i += 1) {
  1335. const month = start.add(i, 'month');
  1336. for (let day = 1; day <= month.daysInMonth(); day += 1) {
  1337. dates.push(month.date(day));
  1338. }
  1339. }
  1340. return dates;
  1341. }
  1342. const firstDay = dayjs(
  1343. `${this.viewQuery.year}-${String(this.viewQuery.month).padStart(
  1344. 2,
  1345. '0'
  1346. )}-01`
  1347. );
  1348. const dates = [];
  1349. for (let day = 1; day <= firstDay.daysInMonth(); day += 1) {
  1350. dates.push(firstDay.date(day));
  1351. }
  1352. return dates;
  1353. },
  1354. calendarCells() {
  1355. return this.buildCalendarCells(true);
  1356. },
  1357. statCells() {
  1358. const dates = this.getMonthDateRange();
  1359. return this.buildCalendarCellsByDates(dates, false, 'month').filter(
  1360. (item) => item.date
  1361. );
  1362. },
  1363. monthStats() {
  1364. const details = this.getStatMonthDetails();
  1365. const countDistinctDates = (predicate) =>
  1366. new Set(
  1367. details
  1368. .filter(predicate)
  1369. .map((item) => item.calendarDate)
  1370. .filter(Boolean)
  1371. ).size;
  1372. const workDays = countDistinctDates(
  1373. (item) => Number(item.dateType) === 1
  1374. );
  1375. const scheduledDateSet = new Set(
  1376. details
  1377. .filter((item) => this.isDetailScheduled(item))
  1378. .map((item) => item.calendarDate)
  1379. .filter(Boolean)
  1380. );
  1381. const scheduledDays = scheduledDateSet.size;
  1382. const scheduledWorkdaySet = new Set(
  1383. details
  1384. .filter(
  1385. (item) =>
  1386. Number(item.dateType) === 1 &&
  1387. scheduledDateSet.has(item.calendarDate)
  1388. )
  1389. .map((item) => item.calendarDate)
  1390. );
  1391. const emptyWorkdaySet = new Set(
  1392. details
  1393. .filter(
  1394. (item) =>
  1395. Number(item.dateType) === 1 &&
  1396. !scheduledDateSet.has(item.calendarDate)
  1397. )
  1398. .map((item) => item.calendarDate)
  1399. );
  1400. const idleDays = Math.max(
  1401. emptyWorkdaySet.size,
  1402. workDays - scheduledWorkdaySet.size,
  1403. 0
  1404. );
  1405. const conflictDays = countDistinctDates(
  1406. (item) => Number(item.isConflict) === 1
  1407. );
  1408. const tempDays = countDistinctDates(
  1409. (item) => Number(item.isTempAdjust) === 1
  1410. );
  1411. const restDays = countDistinctDates((item) =>
  1412. [2, 3].includes(Number(item.dateType))
  1413. );
  1414. return [
  1415. { key: 'work', label: '总工作日', value: workDays },
  1416. { key: 'scheduled', label: '已排班天数', value: scheduledDays },
  1417. {
  1418. key: 'idle',
  1419. label: '未排班天数',
  1420. value: idleDays
  1421. },
  1422. { key: 'conflict', label: '冲突天数', value: conflictDays },
  1423. { key: 'temp', label: '临时调整天数', value: tempDays },
  1424. { key: 'rest', label: '休息/节假日', value: restDays }
  1425. ];
  1426. },
  1427. scheduledWorkdayDays() {
  1428. return new Set(
  1429. this.getStatMonthDetails()
  1430. .filter(
  1431. (item) =>
  1432. Number(item.dateType) === 1 && this.isDetailScheduled(item)
  1433. )
  1434. .map((item) => item.calendarDate)
  1435. .filter(Boolean)
  1436. ).size;
  1437. },
  1438. dayDrawerTitle() {
  1439. return this.currentDay.date
  1440. ? `${this.currentDay.date} 日历详情`
  1441. : '日历详情';
  1442. },
  1443. drawerDateMonth() {
  1444. return this.currentDay.date
  1445. ? dayjs(this.currentDay.date).format('YYYY-MM')
  1446. : '';
  1447. },
  1448. drawerDateDay() {
  1449. return this.currentDay.date
  1450. ? dayjs(this.currentDay.date).format('DD')
  1451. : '';
  1452. },
  1453. relatedPlans() {
  1454. return this.currentDay.relatedPlans || [];
  1455. },
  1456. relatedSectionTitle() {
  1457. return this.isTeamQueueDrawer ? '排班详情' : '关联计划';
  1458. },
  1459. isEquipmentDrawer() {
  1460. return (
  1461. Number(this.viewQuery.calendarType) === 2 ||
  1462. (this.currentDay.details || []).some(
  1463. (item) => Number(item.calendarType) === 2
  1464. )
  1465. );
  1466. },
  1467. isTeamQueueDrawer() {
  1468. return (
  1469. Number(this.viewQuery.calendarType) === 3 ||
  1470. (this.currentDay.details || []).some(
  1471. (item) => Number(item.calendarType) === 3
  1472. )
  1473. );
  1474. },
  1475. legalHolidayOptions() {
  1476. return this.getLegalHolidayOptions(
  1477. this.calendarForm.applyYear,
  1478. this.calendarForm.applyMonth
  1479. );
  1480. },
  1481. legalHolidayGroups() {
  1482. const groupMap = {};
  1483. this.legalHolidayOptions.forEach((item) => {
  1484. if (!groupMap[item.name]) {
  1485. groupMap[item.name] = {
  1486. name: item.name,
  1487. dates: []
  1488. };
  1489. }
  1490. groupMap[item.name].dates.push(item);
  1491. });
  1492. return Object.values(groupMap);
  1493. },
  1494. showLegalHolidaySection() {
  1495. return this.legalHolidayLoading || this.legalHolidayGroups.length > 0;
  1496. },
  1497. legalHolidayVisibleWorkCount() {
  1498. const visibleDates = new Set(
  1499. this.legalHolidayOptions.map((item) => item.calendarDate)
  1500. );
  1501. return (this.calendarForm.legalHolidayWorkDates || []).filter((date) =>
  1502. visibleDates.has(date)
  1503. ).length;
  1504. },
  1505. legalHolidaySourceText() {
  1506. const year = normalizeYearList(this.calendarForm.applyYear)[0];
  1507. if (this.legalHolidayStatusMap[year] === 'remote') {
  1508. return '已同步公共节假日';
  1509. }
  1510. if (this.legalHolidayStatusMap[year] === 'fallback') {
  1511. return '使用本地节假日';
  1512. }
  1513. return '使用本地节假日';
  1514. },
  1515. visualKpis() {
  1516. const workDays =
  1517. this.monthStats.find((item) => item.key === 'work')?.value || 0;
  1518. const scheduledDays =
  1519. this.monthStats.find((item) => item.key === 'scheduled')?.value || 0;
  1520. const tempDays =
  1521. this.monthStats.find((item) => item.key === 'temp')?.value || 0;
  1522. const conflictDays =
  1523. this.monthStats.find((item) => item.key === 'conflict')?.value || 0;
  1524. return [
  1525. {
  1526. key: 'work',
  1527. label: '总工作日',
  1528. value: workDays,
  1529. desc: `${this.viewQuery.year}年${this.viewQuery.month}月`,
  1530. icon: 'el-icon-date'
  1531. },
  1532. {
  1533. key: 'scheduled',
  1534. label: '已排班',
  1535. value: scheduledDays,
  1536. desc: `完成率 ${this.scheduleRate}%`,
  1537. icon: 'el-icon-finished'
  1538. },
  1539. {
  1540. key: 'conflict',
  1541. label: '冲突天数',
  1542. value: conflictDays,
  1543. desc: '当前月需确认修正',
  1544. icon: 'el-icon-warning-outline'
  1545. },
  1546. {
  1547. key: 'temp',
  1548. label: '临时调整',
  1549. value: tempDays,
  1550. desc: '审批通过后生效',
  1551. icon: 'el-icon-refresh'
  1552. }
  1553. ];
  1554. },
  1555. scheduleRate() {
  1556. const workDays =
  1557. this.monthStats.find((item) => item.key === 'work')?.value || 0;
  1558. return workDays
  1559. ? Math.min(
  1560. 100,
  1561. Math.round((this.scheduledWorkdayDays / workDays) * 100)
  1562. )
  1563. : 0;
  1564. },
  1565. scheduleSegments() {
  1566. const scheduled =
  1567. this.monthStats.find((item) => item.key === 'scheduled')?.value || 0;
  1568. const idle =
  1569. this.monthStats.find((item) => item.key === 'idle')?.value || 0;
  1570. const rest =
  1571. this.monthStats.find((item) => item.key === 'rest')?.value || 0;
  1572. return [
  1573. {
  1574. key: 'scheduled',
  1575. label: '已排班',
  1576. value: scheduled,
  1577. color: '#409eff'
  1578. },
  1579. { key: 'idle', label: '未排班', value: idle, color: '#67c23a' },
  1580. { key: 'rest', label: '休息/节假日', value: rest, color: '#c0c4cc' }
  1581. ];
  1582. },
  1583. scheduleDonutBackground() {
  1584. const total = this.scheduleSegments.reduce(
  1585. (sum, item) => sum + item.value,
  1586. 0
  1587. );
  1588. if (!total) {
  1589. return '#ebeef5';
  1590. }
  1591. let start = 0;
  1592. const segments = this.scheduleSegments.map((item) => {
  1593. const end = start + (item.value / total) * 100;
  1594. const value = `${item.color} ${start}% ${end}%`;
  1595. start = end;
  1596. return value;
  1597. });
  1598. return `conic-gradient(${segments.join(', ')})`;
  1599. },
  1600. scheduleTooltip() {
  1601. return `已排班率 ${this.scheduleRate}%,已排班 ${this.scheduleSegments[0].value} 天,未排班 ${this.scheduleSegments[1].value} 天,休息/节假日 ${this.scheduleSegments[2].value} 天`;
  1602. },
  1603. visualMonthBars() {
  1604. const colorMap = {
  1605. work: '#409eff',
  1606. scheduled: '#36cfc9',
  1607. idle: '#67c23a',
  1608. conflict: '#f56c6c',
  1609. temp: '#9254de',
  1610. rest: '#909399'
  1611. };
  1612. const max = Math.max(...this.monthStats.map((item) => item.value), 1);
  1613. return this.monthStats.map((item) => ({
  1614. ...item,
  1615. color: colorMap[item.key],
  1616. percent: Math.round((item.value / max) * 100)
  1617. }));
  1618. },
  1619. calendarTypeStats() {
  1620. const colorMap = {
  1621. 1: '#409eff',
  1622. 2: '#e6a23c',
  1623. 3: '#67c23a'
  1624. };
  1625. return this.calendarTypeOptions.map((item) => {
  1626. const list = this.calendars.filter(
  1627. (calendar) => calendar.calendarType === item.value
  1628. );
  1629. return {
  1630. ...item,
  1631. color: colorMap[item.value],
  1632. count: list.length,
  1633. enabled: list.filter((calendar) => calendar.status === 1).length,
  1634. disabled: list.filter((calendar) => calendar.status === 0).length
  1635. };
  1636. });
  1637. },
  1638. conflictTrend() {
  1639. const days = Array.from({ length: 6 }).map((_, index) => {
  1640. const date = dayjs(
  1641. `${this.viewQuery.year}-${String(this.viewQuery.month).padStart(
  1642. 2,
  1643. '0'
  1644. )}-01`
  1645. ).date(index * 5 + 1);
  1646. const count = new Set(
  1647. this.getStatMonthDetails()
  1648. .filter(
  1649. (item) =>
  1650. Number(item.isConflict) === 1 &&
  1651. dayjs(item.calendarDate).isSame(date, 'week')
  1652. )
  1653. .map((item) => item.calendarDate)
  1654. ).size;
  1655. return {
  1656. label: date.format('MM/DD'),
  1657. count
  1658. };
  1659. });
  1660. const max = Math.max(...days.map((item) => item.count), 1);
  1661. return days.map((item) => ({
  1662. ...item,
  1663. height: Math.max(12, Math.round((item.count / max) * 100))
  1664. }));
  1665. }
  1666. },
  1667. created() {
  1668. this.loadRemoteCalendarData();
  1669. },
  1670. methods: {
  1671. getDefaultCalendarForm() {
  1672. return {
  1673. id: '',
  1674. calendarCode: createCode('CLD'),
  1675. calendarName: '',
  1676. calendarType: 1,
  1677. applyYear: [currentYear],
  1678. applyMonth: Array.from({ length: 12 }, (_, index) => index + 1),
  1679. status: 0,
  1680. shiftId: '',
  1681. shiftName: '',
  1682. shiftCode: '',
  1683. timeRanges: [],
  1684. restMode: 'double',
  1685. restWeekdays: [6, 0],
  1686. legalHolidayWorkDates: [],
  1687. holidayRules: [],
  1688. remark: ''
  1689. };
  1690. },
  1691. getDefaultAdjustForm(day = {}) {
  1692. const enabledCalendars = (this.calendars || []).filter(
  1693. (item) => item.status === 1
  1694. );
  1695. return {
  1696. calendarId: enabledCalendars[0]?.id || '',
  1697. adjustType: 1,
  1698. adjustDate: day.date || dayjs().format('YYYY-MM-DD'),
  1699. startTime: '08:00',
  1700. endTime: '17:00',
  1701. effectiveTime: `${day.date || dayjs().format('YYYY-MM-DD')} 08:00:00`,
  1702. expireTime: `${day.date || dayjs().format('YYYY-MM-DD')} 17:00:00`,
  1703. applyReason: ''
  1704. };
  1705. },
  1706. buildCalendarCells(applyFilter = true) {
  1707. return this.buildCalendarCellsByDates(
  1708. this.calendarDateRange,
  1709. applyFilter,
  1710. this.viewQuery.viewType
  1711. );
  1712. },
  1713. getMonthDateRange(
  1714. year = this.viewQuery.year,
  1715. month = this.viewQuery.month
  1716. ) {
  1717. const firstDay = dayjs(`${year}-${String(month).padStart(2, '0')}-01`);
  1718. const dates = [];
  1719. for (let day = 1; day <= firstDay.daysInMonth(); day += 1) {
  1720. dates.push(firstDay.date(day));
  1721. }
  1722. return dates;
  1723. },
  1724. buildCalendarCellsByDates(
  1725. dates,
  1726. applyFilter = true,
  1727. viewType = this.viewQuery.viewType
  1728. ) {
  1729. const startOffset =
  1730. viewType === 'month' && dates.length ? (dates[0].day() + 6) % 7 : 0;
  1731. const cells = [];
  1732. for (let i = 0; i < startOffset; i += 1) {
  1733. cells.push({ key: `empty-${i}`, date: '', dayText: '', details: [] });
  1734. }
  1735. dates.forEach((dateItem) => {
  1736. const date = dateItem.format('YYYY-MM-DD');
  1737. const details = this.getViewDetails(date);
  1738. const planCount = this.getDetailPlanCount(details);
  1739. const disabled = !this.hasEnabledCalendarForView();
  1740. const holidayName = this.getLegalHolidayName(dateItem);
  1741. const hasWorkDetail = details.some(
  1742. (item) => Number(item.dateType || 1) === 1
  1743. );
  1744. const cell = {
  1745. key: date,
  1746. date,
  1747. dayText:
  1748. viewType === 'quarter'
  1749. ? dateItem.format('M/D')
  1750. : dateItem.format('D'),
  1751. details,
  1752. planCount: disabled ? 0 : planCount,
  1753. scheduleStatus:
  1754. !disabled &&
  1755. (details.some((item) => item.scheduleStatus === 1) ||
  1756. planCount > 0),
  1757. isConflict:
  1758. !disabled && details.some((item) => item.isConflict === 1),
  1759. isTempAdjust:
  1760. !disabled && details.some((item) => item.isTempAdjust === 1),
  1761. isMaintenance:
  1762. !disabled && details.some((item) => item.dateType === 4),
  1763. isHoliday:
  1764. !disabled &&
  1765. (details.some((item) => Number(item.dateType) === 3) ||
  1766. (holidayName && !hasWorkDetail)),
  1767. holidayName,
  1768. isRest: disabled ? true : this.isRestDay(date, details),
  1769. isDisabledCalendar: disabled,
  1770. conflictText: disabled ? '日历已禁用' : this.getConflictText(date)
  1771. };
  1772. if (!applyFilter || this.matchStatusFilter(cell)) {
  1773. cells.push(cell);
  1774. } else {
  1775. cells.push({ ...cell, hiddenByFilter: true });
  1776. }
  1777. });
  1778. return cells;
  1779. },
  1780. hasEnabledCalendarForView() {
  1781. return !!this.getCurrentViewCalendar();
  1782. },
  1783. getCurrentViewCalendar() {
  1784. return this.enabledCalendars.find(
  1785. (item) => item.calendarType === this.viewQuery.calendarType
  1786. );
  1787. },
  1788. getCurrentViewCalendars() {
  1789. return this.enabledCalendars.filter(
  1790. (item) => item.calendarType === this.viewQuery.calendarType
  1791. );
  1792. },
  1793. getRemoteCalendarId(calendar = this.getCurrentViewCalendar()) {
  1794. return calendar?.isRemote ? calendar.id : null;
  1795. },
  1796. getScheduleSegmentTooltip(item) {
  1797. const total = this.scheduleSegments.reduce(
  1798. (sum, segment) => sum + segment.value,
  1799. 0
  1800. );
  1801. const percent = total ? Math.round((item.value / total) * 100) : 0;
  1802. return `${item.label}:${item.value} 天,占比 ${percent}%`;
  1803. },
  1804. getMonthBarTooltip(item) {
  1805. return `${this.viewQuery.year}年${this.viewQuery.month}月,${item.label}:${item.value} 天,占当前最大值 ${item.percent}%`;
  1806. },
  1807. getCalendarTypeTooltip(item) {
  1808. return `${item.label}:共 ${item.count} 个,启用 ${item.enabled} 个,禁用 ${item.disabled} 个`;
  1809. },
  1810. getConflictTrendTooltip(item) {
  1811. return `${item.label} 所在周:${item.count} 条冲突`;
  1812. },
  1813. loadData() {
  1814. this.calendars = [];
  1815. this.details = [];
  1816. this.adjusts = [];
  1817. this.plans = [];
  1818. },
  1819. getCalendarQueryParams(query = this.query) {
  1820. return {
  1821. year: query.year || undefined,
  1822. calendarType: query.calendarType || undefined,
  1823. status: query.status === '' ? undefined : query.status
  1824. };
  1825. },
  1826. async loadRemoteCalendarData() {
  1827. try {
  1828. const data = await pageCalendar({
  1829. pageNum: 1,
  1830. size: 999,
  1831. ...this.getCalendarQueryParams()
  1832. });
  1833. const { list } = normalizePage(data);
  1834. this.calendars = list.map((item) =>
  1835. this.normalizeRemoteCalendar(item)
  1836. );
  1837. this.details = list
  1838. .map((item) =>
  1839. (item.detailList || []).map((detail) =>
  1840. this.normalizeRemoteDetail(detail, item)
  1841. )
  1842. )
  1843. .flat();
  1844. await this.loadRemoteViewData(true);
  1845. await this.loadRemoteAdjustData();
  1846. this.syncFilteredCalendars();
  1847. } catch (e) {
  1848. this.calendars = [];
  1849. this.details = [];
  1850. this.adjusts = [];
  1851. this.plans = [];
  1852. this.syncFilteredCalendars();
  1853. }
  1854. },
  1855. getViewDataKey(query = this.viewQuery) {
  1856. return [
  1857. query.calendarType || '',
  1858. query.year || '',
  1859. query.month || '',
  1860. query.viewType || ''
  1861. ].join('|');
  1862. },
  1863. async loadRemoteViewData(force = false, queryOverride = null) {
  1864. const query = {
  1865. ...this.viewQuery,
  1866. ...(queryOverride || {})
  1867. };
  1868. const dataKey = this.getViewDataKey(query);
  1869. if (!force && this.viewDataKey === dataKey) {
  1870. return;
  1871. }
  1872. if (!force && this.viewDataPromise) {
  1873. await this.viewDataPromise;
  1874. return;
  1875. }
  1876. try {
  1877. this.viewDataPromise = viewCalendar({
  1878. calendarType: query.calendarType,
  1879. year: query.year,
  1880. month: query.month,
  1881. viewType: query.viewType
  1882. });
  1883. const data = await this.viewDataPromise;
  1884. if (!Array.isArray(data)) {
  1885. this.viewDataKey = '';
  1886. this.viewDataPromise = null;
  1887. return;
  1888. }
  1889. const remoteDetails = data.map((item) => ({
  1890. ...this.normalizeRemoteDetail(item),
  1891. isViewDetail: true
  1892. }));
  1893. const visibleDates =
  1894. queryOverride && query.viewType === 'month'
  1895. ? this.getMonthDateRange(query.year, query.month).map((item) =>
  1896. item.format('YYYY-MM-DD')
  1897. )
  1898. : this.calendarDateRange.map((item) => item.format('YYYY-MM-DD'));
  1899. const viewCalendarIds = this.calendars
  1900. .filter((item) => item.calendarType === query.calendarType)
  1901. .map((item) => item.id);
  1902. this.details = [
  1903. ...this.details.filter(
  1904. (item) =>
  1905. !(
  1906. item.calendarType === query.calendarType ||
  1907. viewCalendarIds.includes(item.calendarId)
  1908. ) || !visibleDates.includes(item.calendarDate)
  1909. ),
  1910. ...remoteDetails
  1911. ];
  1912. this.viewDataKey = dataKey;
  1913. } catch (e) {
  1914. this.viewDataKey = '';
  1915. }
  1916. this.viewDataPromise = null;
  1917. },
  1918. async loadRemoteAdjustData() {
  1919. try {
  1920. const data = await pageCalendarAdjust({
  1921. pageNum: 1,
  1922. size: 999
  1923. });
  1924. const { list } = normalizePage(data);
  1925. this.adjusts = list;
  1926. } catch (e) {
  1927. this.adjusts = [];
  1928. }
  1929. },
  1930. normalizeRemoteCalendar(item) {
  1931. const detailList = Array.isArray(item.detailList)
  1932. ? item.detailList
  1933. : [];
  1934. const ruleConfig = this.parseCalendarRuleConfig(item.remark);
  1935. const workdayDetails = detailList.filter(
  1936. (detail) => Number(detail.dateType || 1) === 1
  1937. );
  1938. const applyMonth = normalizeYearList(item.applyMonth);
  1939. const inferredApplyMonth = this.getApplyMonthsFromDetails(detailList);
  1940. const inferredRestRule = this.getRestRuleFromDetails(detailList);
  1941. const restWeekdays = Array.isArray(item.restWeekdays)
  1942. ? item.restWeekdays.map(Number)
  1943. : ruleConfig.restWeekdays === undefined
  1944. ? inferredRestRule.restWeekdays
  1945. : ruleConfig.restWeekdays;
  1946. return {
  1947. ...item,
  1948. remark: this.stripCalendarRuleConfig(item.remark),
  1949. isRemote: true,
  1950. applyYear: normalizeYearList(item.applyYear),
  1951. applyMonth: applyMonth.length
  1952. ? applyMonth
  1953. : ruleConfig.applyMonth ||
  1954. inferredApplyMonth ||
  1955. this.getFullMonthList(),
  1956. shiftId: item.shiftId || ruleConfig.shiftId || '',
  1957. shiftName: item.shiftName || ruleConfig.shiftName || '',
  1958. shiftCode: item.shiftCode || ruleConfig.shiftCode || '',
  1959. timeRanges: workdayDetails.length
  1960. ? this.mergeTimeRanges(
  1961. [],
  1962. workdayDetails.map((detail, index) => ({
  1963. id: detail.id || `${item.id}-${index}`,
  1964. name:
  1965. detail.dateTypeName || detail.remark || `时段${index + 1}`,
  1966. startTime: String(detail.startTime || '').slice(0, 5),
  1967. endTime: String(detail.endTime || '').slice(0, 5),
  1968. timeType: '1'
  1969. }))
  1970. )
  1971. : item.timeRanges || [],
  1972. restWeekdays,
  1973. legalHolidayWorkDates: Array.isArray(item.legalHolidayWorkDates)
  1974. ? item.legalHolidayWorkDates
  1975. : ruleConfig.legalHolidayWorkDates || [],
  1976. restMode:
  1977. item.restMode ||
  1978. ruleConfig.restMode ||
  1979. inferredRestRule.restMode ||
  1980. this.getRestModeByWeekdays(restWeekdays),
  1981. holidayRules: Array.isArray(item.holidayRules)
  1982. ? item.holidayRules
  1983. : ruleConfig.holidayRules || []
  1984. };
  1985. },
  1986. getApplyMonthsFromDetails(detailList = []) {
  1987. const months = [
  1988. ...new Set(
  1989. detailList
  1990. .map((detail) => {
  1991. const month = dayjs(detail.calendarDate).month() + 1;
  1992. return Number.isNaN(month) ? null : month;
  1993. })
  1994. .filter(Boolean)
  1995. )
  1996. ].sort((a, b) => a - b);
  1997. return months.length ? months : null;
  1998. },
  1999. getRestRuleFromDetails(detailList = []) {
  2000. const dayMap = {};
  2001. detailList.forEach((detail) => {
  2002. if (!detail.calendarDate) {
  2003. return;
  2004. }
  2005. if (!dayMap[detail.calendarDate]) {
  2006. dayMap[detail.calendarDate] = [];
  2007. }
  2008. dayMap[detail.calendarDate].push(detail);
  2009. });
  2010. const days = Object.keys(dayMap).map((date) => {
  2011. const details = dayMap[date];
  2012. return {
  2013. date,
  2014. weekDay: dayjs(date).day(),
  2015. isRest: details.every((detail) =>
  2016. [2, 3].includes(Number(detail.dateType))
  2017. )
  2018. };
  2019. });
  2020. const restWeekdays = [
  2021. ...new Set(
  2022. days.filter((item) => item.isRest).map((item) => item.weekDay)
  2023. )
  2024. ].sort((a, b) => a - b);
  2025. const weekdayText = restWeekdays.join(',');
  2026. if (!restWeekdays.length) {
  2027. return { restMode: 'none', restWeekdays: [] };
  2028. }
  2029. if (weekdayText === '0') {
  2030. return { restMode: 'single', restWeekdays };
  2031. }
  2032. if (weekdayText === '0,6') {
  2033. const saturdayDays = days.filter((item) => item.weekDay === 6);
  2034. const saturdayRestCount = saturdayDays.filter(
  2035. (item) => item.isRest
  2036. ).length;
  2037. if (
  2038. saturdayDays.length &&
  2039. saturdayRestCount > 0 &&
  2040. saturdayRestCount < saturdayDays.length
  2041. ) {
  2042. return { restMode: 'alternate', restWeekdays };
  2043. }
  2044. return { restMode: 'double', restWeekdays };
  2045. }
  2046. return { restMode: 'custom', restWeekdays };
  2047. },
  2048. parseCalendarRuleConfig(remark) {
  2049. const match = String(remark || '').match(
  2050. /\[calendarRules\]([\s\S]*?)\[\/calendarRules\]/
  2051. );
  2052. if (!match) {
  2053. return {};
  2054. }
  2055. try {
  2056. const config = JSON.parse(match[1]);
  2057. return {
  2058. applyMonth: Array.isArray(config.applyMonth)
  2059. ? config.applyMonth.map(Number).filter(Boolean)
  2060. : undefined,
  2061. shiftId: config.shiftId || undefined,
  2062. shiftName: config.shiftName || undefined,
  2063. shiftCode: config.shiftCode || undefined,
  2064. restMode: config.restMode || undefined,
  2065. restWeekdays: Array.isArray(config.restWeekdays)
  2066. ? config.restWeekdays.map(Number)
  2067. : undefined,
  2068. legalHolidayWorkDates: Array.isArray(config.legalHolidayWorkDates)
  2069. ? config.legalHolidayWorkDates.filter(Boolean)
  2070. : undefined,
  2071. holidayRules: Array.isArray(config.holidayRules)
  2072. ? config.holidayRules
  2073. .filter((item) => item && item.calendarDate)
  2074. .map((item) =>
  2075. createHolidayRule(
  2076. Number(item.dateType || 3),
  2077. item.calendarDate,
  2078. item.remark || ''
  2079. )
  2080. )
  2081. : undefined
  2082. };
  2083. } catch (e) {
  2084. return {};
  2085. }
  2086. },
  2087. stripCalendarRuleConfig(remark) {
  2088. return String(remark || '')
  2089. .replace(/\s*\[calendarRules\][\s\S]*?\[\/calendarRules\]\s*/g, '')
  2090. .trim();
  2091. },
  2092. getCalendarRulePayload(form) {
  2093. return {
  2094. applyMonth: form.applyMonth || this.getFullMonthList(),
  2095. shiftId: form.shiftId || '',
  2096. shiftName: form.shiftName || '',
  2097. shiftCode: form.shiftCode || '',
  2098. restMode: form.restMode || 'double',
  2099. restWeekdays: form.restWeekdays || [],
  2100. legalHolidayWorkDates: form.legalHolidayWorkDates || [],
  2101. holidayRules: (form.holidayRules || [])
  2102. .filter((item) => item.calendarDate)
  2103. .map((item) => ({
  2104. calendarDate: item.calendarDate,
  2105. dateType: Number(item.dateType || 3),
  2106. remark: item.remark || ''
  2107. }))
  2108. };
  2109. },
  2110. mergeTimeRanges(...groups) {
  2111. const map = {};
  2112. groups.flat().forEach((item, index) => {
  2113. if (!item) {
  2114. return;
  2115. }
  2116. const startTime = String(item.startTime || '').slice(0, 5);
  2117. const endTime = String(item.endTime || '').slice(0, 5);
  2118. if (!startTime || !endTime) {
  2119. return;
  2120. }
  2121. const name = item.name || item.remark || `时段${index + 1}`;
  2122. const key = `${name}-${startTime}-${endTime}`;
  2123. if (!map[key]) {
  2124. map[key] = {
  2125. ...item,
  2126. id: item.id || key,
  2127. name,
  2128. startTime,
  2129. endTime,
  2130. timeType: item.timeType || '1'
  2131. };
  2132. }
  2133. });
  2134. return Object.values(map);
  2135. },
  2136. normalizeRemoteDetail(detail, calendar = {}) {
  2137. const calendarType = detail.calendarType || calendar.calendarType;
  2138. const relationPlanList = this.normalizeRemotePlans(
  2139. detail.relationPlanList || []
  2140. );
  2141. const relationEamPlanList = this.normalizeRemotePlans(
  2142. detail.relationEamPlanList || []
  2143. );
  2144. const relationTeamQueueList = this.normalizeRemotePlans(
  2145. detail.relationTeamQueueList || []
  2146. );
  2147. const relationPlanCountMap = {
  2148. 2: relationEamPlanList.length,
  2149. 3: relationTeamQueueList.length
  2150. };
  2151. const relationPlanCount =
  2152. relationPlanCountMap[Number(calendarType)] ??
  2153. Number(detail.relationPlanCount || relationPlanList.length || 0);
  2154. return {
  2155. ...detail,
  2156. id:
  2157. detail.id ||
  2158. `${detail.calendarId}-${detail.calendarDate}-${detail.startTime}`,
  2159. calendarId: detail.calendarId || calendar.id,
  2160. calendarName: detail.calendarName || calendar.calendarName,
  2161. calendarType,
  2162. calendarDate: detail.calendarDate,
  2163. startTime: String(detail.startTime || '').slice(0, 5),
  2164. endTime: String(detail.endTime || '').slice(0, 5),
  2165. dateType: Number(detail.dateType || 1),
  2166. scheduleStatus: Number(detail.scheduleStatus || 0),
  2167. isConflict: Number(detail.isConflict || 0),
  2168. isTempAdjust: Number(detail.isTempAdjust || 0),
  2169. relationPlanCount,
  2170. relationPlanList,
  2171. relationEamPlanList,
  2172. relationTeamQueueList
  2173. };
  2174. },
  2175. saveData() {
  2176. // 工厂日历页面以后台接口为唯一数据源,不再写入本地演示缓存。
  2177. },
  2178. openImport() {
  2179. this.$message.warning(
  2180. '批量导入需要后端导入接口支持,当前页面不再写入本地数据'
  2181. );
  2182. },
  2183. async calendarDatasource({
  2184. page = 1,
  2185. limit = this.pageSize,
  2186. where = {},
  2187. order = {}
  2188. } = {}) {
  2189. try {
  2190. const data = await pageCalendar({
  2191. ...this.getCalendarQueryParams({
  2192. ...this.query,
  2193. ...where
  2194. }),
  2195. ...order,
  2196. pageNum: page,
  2197. size: limit
  2198. });
  2199. const { list, count } = normalizePage(data);
  2200. const rows = list.map((item) => this.normalizeRemoteCalendar(item));
  2201. return { code: 0, list: rows, count };
  2202. } catch (e) {
  2203. return this.getPagedResult([], page, limit);
  2204. }
  2205. },
  2206. getPagedResult(list, page = 1, limit = this.pageSize) {
  2207. const start = (page - 1) * limit;
  2208. return {
  2209. code: 0,
  2210. list: list.slice(start, start + limit),
  2211. count: list.length
  2212. };
  2213. },
  2214. reloadConflictTable(page = 1) {
  2215. this.$nextTick(() => {
  2216. this.$refs.conflictPanel?.reload?.({ page });
  2217. });
  2218. },
  2219. reloadAdjustTable(page = 1) {
  2220. this.$nextTick(() => {
  2221. this.$refs.adjustApproval?.reload?.({ page });
  2222. });
  2223. },
  2224. reloadPlanTable(page = 1) {
  2225. this.$nextTick(() => {
  2226. this.$refs.planLinkage?.reload?.({ page });
  2227. });
  2228. },
  2229. reloadBaseTable(page = 1) {
  2230. this.$nextTick(() => {
  2231. this.$refs.baseManage?.reload?.({ page });
  2232. });
  2233. },
  2234. async adjustDatasource({
  2235. page = 1,
  2236. limit = this.pageSize,
  2237. where = {},
  2238. order = {}
  2239. } = {}) {
  2240. try {
  2241. const data = await pageCalendarAdjust({
  2242. ...where,
  2243. ...order,
  2244. pageNum: page,
  2245. size: limit
  2246. });
  2247. const { list, count } = normalizePage(data);
  2248. return { code: 0, list, count };
  2249. } catch (e) {
  2250. return this.getPagedResult([], page, limit);
  2251. }
  2252. },
  2253. async planDatasource({ page = 1, limit = this.pageSize } = {}) {
  2254. await this.ensurePlanRefreshData(false);
  2255. if (this.plans.length) {
  2256. return this.getPagedResult(this.plans, page, limit);
  2257. }
  2258. const calendars = this.getCurrentViewCalendars();
  2259. if (calendars.some((item) => this.getRemoteCalendarId(item))) {
  2260. try {
  2261. await this.loadRemoteViewData();
  2262. const details = this.getViewDetails(this.viewQuery.date);
  2263. const plans = this.getDetailRelatedPlans(details);
  2264. return this.getPagedResult(plans, page, limit);
  2265. } catch (e) {
  2266. return this.getPagedResult([], page, limit);
  2267. }
  2268. }
  2269. return this.getPagedResult([], page, limit);
  2270. },
  2271. normalizeRemoteConflicts(data = {}) {
  2272. return (data.conflictDetail || []).map((item, index) => ({
  2273. id:
  2274. item.currentDetailId ||
  2275. [
  2276. item.calendarDate,
  2277. item.startTime,
  2278. item.endTime,
  2279. item.currentCalendarType,
  2280. item.conflictCalendarType,
  2281. item.conflictCalendarId,
  2282. item.conflictDetailId,
  2283. item.conflictMsg || data.msg || '',
  2284. index
  2285. ].join('-'),
  2286. calendarDate: item.calendarDate,
  2287. timeRange: `${String(item.startTime || '').slice(0, 5)}-${String(
  2288. item.endTime || ''
  2289. ).slice(0, 5)}`,
  2290. scene: `${item.currentCalendarType || ''} VS ${
  2291. item.conflictCalendarType || ''
  2292. }`,
  2293. level: data.isConflict ? '高' : '低',
  2294. message: item.conflictMsg || data.msg || ''
  2295. }));
  2296. },
  2297. normalizeRemotePlans(data = {}) {
  2298. const list = Array.isArray(data)
  2299. ? data
  2300. : [
  2301. ...(data.records || []),
  2302. ...(data.list || []),
  2303. ...(data.orderList || []),
  2304. ...(data.taskList || []),
  2305. ...(data.schedulePlanList || []),
  2306. ...(data.relationPlanList || []),
  2307. ...(data.relationEamPlanList || []),
  2308. ...(data.relationTeamQueueList || []),
  2309. ...(data.affectedPlanList || [])
  2310. ];
  2311. return list.map((item, index) => {
  2312. const planNo =
  2313. item.planNo ||
  2314. item.orderNo ||
  2315. item.code ||
  2316. item.teamQueueName ||
  2317. item.teamQueueId ||
  2318. `PLAN-${index + 1}`;
  2319. const salesCode = Array.isArray(item.salesCode)
  2320. ? item.salesCode.join(',')
  2321. : item.salesCode;
  2322. const rawStartTime =
  2323. item.rawStartTime ||
  2324. item.planStartTime ||
  2325. item.queueDate ||
  2326. item.startTime;
  2327. const rawEndTime =
  2328. item.rawEndTime ||
  2329. item.planEndTime ||
  2330. item.queueEndTime ||
  2331. item.endTime;
  2332. const startTime = this.formatPlanTime(rawStartTime);
  2333. const endTime = this.formatPlanTime(rawEndTime);
  2334. const displayStartTime = this.formatPlanDateTime(rawStartTime);
  2335. const displayEndTime = this.formatPlanDateTime(rawEndTime);
  2336. const hasDateRange =
  2337. /^\d{4}-\d{2}-\d{2}/.test(String(rawStartTime || '')) ||
  2338. /^\d{4}-\d{2}-\d{2}/.test(String(rawEndTime || ''));
  2339. return {
  2340. ...item,
  2341. id: item.id || planNo || index,
  2342. planNo,
  2343. orderNo:
  2344. item.orderNo ||
  2345. item.salesCodeList ||
  2346. salesCode ||
  2347. item.batchNo ||
  2348. item.teamName ||
  2349. item.teamId ||
  2350. item.userName ||
  2351. item.userId ||
  2352. '',
  2353. taskName:
  2354. item.taskName ||
  2355. item.productName ||
  2356. item.bomCategoryName ||
  2357. item.teamQueueName ||
  2358. item.queueName ||
  2359. item.teamName ||
  2360. item.userName ||
  2361. item.name ||
  2362. item.title ||
  2363. '关联计划',
  2364. calendarId: item.calendarId,
  2365. calendarDate:
  2366. item.calendarDate ||
  2367. this.formatPlanDate(
  2368. item.planDeliveryTime ||
  2369. item.reqMoldTime ||
  2370. item.planEndTime ||
  2371. item.planStartTime ||
  2372. item.queueDate ||
  2373. item.endTime ||
  2374. item.startTime
  2375. ),
  2376. startTime,
  2377. endTime,
  2378. rawStartTime,
  2379. rawEndTime,
  2380. displayStartTime,
  2381. displayEndTime,
  2382. timeRange: hasDateRange
  2383. ? `${displayStartTime} 至 ${displayEndTime}`
  2384. : `${startTime}-${endTime}`,
  2385. status: item.statusName || item.status || '正常',
  2386. canReschedule: !!item.canReschedule,
  2387. productionLineName:
  2388. item.productionLineName ||
  2389. item.productionLine ||
  2390. item.productionCodes ||
  2391. '',
  2392. workStationName: item.workStationName || item.workStation || ''
  2393. };
  2394. });
  2395. },
  2396. formatPlanDate(value) {
  2397. const text = String(value || '');
  2398. const matched = text.match(/^\d{4}-\d{2}-\d{2}/);
  2399. return matched ? matched[0] : this.viewQuery.date;
  2400. },
  2401. formatPlanTime(value) {
  2402. const text = String(value || '');
  2403. const matched = text.match(/\b(\d{2}):(\d{2})(?::\d{2})?\b/);
  2404. return matched ? `${matched[1]}:${matched[2]}` : text.slice(0, 5);
  2405. },
  2406. formatPlanDateTime(value) {
  2407. const text = String(value || '');
  2408. const matched = text.match(/^(\d{4}-\d{2}-\d{2})[ T](\d{2}):(\d{2})/);
  2409. if (matched) {
  2410. return `${matched[1]} ${matched[2]}:${matched[3]}`;
  2411. }
  2412. return this.formatPlanTime(value);
  2413. },
  2414. getDetailRelatedPlans(details = []) {
  2415. const map = {};
  2416. details.forEach((detail) => {
  2417. [
  2418. ...(detail.relationPlanList || []),
  2419. ...(detail.relationEamPlanList || []),
  2420. ...(detail.relationTeamQueueList || [])
  2421. ].forEach((plan, index) => {
  2422. const normalized = this.normalizeRemotePlans([plan])[0];
  2423. if (!normalized) {
  2424. return;
  2425. }
  2426. const key =
  2427. normalized.id ||
  2428. normalized.planNo ||
  2429. normalized.code ||
  2430. `${detail.id}-${index}`;
  2431. map[key] = {
  2432. ...normalized,
  2433. calendarId: normalized.calendarId || detail.calendarId,
  2434. calendarDate: detail.calendarDate || normalized.calendarDate,
  2435. calendarType: normalized.calendarType || detail.calendarType
  2436. };
  2437. });
  2438. });
  2439. return Object.values(map);
  2440. },
  2441. getRelatedPlanCode(plan = {}) {
  2442. return (
  2443. (this.isEquipmentDrawer
  2444. ? plan.deviceCode ||
  2445. plan.equipmentCode ||
  2446. plan.eamCode ||
  2447. plan.assetCode ||
  2448. plan.planNo
  2449. : plan.planNo) || '-'
  2450. );
  2451. },
  2452. getRelatedPlanName(plan = {}) {
  2453. return (
  2454. (this.isEquipmentDrawer
  2455. ? plan.deviceName ||
  2456. plan.equipmentName ||
  2457. plan.eamName ||
  2458. plan.assetName ||
  2459. plan.taskName
  2460. : plan.taskName) || '-'
  2461. );
  2462. },
  2463. getRelatedQueueName(plan = {}) {
  2464. return plan.teamQueueName || '-';
  2465. },
  2466. getRelatedQueueUserName(plan = {}) {
  2467. return plan.userName || '';
  2468. },
  2469. getDetailPlanCount(details = []) {
  2470. const relatedPlans = this.getDetailRelatedPlans(details);
  2471. if (relatedPlans.length) {
  2472. return relatedPlans.length;
  2473. }
  2474. return details.reduce(
  2475. (sum, item) => sum + Number(item.relationPlanCount || 0),
  2476. 0
  2477. );
  2478. },
  2479. syncFilteredCalendars() {
  2480. this.filteredCalendars = this.calendars.filter((item) => {
  2481. const yearMatch =
  2482. !this.query.year || item.applyYear.includes(this.query.year);
  2483. const typeMatch =
  2484. !this.query.calendarType ||
  2485. item.calendarType === this.query.calendarType;
  2486. const statusMatch =
  2487. this.query.status === '' || item.status === this.query.status;
  2488. return yearMatch && typeMatch && statusMatch;
  2489. });
  2490. },
  2491. async filterCalendar() {
  2492. this.viewDataKey = '';
  2493. this.invalidateConflictCache();
  2494. await this.loadRemoteCalendarData();
  2495. this.reloadBaseTable(1);
  2496. },
  2497. resetQuery() {
  2498. this.query = {
  2499. year: currentYear,
  2500. month: '',
  2501. calendarType: '',
  2502. status: ''
  2503. };
  2504. this.filterCalendar();
  2505. },
  2506. openCalendarDialog(row) {
  2507. this.calendarForm = row ? clone(row) : this.getDefaultCalendarForm();
  2508. this.calendarDialogVisible = true;
  2509. this.loadLegalHolidaysByYears(this.calendarForm.applyYear);
  2510. this.$nextTick(() => {
  2511. this.$refs.calendarForm?.clearValidate?.();
  2512. this.resetCalendarDialogScroll();
  2513. });
  2514. },
  2515. resetCalendarDialogScroll() {
  2516. const dialogBody = document.querySelector(
  2517. '.factory-calendar-dialog .el-dialog__body'
  2518. );
  2519. if (dialogBody) {
  2520. dialogBody.scrollTop = 0;
  2521. }
  2522. document
  2523. .querySelectorAll('.factory-calendar-dialog .legal-holiday-list')
  2524. .forEach((item) => {
  2525. item.scrollTop = 0;
  2526. });
  2527. },
  2528. saveCalendar() {
  2529. this.$refs.calendarForm.validate(async (valid) => {
  2530. if (!valid) {
  2531. return;
  2532. }
  2533. if (this.hasInvalidRestRule()) {
  2534. return;
  2535. }
  2536. if (this.hasInvalidHolidayRules()) {
  2537. return;
  2538. }
  2539. if (this.hasDuplicateCalendarTemplate()) {
  2540. this.$message.error('同类型同年份日历已存在,请勿重复创建');
  2541. return;
  2542. }
  2543. try {
  2544. const payload = this.toRemoteCalendarPayload(this.calendarForm);
  2545. if (this.calendarForm.id) {
  2546. await editCalendar(payload);
  2547. } else {
  2548. const result = await addCalendar(payload);
  2549. if (result?.id) {
  2550. this.calendarForm.id = result.id;
  2551. await updateCalendarStatus({
  2552. id: result.id,
  2553. status: Number(this.calendarForm.status || 0)
  2554. });
  2555. }
  2556. if (result?.calendarCode) {
  2557. this.calendarForm.calendarCode = result.calendarCode;
  2558. }
  2559. }
  2560. await this.loadRemoteCalendarData();
  2561. this.invalidateConflictCache();
  2562. this.reloadBaseTable(1);
  2563. this.calendarDialogVisible = false;
  2564. this.$message.success('保存成功');
  2565. return;
  2566. } catch (e) {
  2567. this.$message.error(e?.message || '保存失败,请检查接口返回');
  2568. }
  2569. });
  2570. },
  2571. hasDuplicateCalendarTemplate() {
  2572. return this.calendars.some((item) => {
  2573. if (item.id === this.calendarForm.id) {
  2574. return false;
  2575. }
  2576. const sameType = item.calendarType === this.calendarForm.calendarType;
  2577. const sameYear = item.applyYear.some((year) =>
  2578. this.calendarForm.applyYear.includes(year)
  2579. );
  2580. return (
  2581. sameType &&
  2582. sameYear &&
  2583. item.calendarName === this.calendarForm.calendarName
  2584. );
  2585. });
  2586. },
  2587. toRemoteCalendarPayload(form) {
  2588. const rulePayload = this.getCalendarRulePayload(form);
  2589. return {
  2590. id: form.id || undefined,
  2591. calendarName: form.calendarName,
  2592. calendarType: form.calendarType,
  2593. status: Number(form.status || 0),
  2594. applyYear: Array.isArray(form.applyYear)
  2595. ? form.applyYear.join(',')
  2596. : form.applyYear,
  2597. remark: this.stripCalendarRuleConfig(form.remark),
  2598. ...rulePayload,
  2599. segmentList: this.buildCalendarSegments(form)
  2600. };
  2601. },
  2602. getFullMonthList() {
  2603. return Array.from({ length: 12 }, (_, index) => index + 1);
  2604. },
  2605. getRestModeByWeekdays(weekdays) {
  2606. const values = (weekdays || []).map(Number).sort().join(',');
  2607. if (values === '0') {
  2608. return 'single';
  2609. }
  2610. if (values === '0,6') {
  2611. return 'double';
  2612. }
  2613. if (!values) {
  2614. return 'none';
  2615. }
  2616. return 'double';
  2617. },
  2618. isRestDateByMode(dateItem, restMode) {
  2619. const weekDay = dateItem.day();
  2620. if (restMode === 'none') {
  2621. return false;
  2622. }
  2623. if (restMode === 'single') {
  2624. return weekDay === 0;
  2625. }
  2626. if (restMode === 'alternate') {
  2627. const yearStart = dayjs(`${dateItem.year()}-01-01`);
  2628. const weekIndex = Math.floor(dateItem.diff(yearStart, 'day') / 7);
  2629. return weekDay === 0 || (weekDay === 6 && weekIndex % 2 === 0);
  2630. }
  2631. if (restMode === 'custom') {
  2632. return false;
  2633. }
  2634. return weekDay === 0 || weekDay === 6;
  2635. },
  2636. getLegalHolidayInfo(dateItem) {
  2637. if (!dateItem || !dateItem.isValid()) {
  2638. return null;
  2639. }
  2640. const holidayInfo = this.getConfiguredHolidayRanges(
  2641. dateItem.year()
  2642. ).find(
  2643. (item) =>
  2644. !dateItem.isBefore(dayjs(item.start), 'day') &&
  2645. !dateItem.isAfter(dayjs(item.end), 'day')
  2646. );
  2647. if (holidayInfo) {
  2648. return {
  2649. name: holidayInfo.name,
  2650. calendarDate: dateItem.format('YYYY-MM-DD')
  2651. };
  2652. }
  2653. const lunar = solarToLunar(
  2654. dateItem.year(),
  2655. dateItem.month() + 1,
  2656. dateItem.date()
  2657. );
  2658. const festivalText = [
  2659. lunar.solarFestival,
  2660. lunar.lunarFestival,
  2661. lunar.term
  2662. ]
  2663. .filter(Boolean)
  2664. .join(' ');
  2665. const match = legalHolidayKeywords.find((item) =>
  2666. festivalText.includes(item.keyword)
  2667. );
  2668. return match
  2669. ? {
  2670. name: match.label,
  2671. calendarDate: dateItem.format('YYYY-MM-DD')
  2672. }
  2673. : null;
  2674. },
  2675. getLegalHolidayFestivalDates(year) {
  2676. const festivalMap = {};
  2677. const firstDay = dayjs(`${year}-01-01`);
  2678. const end = firstDay.endOf('year');
  2679. let cursor = firstDay;
  2680. while (!cursor.isAfter(end, 'day')) {
  2681. const lunar = solarToLunar(
  2682. cursor.year(),
  2683. cursor.month() + 1,
  2684. cursor.date()
  2685. );
  2686. const festivalText = [
  2687. lunar.solarFestival,
  2688. lunar.lunarFestival,
  2689. lunar.term
  2690. ]
  2691. .filter(Boolean)
  2692. .join(' ');
  2693. const match = legalHolidayKeywords.find((item) =>
  2694. festivalText.includes(item.keyword)
  2695. );
  2696. if (match && !festivalMap[match.label]) {
  2697. festivalMap[match.label] = cursor.format('YYYY-MM-DD');
  2698. }
  2699. cursor = cursor.add(1, 'day');
  2700. }
  2701. return festivalMap;
  2702. },
  2703. getInferredHolidayRanges(year) {
  2704. if (inferredHolidayRangeCache[year]) {
  2705. return inferredHolidayRangeCache[year];
  2706. }
  2707. const festivalDates = this.getLegalHolidayFestivalDates(year);
  2708. const ranges = Object.keys(festivalDates).map((name) => {
  2709. const rule = inferredHolidayRules[name] || { before: 0, after: 0 };
  2710. const date = dayjs(festivalDates[name]);
  2711. return {
  2712. name,
  2713. start: date.subtract(rule.before, 'day').format('YYYY-MM-DD'),
  2714. end: date.add(rule.after, 'day').format('YYYY-MM-DD')
  2715. };
  2716. });
  2717. inferredHolidayRangeCache[year] = ranges;
  2718. return ranges;
  2719. },
  2720. getConfiguredHolidayRanges(year) {
  2721. const remoteRanges = this.legalHolidayCache[year];
  2722. if (remoteRanges && remoteRanges.length) {
  2723. return remoteRanges;
  2724. }
  2725. return (
  2726. officialHolidayRanges[year] || this.getInferredHolidayRanges(year)
  2727. );
  2728. },
  2729. async loadLegalHolidaysByYears(applyYear) {
  2730. const years = normalizeYearList(applyYear);
  2731. if (!years.length) {
  2732. return;
  2733. }
  2734. this.legalHolidayLoading = true;
  2735. try {
  2736. await Promise.all(
  2737. years.map((year) => this.loadLegalHolidayYear(year))
  2738. );
  2739. } finally {
  2740. this.legalHolidayLoading = false;
  2741. }
  2742. },
  2743. async loadLegalHolidayYear(year) {
  2744. if (
  2745. this.legalHolidayCache[year] ||
  2746. this.legalHolidayStatusMap[year] === 'fallback'
  2747. ) {
  2748. return this.legalHolidayCache[year];
  2749. }
  2750. if (!this.legalHolidayPromises[year]) {
  2751. this.$set(this.legalHolidayStatusMap, year, 'loading');
  2752. this.legalHolidayPromises[year] = getPublicLegalHolidays(year)
  2753. .then((data) => {
  2754. const ranges = this.normalizePublicHolidayRanges(data, year);
  2755. if (ranges.length) {
  2756. this.$set(this.legalHolidayCache, year, ranges);
  2757. this.$set(this.legalHolidayStatusMap, year, 'remote');
  2758. } else {
  2759. this.$set(this.legalHolidayStatusMap, year, 'fallback');
  2760. }
  2761. return ranges;
  2762. })
  2763. .catch(() => {
  2764. this.$set(this.legalHolidayStatusMap, year, 'fallback');
  2765. return [];
  2766. })
  2767. .finally(() => {
  2768. this.$delete(this.legalHolidayPromises, year);
  2769. });
  2770. }
  2771. return this.legalHolidayPromises[year];
  2772. },
  2773. normalizePublicHolidayRanges(data, year) {
  2774. const rawList = this.extractPublicHolidayList(data);
  2775. const dateMap = {};
  2776. rawList.forEach((item) => {
  2777. const source = this.normalizePublicHolidayItem(item);
  2778. const dateText = this.normalizePublicHolidayDate(
  2779. source.calendarDate,
  2780. year
  2781. );
  2782. if (!dateText) {
  2783. return;
  2784. }
  2785. const isWorkday =
  2786. source.isWorkday === true ||
  2787. source.is_workday === true ||
  2788. source.workday === true ||
  2789. source.is_holiday === false ||
  2790. source.holiday === false ||
  2791. source.type === 'workday' ||
  2792. source.type === 'work' ||
  2793. source.type === 0;
  2794. if (isWorkday) {
  2795. return;
  2796. }
  2797. dateMap[dateText] = {
  2798. name:
  2799. source.name ||
  2800. source.holidayName ||
  2801. source.festival ||
  2802. source.title ||
  2803. '法定节假日',
  2804. calendarDate: dateText
  2805. };
  2806. });
  2807. return this.mergeHolidayDatesToRanges(Object.values(dateMap));
  2808. },
  2809. normalizePublicHolidayItem(item) {
  2810. if (typeof item === 'string') {
  2811. return {
  2812. calendarDate: item
  2813. };
  2814. }
  2815. if (!item || typeof item !== 'object') {
  2816. return {};
  2817. }
  2818. return {
  2819. ...item,
  2820. calendarDate:
  2821. item.date ||
  2822. item.calendarDate ||
  2823. item.holidayDate ||
  2824. item.day ||
  2825. item.time
  2826. };
  2827. },
  2828. normalizePublicHolidayDate(value, year) {
  2829. if (!value && value !== 0) {
  2830. return '';
  2831. }
  2832. const text = String(value).trim();
  2833. let match = text.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})$/);
  2834. if (match) {
  2835. const date = dayjs(
  2836. `${match[1]}-${String(match[2]).padStart(2, '0')}-${String(
  2837. match[3]
  2838. ).padStart(2, '0')}`
  2839. );
  2840. return date.isValid() && date.year() === Number(year)
  2841. ? date.format('YYYY-MM-DD')
  2842. : '';
  2843. }
  2844. match = text.match(/^(\d{4})(\d{2})(\d{2})$/);
  2845. if (match) {
  2846. const date = dayjs(`${match[1]}-${match[2]}-${match[3]}`);
  2847. return date.isValid() && date.year() === Number(year)
  2848. ? date.format('YYYY-MM-DD')
  2849. : '';
  2850. }
  2851. match = text.match(/^(\d{1,2})[-/](\d{1,2})$/);
  2852. if (match) {
  2853. const date = dayjs(
  2854. `${year}-${String(match[1]).padStart(2, '0')}-${String(
  2855. match[2]
  2856. ).padStart(2, '0')}`
  2857. );
  2858. return date.isValid() ? date.format('YYYY-MM-DD') : '';
  2859. }
  2860. return '';
  2861. },
  2862. extractPublicHolidayList(data) {
  2863. if (Array.isArray(data)) {
  2864. return data;
  2865. }
  2866. if (Array.isArray(data?.data)) {
  2867. return data.data;
  2868. }
  2869. if (Array.isArray(data?.holidays)) {
  2870. return data.holidays;
  2871. }
  2872. if (Array.isArray(data?.data?.holidays)) {
  2873. return data.data.holidays;
  2874. }
  2875. const source =
  2876. data?.data && typeof data.data === 'object' ? data.data : data;
  2877. if (source && typeof source === 'object') {
  2878. return Object.keys(source).map((key) => {
  2879. const value = source[key];
  2880. if (typeof value === 'string') {
  2881. return {
  2882. calendarDate: key,
  2883. name: value
  2884. };
  2885. }
  2886. return {
  2887. calendarDate: key,
  2888. ...(value || {})
  2889. };
  2890. });
  2891. }
  2892. return [];
  2893. },
  2894. mergeHolidayDatesToRanges(holidayList) {
  2895. const list = holidayList
  2896. .filter((item) => item.calendarDate)
  2897. .sort((a, b) => a.calendarDate.localeCompare(b.calendarDate));
  2898. const ranges = [];
  2899. list.forEach((item) => {
  2900. const last = ranges[ranges.length - 1];
  2901. if (
  2902. last &&
  2903. last.name === item.name &&
  2904. dayjs(item.calendarDate).diff(dayjs(last.end), 'day') === 1
  2905. ) {
  2906. last.end = item.calendarDate;
  2907. } else {
  2908. ranges.push({
  2909. name: item.name,
  2910. start: item.calendarDate,
  2911. end: item.calendarDate
  2912. });
  2913. }
  2914. });
  2915. return ranges;
  2916. },
  2917. getLegalHolidayName(dateItem) {
  2918. return this.getLegalHolidayInfo(dateItem)?.name || '';
  2919. },
  2920. getLegalHolidayOptions(applyYear, applyMonth) {
  2921. const monthSet = new Set(
  2922. (applyMonth || this.getFullMonthList()).map(Number)
  2923. );
  2924. const holidayMap = {};
  2925. normalizeYearList(applyYear).forEach((year) => {
  2926. const ranges = this.getConfiguredHolidayRanges(year);
  2927. ranges.forEach((range) => {
  2928. let cursor = dayjs(range.start);
  2929. const end = dayjs(range.end);
  2930. while (!cursor.isAfter(end, 'day')) {
  2931. if (monthSet.has(cursor.month() + 1)) {
  2932. const calendarDate = cursor.format('YYYY-MM-DD');
  2933. if (!holidayMap[calendarDate]) {
  2934. holidayMap[calendarDate] = {
  2935. name: range.name,
  2936. calendarDate
  2937. };
  2938. }
  2939. }
  2940. cursor = cursor.add(1, 'day');
  2941. }
  2942. });
  2943. });
  2944. return Object.values(holidayMap).sort((a, b) =>
  2945. a.calendarDate.localeCompare(b.calendarDate)
  2946. );
  2947. },
  2948. getCalendarDateType(cursor, restMode, customRestWeekdays, specialRule) {
  2949. if (specialRule) {
  2950. return specialRule.dateType;
  2951. }
  2952. if (this.getLegalHolidayName(cursor)) {
  2953. return 3;
  2954. }
  2955. if (restMode === 'custom') {
  2956. return customRestWeekdays.has(cursor.day()) ? 2 : 1;
  2957. }
  2958. return this.isRestDateByMode(cursor, restMode) ? 2 : 1;
  2959. },
  2960. getLegalHolidayRules(form) {
  2961. const holidayInfoMap = {};
  2962. this.getLegalHolidayOptions(form.applyYear, form.applyMonth).forEach(
  2963. (item) => {
  2964. holidayInfoMap[item.calendarDate] = item;
  2965. }
  2966. );
  2967. return (form.legalHolidayWorkDates || [])
  2968. .filter((date) => holidayInfoMap[date])
  2969. .map((date) => ({
  2970. calendarDate: date,
  2971. dateType: 1,
  2972. remark: holidayInfoMap[date].name
  2973. }));
  2974. },
  2975. buildCalendarSegments(form) {
  2976. const ranges = form.timeRanges || [];
  2977. const monthList = (form.applyMonth || this.getFullMonthList())
  2978. .map(Number)
  2979. .filter(Boolean);
  2980. const applyMonths = new Set(monthList);
  2981. const restMode =
  2982. form.restMode || this.getRestModeByWeekdays(form.restWeekdays);
  2983. const customRestWeekdays = new Set(
  2984. (form.restWeekdays || []).map(Number)
  2985. );
  2986. const specialRuleMap = {};
  2987. const specialRules = [
  2988. ...this.getLegalHolidayRules(form),
  2989. ...(form.holidayRules || [])
  2990. ];
  2991. specialRules.forEach((rule) => {
  2992. if (rule.calendarDate) {
  2993. specialRuleMap[rule.calendarDate] = {
  2994. ...rule,
  2995. dateType: Number(rule.dateType || 3)
  2996. };
  2997. }
  2998. });
  2999. const segments = [];
  3000. if (!applyMonths.size) {
  3001. return segments;
  3002. }
  3003. normalizeYearList(form.applyYear).forEach((year) => {
  3004. const months = Array.from(applyMonths).sort((a, b) => a - b);
  3005. let cursor = dayjs(
  3006. `${year}-${String(months[0]).padStart(2, '0')}-01`
  3007. );
  3008. const lastMonth = months[months.length - 1];
  3009. const end = dayjs(
  3010. `${year}-${String(lastMonth).padStart(2, '0')}-01`
  3011. ).endOf('month');
  3012. while (!cursor.isAfter(end, 'day')) {
  3013. if (!applyMonths.has(cursor.month() + 1)) {
  3014. cursor = cursor.add(1, 'day');
  3015. continue;
  3016. }
  3017. const calendarDate = cursor.format('YYYY-MM-DD');
  3018. const specialRule = specialRuleMap[calendarDate];
  3019. const legalHolidayName = this.getLegalHolidayName(cursor);
  3020. const dateType = this.getCalendarDateType(
  3021. cursor,
  3022. restMode,
  3023. customRestWeekdays,
  3024. specialRule
  3025. );
  3026. if (dateType === 1) {
  3027. const workRanges = ranges.length
  3028. ? ranges
  3029. : [
  3030. {
  3031. startTime: '00:00',
  3032. endTime: '23:59',
  3033. scheduleStatus: 0,
  3034. remark:
  3035. specialRule?.remark || legalHolidayName || '工作日'
  3036. }
  3037. ];
  3038. workRanges.forEach((range) => {
  3039. segments.push({
  3040. calendarDate,
  3041. startTime: range.startTime,
  3042. endTime: range.endTime,
  3043. dateType: 1,
  3044. scheduleStatus:
  3045. range.scheduleStatus === undefined
  3046. ? 0
  3047. : range.scheduleStatus,
  3048. remark:
  3049. range.name ||
  3050. range.remark ||
  3051. specialRule?.remark ||
  3052. legalHolidayName ||
  3053. ''
  3054. });
  3055. });
  3056. } else {
  3057. segments.push({
  3058. calendarDate,
  3059. startTime: '00:00',
  3060. endTime: '23:59',
  3061. dateType,
  3062. scheduleStatus: 0,
  3063. remark:
  3064. specialRule?.remark ||
  3065. legalHolidayName ||
  3066. (dateType === 3 ? '法定节假日' : '休息日')
  3067. });
  3068. }
  3069. cursor = cursor.add(1, 'day');
  3070. }
  3071. });
  3072. return segments;
  3073. },
  3074. hasInvalidRestRule() {
  3075. if (
  3076. this.calendarForm.restMode === 'custom' &&
  3077. !(this.calendarForm.restWeekdays || []).length
  3078. ) {
  3079. this.$message.error('自定义休息请至少选择一个休息星期');
  3080. return true;
  3081. }
  3082. return false;
  3083. },
  3084. hasInvalidHolidayRules() {
  3085. const dateMap = {};
  3086. (this.calendarForm.legalHolidayWorkDates || []).forEach((date) => {
  3087. dateMap[date] = true;
  3088. });
  3089. const years = new Set(
  3090. normalizeYearList(this.calendarForm.applyYear).map(String)
  3091. );
  3092. const months = new Set(
  3093. (this.calendarForm.applyMonth || []).map((item) => Number(item))
  3094. );
  3095. for (const rule of this.calendarForm.holidayRules || []) {
  3096. if (!rule.calendarDate) {
  3097. this.$message.error('特殊日期存在未选择日期的配置,请补充或删除');
  3098. return true;
  3099. }
  3100. if (!years.has(dayjs(rule.calendarDate).format('YYYY'))) {
  3101. this.$message.error('特殊日期必须在适用年份范围内');
  3102. return true;
  3103. }
  3104. if (!months.has(dayjs(rule.calendarDate).month() + 1)) {
  3105. this.$message.error('特殊日期必须在适用月份范围内');
  3106. return true;
  3107. }
  3108. if (dateMap[rule.calendarDate]) {
  3109. this.$message.error('特殊日期存在重复日期,请调整后保存');
  3110. return true;
  3111. }
  3112. dateMap[rule.calendarDate] = true;
  3113. }
  3114. return false;
  3115. },
  3116. hasDuplicateDetail(
  3117. calendarId,
  3118. calendarDate,
  3119. startTime,
  3120. endTime,
  3121. excludeId
  3122. ) {
  3123. const calendar = this.calendars.find((item) => item.id === calendarId);
  3124. if (!calendar) {
  3125. return false;
  3126. }
  3127. return this.details.some((item) => {
  3128. const itemCalendar = this.calendars.find(
  3129. (calendarItem) => calendarItem.id === item.calendarId
  3130. );
  3131. return (
  3132. item.id !== excludeId &&
  3133. item.calendarDate === calendarDate &&
  3134. itemCalendar?.calendarType === calendar.calendarType &&
  3135. isOverlap(startTime, endTime, item.startTime, item.endTime)
  3136. );
  3137. });
  3138. },
  3139. addHolidayRule() {
  3140. this.calendarForm.holidayRules.push(createHolidayRule(1));
  3141. },
  3142. removeHolidayRule(index) {
  3143. this.calendarForm.holidayRules.splice(index, 1);
  3144. },
  3145. handleApplyMonthChange() {
  3146. this.pruneLegalHolidayWorkDates();
  3147. },
  3148. pruneLegalHolidayWorkDates() {
  3149. const visibleDates = new Set(
  3150. this.legalHolidayOptions.map((item) => item.calendarDate)
  3151. );
  3152. this.calendarForm.legalHolidayWorkDates = (
  3153. this.calendarForm.legalHolidayWorkDates || []
  3154. ).filter((date) => visibleDates.has(date));
  3155. },
  3156. changeLegalHolidayWorkStatus(calendarDate, checked) {
  3157. const dates = new Set(this.calendarForm.legalHolidayWorkDates || []);
  3158. if (checked) {
  3159. dates.add(calendarDate);
  3160. } else {
  3161. dates.delete(calendarDate);
  3162. }
  3163. this.calendarForm.legalHolidayWorkDates = Array.from(dates).sort();
  3164. },
  3165. toggleLegalHolidayWorkStatus(calendarDate) {
  3166. const checked = !(
  3167. this.calendarForm.legalHolidayWorkDates || []
  3168. ).includes(calendarDate);
  3169. this.changeLegalHolidayWorkStatus(calendarDate, checked);
  3170. },
  3171. formatHolidayDate(calendarDate) {
  3172. return dayjs(calendarDate).format('MM-DD');
  3173. },
  3174. getTimePickerOptions(minTime) {
  3175. return minTime
  3176. ? {
  3177. ...this.timePickerOptions,
  3178. minTime
  3179. }
  3180. : this.timePickerOptions;
  3181. },
  3182. async changeCalendarStatus(row) {
  3183. try {
  3184. await updateCalendarStatus({
  3185. id: row.id,
  3186. status: row.status
  3187. });
  3188. await this.loadRemoteCalendarData();
  3189. this.invalidateConflictCache();
  3190. this.reloadBaseTable(1);
  3191. this.$message.success(row.status ? '已启用' : '已禁用');
  3192. return;
  3193. } catch (e) {
  3194. row.status = row.status === 1 ? 0 : 1;
  3195. this.$message.error(e?.message || '状态更新失败,请检查接口返回');
  3196. }
  3197. },
  3198. async deleteCalendarRow(row) {
  3199. if (!row?.id) {
  3200. this.$message.error('未获取到日历ID,无法删除');
  3201. return;
  3202. }
  3203. try {
  3204. const calendarName = row.calendarName || row.calendarCode || row.id;
  3205. await this.$confirm(`确认删除日历 ${calendarName} 吗?`, '删除确认', {
  3206. type: 'warning'
  3207. });
  3208. await deleteCalendar([row.id]);
  3209. await this.loadRemoteCalendarData();
  3210. this.invalidateConflictCache();
  3211. this.reloadBaseTable(1);
  3212. await this.refreshRemoteView();
  3213. this.$message.success('删除成功');
  3214. } catch (e) {
  3215. if (e === 'cancel' || e === 'close') {
  3216. return;
  3217. }
  3218. this.$message.error(e?.message || '删除失败,请检查接口返回');
  3219. }
  3220. },
  3221. openCopyDialog() {
  3222. this.copyForm = {
  3223. sourceId: this.calendars[0]?.id || '',
  3224. targetYear: currentYear + 1
  3225. };
  3226. this.copyDialogVisible = true;
  3227. },
  3228. async copyCalendar() {
  3229. const source = this.calendars.find(
  3230. (item) => item.id === this.copyForm.sourceId
  3231. );
  3232. if (!source || !this.copyForm.targetYear) {
  3233. this.$message.error('请选择源日历和目标年份');
  3234. return;
  3235. }
  3236. try {
  3237. await copyCalendar({
  3238. sourceId: this.copyForm.sourceId,
  3239. targetYear: this.copyForm.targetYear
  3240. });
  3241. await this.loadRemoteCalendarData();
  3242. this.invalidateConflictCache();
  3243. this.reloadBaseTable(1);
  3244. this.copyDialogVisible = false;
  3245. this.$message.success('复制成功,新日历默认禁用');
  3246. return;
  3247. } catch (e) {
  3248. this.$message.error(e?.message || '复制失败,请检查接口返回');
  3249. }
  3250. },
  3251. async locateCalendar(row) {
  3252. this.activeTab = 'view';
  3253. this.viewQuery.calendarType = row.calendarType;
  3254. this.viewQuery.year = row.applyYear[0] || currentYear;
  3255. this.viewQuery.date = `${this.viewQuery.year}-${String(
  3256. this.viewQuery.month
  3257. ).padStart(2, '0')}-01`;
  3258. this.viewMonth = `${this.viewQuery.year}-${String(
  3259. this.viewQuery.month
  3260. ).padStart(2, '0')}`;
  3261. await this.refreshRemoteView();
  3262. },
  3263. async changeViewCalendarType() {
  3264. await this.refreshRemoteView();
  3265. },
  3266. async changeViewMonth(value) {
  3267. if (!value) {
  3268. return;
  3269. }
  3270. const [year, month] = value.split('-');
  3271. this.viewQuery.year = Number(year);
  3272. this.viewQuery.month = Number(month);
  3273. this.viewQuery.date = `${year}-${month}-01`;
  3274. await this.refreshRemoteView();
  3275. },
  3276. async changeViewType(type) {
  3277. if (type === 'quarter') {
  3278. const quarterStartMonth =
  3279. Math.floor((this.viewQuery.month - 1) / 3) * 3 + 1;
  3280. this.viewQuery.month = quarterStartMonth;
  3281. this.viewQuery.date = `${this.viewQuery.year}-${String(
  3282. quarterStartMonth
  3283. ).padStart(2, '0')}-01`;
  3284. this.viewMonth = `${this.viewQuery.year}-${String(
  3285. quarterStartMonth
  3286. ).padStart(2, '0')}`;
  3287. await this.refreshRemoteView();
  3288. return;
  3289. }
  3290. if (type === 'month') {
  3291. this.viewQuery.date = `${this.viewQuery.year}-${String(
  3292. this.viewQuery.month
  3293. ).padStart(2, '0')}-01`;
  3294. }
  3295. await this.refreshRemoteView();
  3296. },
  3297. async refreshRemoteView() {
  3298. await this.loadRemoteViewData(true);
  3299. this.plans = [];
  3300. this.planDataKey = '';
  3301. this.reloadPlanTable(1);
  3302. },
  3303. async refreshStatView() {
  3304. await this.loadRemoteViewData(true, {
  3305. viewType: 'month',
  3306. date: `${this.viewQuery.year}-${String(this.viewQuery.month).padStart(
  3307. 2,
  3308. '0'
  3309. )}-01`
  3310. });
  3311. },
  3312. getViewDetails(date) {
  3313. return this.details.filter(
  3314. (item) =>
  3315. this.isDetailInCurrentView(item) && item.calendarDate === date
  3316. );
  3317. },
  3318. getStatMonthDetails() {
  3319. const monthStart = dayjs(
  3320. `${this.viewQuery.year}-${String(this.viewQuery.month).padStart(
  3321. 2,
  3322. '0'
  3323. )}-01`
  3324. );
  3325. const monthEnd = monthStart.endOf('month');
  3326. return this.details.filter((item) => {
  3327. const date = dayjs(item.calendarDate);
  3328. return (
  3329. this.isDetailInCurrentView(item) &&
  3330. date.isValid() &&
  3331. (date.isSame(monthStart, 'day') || date.isAfter(monthStart)) &&
  3332. (date.isSame(monthEnd, 'day') || date.isBefore(monthEnd))
  3333. );
  3334. });
  3335. },
  3336. isDetailInCurrentView(item = {}) {
  3337. const targetType = Number(this.viewQuery.calendarType);
  3338. const detailType = Number(item.calendarType);
  3339. const typeMatched = targetType ? detailType === targetType : true;
  3340. const calendarIds = new Set(
  3341. this.getCurrentViewCalendars().map((calendar) => String(calendar.id))
  3342. );
  3343. const hasCalendarId =
  3344. item.calendarId !== undefined &&
  3345. item.calendarId !== null &&
  3346. item.calendarId !== '';
  3347. if (hasCalendarId && calendarIds.has(String(item.calendarId))) {
  3348. return true;
  3349. }
  3350. if (item.isViewDetail) {
  3351. return typeMatched;
  3352. }
  3353. return !hasCalendarId && typeMatched;
  3354. },
  3355. isDetailScheduled(item = {}) {
  3356. return (
  3357. Number(item.scheduleStatus) === 1 ||
  3358. Number(item.relationPlanCount || 0) > 0 ||
  3359. this.getDetailRelatedPlans([item]).length > 0
  3360. );
  3361. },
  3362. isWeekend(date) {
  3363. const week = dayjs(date).day();
  3364. return week === 0 || week === 6;
  3365. },
  3366. isRestDay(date, details) {
  3367. if (!details.length) {
  3368. return this.isWeekend(date);
  3369. }
  3370. return details.every((item) => [2, 3].includes(item.dateType));
  3371. },
  3372. getConflictText(date) {
  3373. const conflict = this.conflictList.find(
  3374. (item) => item.calendarDate === date
  3375. );
  3376. return conflict?.message || '';
  3377. },
  3378. matchStatusFilter(day) {
  3379. const filter = this.viewQuery.statusFilter;
  3380. if (!filter || !day.date) {
  3381. return true;
  3382. }
  3383. const matchMap = {
  3384. scheduled: day.scheduleStatus,
  3385. idle: !day.scheduleStatus && !day.isRest,
  3386. rest: day.isRest,
  3387. maintenance: day.isMaintenance,
  3388. temp: day.isTempAdjust,
  3389. conflict: day.isConflict
  3390. };
  3391. return matchMap[filter];
  3392. },
  3393. getDayClass(day) {
  3394. if (!day.date) {
  3395. return ['empty'];
  3396. }
  3397. if (day.isDisabledCalendar) {
  3398. return ['disabled-calendar'];
  3399. }
  3400. if (day.hiddenByFilter) {
  3401. return ['muted'];
  3402. }
  3403. if (day.isConflict) {
  3404. return ['conflict'];
  3405. }
  3406. if (day.isTempAdjust) {
  3407. return ['temp'];
  3408. }
  3409. if (day.isMaintenance) {
  3410. return ['maintenance'];
  3411. }
  3412. if (day.isHoliday) {
  3413. return ['holiday'];
  3414. }
  3415. if (day.isRest) {
  3416. return ['rest'];
  3417. }
  3418. if (day.scheduleStatus) {
  3419. return ['scheduled'];
  3420. }
  3421. return ['idle'];
  3422. },
  3423. getDateTypeText(day) {
  3424. if (!day.date) {
  3425. return '';
  3426. }
  3427. if (day.isHoliday) {
  3428. return day.holidayName || '法定节假日';
  3429. }
  3430. if (day.isRest && !day.details.length) {
  3431. return '休息日';
  3432. }
  3433. const first = day.details[0];
  3434. return first
  3435. ? this.getLabel(dateTypeOptions, first.dateType)
  3436. : '正常工作日';
  3437. },
  3438. getRangeText(details) {
  3439. if (!details.length) {
  3440. return '无有效时段';
  3441. }
  3442. return details
  3443. .map((item) => `${item.startTime}-${item.endTime}`)
  3444. .join('、');
  3445. },
  3446. buildAdjustSegments() {
  3447. return [
  3448. {
  3449. calendarDate: this.adjustForm.adjustDate,
  3450. startTime: this.adjustForm.startTime,
  3451. endTime: this.adjustForm.endTime,
  3452. dateType: this.getAdjustDateType(this.adjustForm.adjustType),
  3453. scheduleStatus: this.adjustForm.adjustType === 2 ? 0 : 1,
  3454. remark: this.adjustForm.applyReason || ''
  3455. }
  3456. ];
  3457. },
  3458. stringifySegments(segments) {
  3459. return JSON.stringify(segments || []);
  3460. },
  3461. parseSegmentContent(content) {
  3462. if (Array.isArray(content)) {
  3463. return content;
  3464. }
  3465. if (!content || typeof content !== 'string') {
  3466. return [];
  3467. }
  3468. try {
  3469. const parsed = JSON.parse(content);
  3470. return Array.isArray(parsed) ? parsed : [parsed];
  3471. } catch (e) {
  3472. const [timeRange] = content.split(' ');
  3473. const [startTime, endTime] = timeRange.split('-');
  3474. return startTime && endTime ? [{ startTime, endTime }] : [];
  3475. }
  3476. },
  3477. formatSegmentContent(content, row = {}) {
  3478. const segments = this.parseSegmentContent(content);
  3479. if (!segments.length) {
  3480. return content || '';
  3481. }
  3482. return segments
  3483. .map((segment) => {
  3484. const startTime = String(segment.startTime || '').slice(0, 5);
  3485. const endTime = String(segment.endTime || '').slice(0, 5);
  3486. const dateType =
  3487. segment.dateType || this.getAdjustDateType(row.adjustType);
  3488. const dateText = segment.calendarDate
  3489. ? `${segment.calendarDate} `
  3490. : '';
  3491. const typeText = this.getLabel(dateTypeOptions, dateType);
  3492. return `${dateText}${startTime}-${endTime} ${typeText}`.trim();
  3493. })
  3494. .join('、');
  3495. },
  3496. getAdjustApplicantName(row = {}) {
  3497. return (
  3498. row.applyUserName ||
  3499. row.applicantName ||
  3500. row.createUserName ||
  3501. row.userName ||
  3502. row.applyUserId ||
  3503. '-'
  3504. );
  3505. },
  3506. formatApproveNodes(approveNode) {
  3507. if (!approveNode) {
  3508. return [];
  3509. }
  3510. let nodes = approveNode;
  3511. if (typeof approveNode === 'string') {
  3512. try {
  3513. nodes = JSON.parse(approveNode);
  3514. } catch (e) {
  3515. return [
  3516. {
  3517. statusText: '审批记录',
  3518. approveOpinion: approveNode,
  3519. approveTime: '',
  3520. approveUserId: ''
  3521. }
  3522. ];
  3523. }
  3524. }
  3525. const list = Array.isArray(nodes) ? nodes : [nodes];
  3526. return list
  3527. .filter((item) => item && typeof item === 'object')
  3528. .map((item) => {
  3529. const status = Number(item.applyStatus ?? item.approveStatus);
  3530. return {
  3531. statusText:
  3532. this.getLabel(approvalStatusOptions, status) ||
  3533. item.statusText ||
  3534. '审批记录',
  3535. approveOpinion:
  3536. item.approveOpinion || item.opinion || item.remark || '',
  3537. approveTime: String(item.approveTime || item.createTime || '')
  3538. .replace('T', ' ')
  3539. .slice(0, 19),
  3540. approveUserId: item.approveUserId || item.userId || ''
  3541. };
  3542. });
  3543. },
  3544. async openDayDrawer(day) {
  3545. if (!day.date || day.hiddenByFilter) {
  3546. return;
  3547. }
  3548. if (day.isDisabledCalendar) {
  3549. this.$message.warning('当前类型日历已禁用,不可编辑');
  3550. return;
  3551. }
  3552. await this.loadRemoteViewData();
  3553. const details = this.getViewDetails(day.date);
  3554. const relatedPlans = this.getDetailRelatedPlans(details);
  3555. this.currentDay = {
  3556. ...day,
  3557. details,
  3558. relatedPlans,
  3559. planCount: this.getDetailPlanCount(details)
  3560. };
  3561. this.dayDrawerVisible = true;
  3562. },
  3563. openAdjustDialog(day = {}) {
  3564. this.adjustForm = this.getDefaultAdjustForm(day);
  3565. const calendar = this.enabledCalendars.find(
  3566. (item) => item.calendarType === this.viewQuery.calendarType
  3567. );
  3568. if (calendar) {
  3569. this.adjustForm.calendarId = calendar.id;
  3570. }
  3571. this.adjustDialogVisible = true;
  3572. this.$nextTick(() => {
  3573. this.$refs.adjustForm?.clearValidate?.();
  3574. });
  3575. },
  3576. submitAdjust() {
  3577. this.$refs.adjustForm.validate((valid) => {
  3578. if (!valid) {
  3579. return;
  3580. }
  3581. if (!this.adjustForm.startTime || !this.adjustForm.endTime) {
  3582. this.$message.error('请选择调整时段');
  3583. return;
  3584. }
  3585. const calendar = this.calendars.find(
  3586. (item) => item.id === this.adjustForm.calendarId
  3587. );
  3588. if (!calendar) {
  3589. this.$message.error('请选择关联日历');
  3590. return;
  3591. }
  3592. const saveApply = async () => {
  3593. const originalDetails = this.details.filter(
  3594. (item) =>
  3595. item.calendarId === calendar.id &&
  3596. item.calendarDate === this.adjustForm.adjustDate
  3597. );
  3598. const newSegments = this.buildAdjustSegments();
  3599. const adjustRow = {
  3600. id: Date.now(),
  3601. applyNo: createCode('ADJ'),
  3602. calendarId: calendar.id,
  3603. calendarName: calendar.calendarName,
  3604. adjustType: this.adjustForm.adjustType,
  3605. adjustDate: this.adjustForm.adjustDate,
  3606. oldContent: this.getRangeText(originalDetails),
  3607. originalDetails: clone(originalDetails),
  3608. newContent: this.stringifySegments(newSegments),
  3609. newContentText: `${this.adjustForm.startTime}-${
  3610. this.adjustForm.endTime
  3611. } ${this.getLabel(
  3612. adjustTypeOptions,
  3613. this.adjustForm.adjustType
  3614. )}`,
  3615. effectiveTime: this.adjustForm.effectiveTime,
  3616. expireTime: this.adjustForm.expireTime,
  3617. applyReason: this.adjustForm.applyReason,
  3618. applyStatus: 0,
  3619. isConflict: 0,
  3620. applyUserName: '当前用户',
  3621. applyTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  3622. approveNode: '',
  3623. canReactivate: true
  3624. };
  3625. try {
  3626. await applyCalendarAdjust({
  3627. calendarId: calendar.id,
  3628. adjustType: this.adjustForm.adjustType,
  3629. adjustDate: this.adjustForm.adjustDate,
  3630. oldContent: adjustRow.oldContent,
  3631. newContent: adjustRow.newContent,
  3632. effectiveTime: this.adjustForm.effectiveTime,
  3633. expireTime: this.adjustForm.expireTime,
  3634. applyReason: this.adjustForm.applyReason
  3635. });
  3636. await this.loadRemoteAdjustData();
  3637. this.invalidateConflictCache();
  3638. this.reloadAdjustTable(1);
  3639. this.adjustDialogVisible = false;
  3640. this.$message.success('已提交审批');
  3641. return;
  3642. } catch (e) {
  3643. this.$message.error(e?.message || '提交审批失败,请检查接口返回');
  3644. }
  3645. };
  3646. saveApply();
  3647. });
  3648. },
  3649. openApproveDialog(row, status) {
  3650. if (row.applyStatus === 3) {
  3651. this.$message.warning('已失效单据仅可查询追溯,无法重新生效');
  3652. return;
  3653. }
  3654. this.approveForm = {
  3655. row,
  3656. status,
  3657. opinion: status === 1 ? '审批通过' : ''
  3658. };
  3659. this.approveDialogVisible = true;
  3660. },
  3661. async confirmApproveAdjust() {
  3662. if (this.approveForm.status === 2 && !this.approveForm.opinion) {
  3663. this.$message.error('请输入驳回原因');
  3664. return;
  3665. }
  3666. await this.approveAdjust(
  3667. this.approveForm.row,
  3668. this.approveForm.status,
  3669. this.approveForm.opinion
  3670. );
  3671. this.approveDialogVisible = false;
  3672. },
  3673. async approveAdjust(row, status, opinion = '') {
  3674. try {
  3675. await approveCalendarAdjust({
  3676. id: row.id,
  3677. applyStatus: status,
  3678. approveOpinion: opinion
  3679. });
  3680. await this.loadRemoteAdjustData();
  3681. await this.loadRemoteViewData(true);
  3682. this.invalidateConflictCache();
  3683. this.reloadAdjustTable();
  3684. if (status === 1) {
  3685. this.reloadPlanTable(1);
  3686. }
  3687. this.$message.success(status === 1 ? '审批通过并已生效' : '已驳回');
  3688. return;
  3689. } catch (e) {
  3690. this.$message.error(e?.message || '审批失败,请检查接口返回');
  3691. }
  3692. },
  3693. getAdjustDateType(adjustType) {
  3694. return (
  3695. {
  3696. 1: 5,
  3697. 2: 2,
  3698. 3: 4,
  3699. 4: 5
  3700. }[adjustType] || 5
  3701. );
  3702. },
  3703. expireAdjustments() {
  3704. // 已停用:临时调整失效由后端任务/接口处理。
  3705. },
  3706. async checkSingleDay(day) {
  3707. if (!day.date || !day.details.length) {
  3708. this.$message.success('当前日期未发现冲突');
  3709. return;
  3710. }
  3711. try {
  3712. const results = await Promise.all(
  3713. day.details.map((detail) =>
  3714. checkCalendarConflict({
  3715. calendarType:
  3716. detail.calendarType || this.viewQuery.calendarType,
  3717. calendarDate: day.date,
  3718. startTime: detail.startTime,
  3719. endTime: detail.endTime,
  3720. dateType: detail.dateType,
  3721. scheduleStatus: detail.scheduleStatus,
  3722. excludeDetailId: detail.id
  3723. })
  3724. )
  3725. );
  3726. const conflicts = results
  3727. .map((item) => item?.conflictDetail || [])
  3728. .flat();
  3729. if (conflicts.length) {
  3730. this.$message.warning(`发现 ${conflicts.length} 条冲突`);
  3731. } else {
  3732. this.$message.success('当前日期未发现冲突');
  3733. }
  3734. } catch (e) {
  3735. this.$message.error(e?.message || '冲突检测失败,请检查接口返回');
  3736. }
  3737. },
  3738. async toggleScheduleStatus(status) {
  3739. if (!this.currentDay.date || this.currentDay.isDisabledCalendar) {
  3740. this.$message.warning('当前日历不可编辑');
  3741. return;
  3742. }
  3743. const calendar = this.enabledCalendars.find(
  3744. (item) => item.calendarType === this.viewQuery.calendarType
  3745. );
  3746. if (!calendar) {
  3747. this.$message.warning('当前类型日历已禁用');
  3748. return;
  3749. }
  3750. const currentDetails = this.getViewDetails(this.currentDay.date);
  3751. const nextDetails = currentDetails.map((detail) => ({
  3752. ...detail,
  3753. calendarId: calendar.id,
  3754. calendarDate: this.currentDay.date,
  3755. scheduleStatus: status
  3756. }));
  3757. try {
  3758. await Promise.all(
  3759. nextDetails.map((nextDetail) =>
  3760. saveCalendarDetail({
  3761. id: nextDetail.id,
  3762. calendarId: nextDetail.calendarId,
  3763. calendarDate: nextDetail.calendarDate,
  3764. startTime: nextDetail.startTime,
  3765. endTime: nextDetail.endTime,
  3766. dateType: nextDetail.dateType || 1,
  3767. scheduleStatus: nextDetail.scheduleStatus,
  3768. remark: nextDetail.remark,
  3769. forceSave: true
  3770. })
  3771. )
  3772. );
  3773. await this.loadRemoteViewData(true);
  3774. const details = this.getViewDetails(this.currentDay.date);
  3775. const relatedPlans = this.getDetailRelatedPlans(details);
  3776. this.currentDay = {
  3777. ...this.currentDay,
  3778. details,
  3779. relatedPlans,
  3780. planCount: this.getDetailPlanCount(details),
  3781. scheduleStatus: !!status
  3782. };
  3783. this.reloadPlanTable(1);
  3784. this.invalidateConflictCache();
  3785. this.$message.success(status ? '已完成排班并回写状态' : '已取消排班');
  3786. return;
  3787. } catch (e) {
  3788. this.$message.error(e?.message || '排班状态回写失败,请检查接口返回');
  3789. }
  3790. },
  3791. getConflictDataKey() {
  3792. return [
  3793. this.viewQuery.year || '',
  3794. this.getConflictCheckTypes().join(',')
  3795. ].join('|');
  3796. },
  3797. getConflictCheckTypes() {
  3798. return this.calendarTypeOptions
  3799. .map((item) => Number(item.value))
  3800. .filter((type) => [1, 2, 3].includes(type));
  3801. },
  3802. invalidateConflictCache() {
  3803. this.conflictDataKey = '';
  3804. },
  3805. async runGlobalConflictCheck(showMessage = true, force = showMessage) {
  3806. const dataKey = this.getConflictDataKey();
  3807. if (!force && this.conflictDataKey === dataKey) {
  3808. this.reloadConflictTable(1);
  3809. return;
  3810. }
  3811. if (this.conflictCheckPromise) {
  3812. await this.conflictCheckPromise;
  3813. return;
  3814. }
  3815. try {
  3816. const conflictTypes = this.getConflictCheckTypes();
  3817. this.conflictCheckPromise = Promise.all(
  3818. conflictTypes.map((calendarType) =>
  3819. checkAllCalendarConflict({
  3820. year: this.viewQuery.year,
  3821. calendarType
  3822. })
  3823. )
  3824. );
  3825. const list = await this.conflictCheckPromise;
  3826. this.conflictList = this.uniqueConflicts(
  3827. list.flatMap((data) => this.normalizeRemoteConflicts(data))
  3828. );
  3829. this.conflictDataKey = dataKey;
  3830. this.reloadConflictTable(1);
  3831. if (showMessage) {
  3832. this.$message[this.conflictList.length ? 'warning' : 'success'](
  3833. this.conflictList.length
  3834. ? `检测完成,发现 ${this.conflictList.length} 条冲突`
  3835. : '检测完成,未发现冲突'
  3836. );
  3837. }
  3838. return;
  3839. } catch (e) {
  3840. this.conflictList = [];
  3841. this.conflictDataKey = '';
  3842. if (showMessage) {
  3843. this.$message.error(e?.message || '冲突检测失败,请检查接口返回');
  3844. }
  3845. } finally {
  3846. this.conflictCheckPromise = null;
  3847. }
  3848. this.reloadConflictTable(1);
  3849. },
  3850. checkConflict({
  3851. calendarType,
  3852. calendarDate,
  3853. startTime,
  3854. endTime,
  3855. dateType = 1,
  3856. scheduleStatus = 1,
  3857. sourceId
  3858. }) {
  3859. const sameDay = this.details.filter((item) => {
  3860. const calendar = this.calendars.find(
  3861. (calendarItem) => calendarItem.id === item.calendarId
  3862. );
  3863. return (
  3864. item.id !== sourceId &&
  3865. item.calendarDate === calendarDate &&
  3866. calendar?.status === 1 &&
  3867. isOverlap(startTime, endTime, item.startTime, item.endTime)
  3868. );
  3869. });
  3870. const conflicts = [];
  3871. sameDay.forEach((item) => {
  3872. const targetCalendar = this.calendars.find(
  3873. (calendarItem) => calendarItem.id === item.calendarId
  3874. );
  3875. const targetType = targetCalendar?.calendarType;
  3876. const source = {
  3877. calendarType,
  3878. dateType,
  3879. scheduleStatus
  3880. };
  3881. const target = {
  3882. calendarType: targetType,
  3883. dateType: item.dateType,
  3884. scheduleStatus: item.scheduleStatus
  3885. };
  3886. const timeRange = `${Math.max(
  3887. toMinute(startTime),
  3888. toMinute(item.startTime)
  3889. )}-${Math.min(toMinute(endTime), toMinute(item.endTime))}`;
  3890. const readableRange = `${startTime}-${endTime}`;
  3891. if (
  3892. [source.calendarType, target.calendarType].includes(1) &&
  3893. [source.calendarType, target.calendarType].includes(2) &&
  3894. [source, target].some(
  3895. (segment) => segment.calendarType === 2 && segment.dateType === 4
  3896. )
  3897. ) {
  3898. conflicts.push({
  3899. id: `${calendarDate}-${timeRange}-1-2`,
  3900. calendarDate,
  3901. timeRange: readableRange,
  3902. scene: '生产日历 VS 设备维护日历',
  3903. level: '高',
  3904. message: '当前生产作业时段设备停机,无法排产'
  3905. });
  3906. }
  3907. if (
  3908. [source.calendarType, target.calendarType].includes(1) &&
  3909. [source.calendarType, target.calendarType].includes(3) &&
  3910. [source, target].some(
  3911. (segment) =>
  3912. segment.calendarType === 3 &&
  3913. (segment.dateType === 2 ||
  3914. segment.dateType === 3 ||
  3915. segment.scheduleStatus === 0)
  3916. )
  3917. ) {
  3918. conflicts.push({
  3919. id: `${calendarDate}-${timeRange}-1-3`,
  3920. calendarDate,
  3921. timeRange: readableRange,
  3922. scene: '生产日历 VS 人员排班日历',
  3923. level: '高',
  3924. message: '当前生产时段无在岗人员,人力缺失'
  3925. });
  3926. }
  3927. if (
  3928. [source.calendarType, target.calendarType].includes(2) &&
  3929. [source.calendarType, target.calendarType].includes(3) &&
  3930. [source, target].some(
  3931. (segment) =>
  3932. segment.calendarType === 3 &&
  3933. (segment.dateType === 2 ||
  3934. segment.dateType === 3 ||
  3935. segment.scheduleStatus === 0)
  3936. )
  3937. ) {
  3938. conflicts.push({
  3939. id: `${calendarDate}-${timeRange}-2-3`,
  3940. calendarDate,
  3941. timeRange: readableRange,
  3942. scene: '设备维护日历 VS 人员排班日历',
  3943. level: '中',
  3944. message: '设备检修时段维保人员缺失'
  3945. });
  3946. }
  3947. });
  3948. if (calendarType === 1) {
  3949. const hasStaff = sameDay.some((item) => {
  3950. const targetCalendar = this.calendars.find(
  3951. (calendarItem) => calendarItem.id === item.calendarId
  3952. );
  3953. return (
  3954. targetCalendar?.calendarType === 3 &&
  3955. item.scheduleStatus === 1 &&
  3956. ![2, 3].includes(item.dateType)
  3957. );
  3958. });
  3959. if (!hasStaff) {
  3960. conflicts.push({
  3961. id: `${calendarDate}-${startTime}-${endTime}-1-3-missing`,
  3962. calendarDate,
  3963. timeRange: `${startTime}-${endTime}`,
  3964. scene: '生产日历 VS 人员排班日历',
  3965. level: '高',
  3966. message: '当前生产时段无在岗人员,人力缺失'
  3967. });
  3968. }
  3969. }
  3970. if (calendarType === 2) {
  3971. const hasMaintainer = sameDay.some((item) => {
  3972. const targetCalendar = this.calendars.find(
  3973. (calendarItem) => calendarItem.id === item.calendarId
  3974. );
  3975. return (
  3976. targetCalendar?.calendarType === 3 &&
  3977. item.scheduleStatus === 1 &&
  3978. ![2, 3].includes(item.dateType)
  3979. );
  3980. });
  3981. if (!hasMaintainer) {
  3982. conflicts.push({
  3983. id: `${calendarDate}-${startTime}-${endTime}-2-3-missing`,
  3984. calendarDate,
  3985. timeRange: `${startTime}-${endTime}`,
  3986. scene: '设备维护日历 VS 人员排班日历',
  3987. level: '中',
  3988. message: '设备检修时段维保人员缺失'
  3989. });
  3990. }
  3991. }
  3992. return conflicts;
  3993. },
  3994. uniqueConflicts(conflicts) {
  3995. const map = {};
  3996. conflicts.forEach((item) => {
  3997. map[item.id] = item;
  3998. });
  3999. return Object.values(map);
  4000. },
  4001. async locateConflict(row) {
  4002. this.activeTab = 'view';
  4003. this.viewQuery.viewType = 'day';
  4004. this.viewMonth = dayjs(row.calendarDate).format('YYYY-MM');
  4005. this.viewQuery.year = Number(dayjs(row.calendarDate).format('YYYY'));
  4006. this.viewQuery.month = Number(dayjs(row.calendarDate).format('M'));
  4007. this.viewQuery.date = row.calendarDate;
  4008. this.viewQuery.statusFilter = 'conflict';
  4009. await this.refreshRemoteView();
  4010. },
  4011. handleTabChange() {
  4012. if (this.activeTab === 'base') {
  4013. this.reloadBaseTable(1);
  4014. }
  4015. if (this.activeTab === 'view') {
  4016. this.refreshRemoteView();
  4017. }
  4018. if (this.activeTab === 'stat') {
  4019. this.refreshStatView();
  4020. }
  4021. if (this.activeTab === 'conflict') {
  4022. this.runGlobalConflictCheck(false);
  4023. }
  4024. if (this.activeTab === 'adjust') {
  4025. this.reloadAdjustTable(1);
  4026. }
  4027. if (this.activeTab === 'plan') {
  4028. this.reloadPlanTable(1);
  4029. }
  4030. },
  4031. getPlanDataKey() {
  4032. const calendar = this.getCurrentViewCalendar();
  4033. return [
  4034. this.getRemoteCalendarId(calendar) || '',
  4035. this.viewQuery.year || '',
  4036. this.viewQuery.month || ''
  4037. ].join('|');
  4038. },
  4039. async ensurePlanRefreshData(force = false) {
  4040. const calendar = this.getCurrentViewCalendar();
  4041. const calendarId = this.getRemoteCalendarId(calendar);
  4042. if (!calendarId) {
  4043. this.plans = [];
  4044. this.planDataKey = '';
  4045. return;
  4046. }
  4047. const dataKey = this.getPlanDataKey();
  4048. if (!force && this.planDataKey === dataKey && this.plans.length) {
  4049. return;
  4050. }
  4051. if (!force && this.planDataPromise) {
  4052. await this.planDataPromise;
  4053. return;
  4054. }
  4055. try {
  4056. this.planDataPromise = refreshCalendarPlan({
  4057. calendarId,
  4058. startDate: `${this.viewQuery.year}-${String(
  4059. this.viewQuery.month
  4060. ).padStart(2, '0')}-01`,
  4061. endDate: dayjs(
  4062. `${this.viewQuery.year}-${String(this.viewQuery.month).padStart(
  4063. 2,
  4064. '0'
  4065. )}-01`
  4066. )
  4067. .endOf('month')
  4068. .format('YYYY-MM-DD')
  4069. });
  4070. const data = await this.planDataPromise;
  4071. this.plans = this.normalizeRemotePlans(data);
  4072. this.planDataKey = dataKey;
  4073. } catch (e) {
  4074. this.plans = [];
  4075. this.planDataKey = '';
  4076. } finally {
  4077. this.planDataPromise = null;
  4078. }
  4079. },
  4080. async refreshPlans() {
  4081. try {
  4082. await this.ensurePlanRefreshData(true);
  4083. await this.loadRemoteViewData(true);
  4084. this.reloadPlanTable(1);
  4085. this.$message.success(`已刷新受影响计划,共 ${this.plans.length} 条`);
  4086. } catch (e) {
  4087. this.plans = [];
  4088. this.reloadPlanTable(1);
  4089. }
  4090. },
  4091. reschedulePlans() {
  4092. this.$message.warning('批量重排需要后端返回可重排计划后执行');
  4093. this.reloadPlanTable(1);
  4094. },
  4095. async jumpPlanToCalendar(row) {
  4096. const calendar = this.calendars.find(
  4097. (item) => item.id === row.calendarId
  4098. );
  4099. this.activeTab = 'view';
  4100. this.viewQuery.calendarType = calendar?.calendarType || 1;
  4101. this.viewQuery.viewType = 'day';
  4102. this.viewQuery.date = row.calendarDate;
  4103. this.viewMonth = dayjs(row.calendarDate).format('YYYY-MM');
  4104. await this.changeViewMonth(this.viewMonth);
  4105. this.viewQuery.date = row.calendarDate;
  4106. this.$nextTick(async () => {
  4107. await this.loadRemoteViewData(true);
  4108. const details = this.getViewDetails(row.calendarDate);
  4109. const relatedPlans = this.getDetailRelatedPlans(details);
  4110. const day = {
  4111. key: row.calendarDate,
  4112. date: row.calendarDate,
  4113. dayText: dayjs(row.calendarDate).format('D'),
  4114. details,
  4115. relatedPlans,
  4116. planCount: this.getDetailPlanCount(details),
  4117. scheduleStatus: details.some((item) => item.scheduleStatus === 1),
  4118. isConflict: details.some((item) => item.isConflict === 1),
  4119. isTempAdjust: details.some((item) => item.isTempAdjust === 1),
  4120. isMaintenance: details.some((item) => item.dateType === 4),
  4121. isRest: this.isRestDay(row.calendarDate, details),
  4122. isDisabledCalendar: !this.hasEnabledCalendarForView(),
  4123. conflictText: this.getConflictText(row.calendarDate)
  4124. };
  4125. this.openDayDrawer(day);
  4126. });
  4127. },
  4128. exportCalendar() {
  4129. const rows = this.filteredCalendars.map((item) => ({
  4130. calendarCode: item.calendarCode,
  4131. calendarName: item.calendarName,
  4132. calendarType: this.getLabel(calendarTypeOptions, item.calendarType),
  4133. applyYear: item.applyYear.join(','),
  4134. status: item.status ? '启用' : '禁用'
  4135. }));
  4136. this.downloadJson(
  4137. rows,
  4138. `factory-calendar-${dayjs().format('YYYYMMDDHHmmss')}.json`
  4139. );
  4140. this.$message.success(`导出成功,共 ${rows.length} 条`);
  4141. },
  4142. openAdjustDetail(row) {
  4143. this.adjustDetail = clone(row);
  4144. this.adjustDetailVisible = true;
  4145. },
  4146. exportAdjustRecord() {
  4147. if (!this.adjustDetail.id) {
  4148. return;
  4149. }
  4150. this.downloadJson(
  4151. this.adjustDetail,
  4152. `calendar-adjust-${this.adjustDetail.applyNo}.json`
  4153. );
  4154. this.$message.success('追溯记录已导出');
  4155. },
  4156. downloadJson(data, filename) {
  4157. const blob = new Blob([JSON.stringify(data, null, 2)], {
  4158. type: 'application/json;charset=utf-8'
  4159. });
  4160. const url = URL.createObjectURL(blob);
  4161. const link = document.createElement('a');
  4162. link.href = url;
  4163. link.download = filename;
  4164. link.click();
  4165. URL.revokeObjectURL(url);
  4166. },
  4167. getCalendarCount(type) {
  4168. return this.calendars.filter((item) => item.calendarType === type)
  4169. .length;
  4170. },
  4171. getStatPercent(value) {
  4172. const total = Math.max(...this.monthStats.map((item) => item.value), 1);
  4173. return Math.round((value / total) * 100);
  4174. },
  4175. calendarTypeTag(type) {
  4176. return {
  4177. 1: '',
  4178. 2: 'warning',
  4179. 3: 'success'
  4180. }[type];
  4181. },
  4182. approvalStatusTag(status) {
  4183. return {
  4184. 0: 'warning',
  4185. 1: 'success',
  4186. 2: 'danger',
  4187. 3: 'info'
  4188. }[status];
  4189. },
  4190. getLabel(options, value) {
  4191. return options.find((item) => item.value === value)?.label || '';
  4192. }
  4193. }
  4194. };
  4195. </script>
  4196. <style lang="scss">
  4197. @import './components/factoryCalendar.scss';
  4198. </style>