| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799 |
- <template>
- <el-dialog v-model="visible" :title="isView ? '查看' : isCollect ? '领取' : '归还'" width="75%" :close-on-click-modal="false" @close="onCancel">
- <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
- <el-tab-pane label="借用单信息" name="first">
- <el-form :model="form" label-width="110px" label-position="top" :rules="rules" ref="formRef">
- <el-row :gutter="16">
- <el-col :span="8">
- <el-form-item label="借用单编号" prop="application_no">
- <el-input v-model="form.application_no" placeholder="自动生成" disabled />
- </el-form-item>
- </el-col>
- <el-col :span="8">
- <el-form-item label="借用人类型" prop="borrower_type">
- <el-select v-model="form.borrower_type" :placeholder="isView?'':'请选择借用人角色'" :disabled="true">
- <el-option label="管理员用户" :value=0 />
- <el-option label="应用用户" :value=1 />
- <el-option label="外部用户" :value=2 />
- </el-select>
- </el-form-item>
- </el-col>
- <el-col :span="8" >
- <!-- <el-form-item label="借用人" prop="external_borrower_name" v-if="form.borrower_type !== 2">
- <el-input v-model="form.borrower_info.name" placeholder="请输入借用人" :disabled="true" />
- </el-form-item> -->
- <el-form-item label="借用人" prop="admin_borrower" v-if="form.borrower_type == 0">
-
- <el-select v-model="form.admin_borrower" :placeholder="isView?'':'请选择借用人'" :disabled="true" >
- <el-option :label="adminList.name" :value="adminList.id" />
- </el-select>
- </el-form-item>
- <el-form-item label="借用人" prop="app_user_borrower" v-if="form.borrower_type == 1">
- <el-select v-model="form.app_user_borrower.id" :placeholder="isView?'':'请选择借用人'" :disabled="true" >
- <el-option v-for="item in allUserList" :key="item.id" :label="item.name" :value="item.id" />
- </el-select>
- </el-form-item>
- <el-form-item label="借用人" prop="external_borrower_name" v-if="form.borrower_type == 2">
- <el-input v-model="form.external_borrower_name" :placeholder="isView?'':'请输入借用人'" :disabled="true" />
- </el-form-item>
- </el-col>
- <el-col :span="8" v-if="form.borrower_type !== 2">
- <el-form-item label="学号/工号" prop="user_code" >
- <!-- {{ form.borrower_info.user_code }} -->
- <el-input v-model="form.app_user_borrower.user_code" :placeholder="isView?'':'请输入学号/工号'" :disabled="true"/>
- </el-form-item>
- </el-col>
- <el-col :span="8">
- <el-form-item label="联系电话" v-if="form.borrower_type !== 2">
- <el-input v-model="form.app_user_borrower.mobile" :placeholder="isView?'':'请输入联系电话'" :disabled="true" />
- </el-form-item>
- <el-form-item label="联系电话" v-if="form.borrower_type == 2">
- <el-input v-model="form.external_borrower_phone" :placeholder="isView?'':'请输入联系电话'" :disabled="true" />
- </el-form-item>
- </el-col>
- <el-col :span="8">
- <el-form-item label="借用部门" prop="borrower_dept">
- <el-input v-model="form.borrower_dept" placeholder="请输入借用部门" :disabled="true" />
- </el-form-item>
- </el-col>
- <el-col :span="8">
- <el-form-item label="预计归还时间" prop="expected_end_time">
- <el-date-picker v-model="form.expected_end_time" type="date"
- format="YYYY-MM-DD"
- value-format="YYYY-MM-DD"
- :disabledDate="disabledDate" placeholder="请选择预计归还时间" style="width: 100%" :disabled="true"/>
- </el-form-item>
- </el-col>
- <el-col :span="4">
- <el-form-item label="个人/团队" prop="team_type" >
- <el-select v-model="form.team_type" placeholder="请选择" :disabled="true">
- <el-option label="个人" :value="0" />
- <el-option label="团队" :value="1" />
- </el-select>
- </el-form-item>
- </el-col>
- <el-col :span="4" v-show="form.team_type===1">
- <el-form-item label="团队人数" prop="team_members_count">
- <el-input v-model="form.team_members_count" :placeholder="isView?'':'请输入'" :disabled="true"/>
- </el-form-item>
- </el-col>
- <el-col :span="16" v-show="form.team_type===1">
- <el-form-item label="团队其他人员名单" prop="team_members">
- <el-input v-model="form.team_members" :placeholder="isView?'':'请输入团队其他人员名单'" :disabled="true"/>
- </el-form-item>
- </el-col>
- <el-col :span="24">
- <el-form-item label="借用原因" prop="purpose">
- <el-input v-model="form.purpose" type="textarea" :placeholder="isView?'':'请输入借用原因'" :disabled="true" />
- </el-form-item>
- </el-col>
- <el-col :span="4">
- <!-- ||form.approver_info.name -->
- <el-form-item label="审批人" prop="applicant_remark_type">
- <el-input :model-value="displayApproverName" placeholder="-" :disabled="true" />
- </el-form-item>
- </el-col>
- <el-col :span="20">
- <el-form-item label="备注" prop="applicant_remark">
- <el-input v-model="form.applicant_remark" :placeholder="isView?'':'请输入备注'" :disabled="true"/>
- </el-form-item>
- </el-col>
- </el-row>
- <div style="margin: 16px 0 8px 0; font-weight: bold"> {{ isView ? '借用列表' : (isCollect ? '借用列表' : '归还列表') }}</div>
- <el-table :data="form.items.filter(item => item.device === null)" border style="width: 50%; margin-bottom: 12px">
- <el-table-column type="index" label="序号" width="60" />
- <el-table-column prop="device_category_name" label="设备分类" />
- <el-table-column :label="isView ? '数量' : (isCollect ? '借用数量' : '归还数量')">
- <template #default="{ row }">
- <el-input v-model="row.quantity" type="number" :min="1" prop="quantity" size="small" :disabled="true" />
- </template>
- </el-table-column>
- <el-table-column label="操作" width="80">
- <template #default="{ $index }">
- <el-button type="text" style="color: red" @click="removeItem($index)" :disabled="true">移除</el-button>
- </template>
- </el-table-column>
- </el-table>
- <el-button type="primary" @click="addItem" v-if="!isView" :disabled="true">选择设备分类</el-button>
- <div style="margin: 16px 0 8px 0; font-weight: bold">预借配件信息</div>
- <el-input v-model="form.accessories" :placeholder="isView?'':'请输入预借配件信息'" :disabled="true"/>
- <div style="margin: 16px 0 8px 0; font-weight: bold" >附件</div>
- <!-- <el-upload
- action="#"
- drag
- :list-type="'picture'"
- accept=".bmp,.gif,.jpeg,.jpg,.png,.webp,.svg"
- multiple
- :show-file-list="true"
- :file-list="attachmentFileList"
- :on-success="handleUploadSuccess"
- :on-error="handleUploadError"
- :disabled="true"
- >
- <i class="el-icon-upload"></i>
- <div class="el-upload__text">将文件拖到此处,或 <em>点击上传</em></div>
- </el-upload> -->
- <el-upload
- :disabled="true"
- action="#"
- list-type="picture-card"
- :on-preview="handlePictureCardPreview"
- :on-remove="handleRemoves"
- :file-list="attachmentFileList"
- >
- <el-icon><Plus /></el-icon>
- </el-upload>
- <div v-if="isView && form.latest_renewal" style="margin-top: 8px;">
- <div style="font-weight: bold; margin-bottom: 8px">续借信息</div>
- <el-row :gutter="16">
- <el-col :span="4">
- <el-form-item label="续借天数">
- <el-input :model-value="form.latest_renewal?.renewal_days" :disabled="true">
- <template #append>天</template>
- </el-input>
- </el-form-item>
- </el-col>
- <el-col :span="21">
- <el-form-item label="续借理由">
- <el-input :model-value="form.latest_renewal?.renewal_reason" type="textarea" :disabled="true" />
- </el-form-item>
- </el-col>
- </el-row>
- </div>
- </el-form>
-
- <!-- 审批信息流程展示 -->
- <!-- <div v-if="isView" style="margin-top: 24px; padding: 0 12px">
- <div style="font-weight: bold; margin-bottom: 12px">审批流程进度</div>
- <el-steps :active="activeStep" align-center>
- <el-step
- title="创建申请"
- :description="`创建时间:${ timeline.create }`"
- icon="CircleCheck"
- :status="activeStep >= 1 ? 'finish' : 'wait'"
- />
- <el-step
- title="待审批"
- description="待审批人审批"
- icon="CircleCheck"
- :status="activeStep >= 2 ? 'finish' : 'wait'"
- />
- <el-step
- title="审批通过"
- :description="`审批人:${timeline.approver},时间:${timeline.approve}`"
- icon="CircleCheck"
- :status="activeStep >= 3 ? 'finish' : 'wait'"
- />
- <el-step
- title="流程完成"
- description="流程已结束"
- icon="CircleCheck"
- :status="activeStep >= 4 ? 'finish' : 'wait'"
- />
- </el-steps>
- </div> -->
- <div v-if="isView" style="margin-top: 24px; padding: 0 12px">
- <div style="font-weight: bold; margin-bottom: 12px">审批流程进度</div>
- <el-steps :active="steps.length" align-center>
- <el-step
- v-for="(step, index) in steps"
- :key="index"
- :title="step.title"
- :description="step.description"
- icon="CircleCheck"
- :status="step.status"
- />
- </el-steps>
- </div>
- </el-tab-pane>
- <el-tab-pane v-if="isCollect && !shouldHideDeviceList" label="设备清单" name="second">
- <el-form :model="form" label-width="110px">
- <el-row :gutter="16">
- <el-col :span="24">
- <div style="margin: 8px 0">
- <textarea
- ref="searchInputRef"
- v-model="searchText"
- class="device-code-input"
- placeholder="设备编号(支持扫码枪/RFID批量录入)"
- :disabled="loading"
- autocomplete="off"
- rows="1"
- style="width: 300px; vertical-align: top;"
- @input="handleDeviceInput"
- @keydown="handleRFIDKeydown"
- @blur="handleDeviceBlur"
- @keydown.enter.prevent="handleDeviceEnter"
- ></textarea>
- <el-button type="primary" style="margin-left: 16px" @click="handleAdd">手动借用</el-button>
- </div>
- <el-table :data="deviceList" border style="width: 100%">
- <el-table-column type="index" label="序号" width="60" align="center" />
- <el-table-column prop="device_code" label="设备编号" align="center" />
- <el-table-column prop="device_type" label="设备分类" align="center" />
- <el-table-column prop="device_name" label="设备名称" align="center" />
- <el-table-column prop="borrow_count" label="借用数量" align="center" width="150">
- <template #default="{ row }">
- <el-input-number v-model="row.borrow_count" :disabled="isView" :min="1" :max="row.available_quantity" size="small" />
- </template>
- </el-table-column>
- <el-table-column prop="brand" label="品牌" align="center" />
- <el-table-column prop="device_specification" label="规格型号" align="center" />
- <!-- <el-table-column prop="warehouse" label="存放仓库" align="center" /> -->
- <el-table-column label="操作" width="80" align="center">
- <template #default="{ $index }">
- <el-button type="text" style="color: red" :disabled="isView" @click="handleRemove($index)">移除</el-button>
- </template>
- </el-table-column>
- </el-table>
- </el-col>
- </el-row>
- <el-row :gutter="16" style="margin-top: 16px">
- <el-col :span="24">
- <div style="font-weight: bold; margin-bottom: 8px">实借配件信息</div>
- <el-input v-if="isCollect" v-model="collectAccessories" :disabled="isView" type="textarea" :placeholder="isView?'':'请输入实借配件信息'" />
- <el-input v-else v-model="form.pre_borrow_accessories" :disabled="isView" type="textarea" :placeholder="isView?'':'请输入实借配件信息'" />
- </el-col>
- <el-col :span="24" style="margin-top: 16px">
- <div style="font-weight: bold; margin-bottom: 8px">备注</div>
- <el-input v-model="remark" type="textarea" :disabled="isView" :placeholder="isView?'':'请输入备注'" />
- </el-col>
- </el-row>
- <el-row :gutter="16" style="margin-top: 16px">
- <el-col :span="24">
- <div style="font-weight: bold; margin-bottom: 8px">异常记录 <span>{{
- abnormalList?.length ?
- abnormalList.reduce((sum, item) => sum + (Number(item?.condition) || 0), 0)
- : 0
- }}</span> 次</div>
- <el-table v-if="abnormalList.length > 0" :data="abnormalList" border style="width: 100%">
- <!-- <el-table-column type="index" label="序号" width="60" align="center" />
- <el-table-column prop="application_no" label="借用单编号" align="center" /> -->
- <el-table-column prop="operator_name" label="借用人" align="center" />
- <el-table-column prop="user_code" label="学号" align="center" />
- <el-table-column prop="emergency_phone" label="借用人电话" align="center" />
- <!-- <el-table-column prop="time" label="发生时间" align="center" /> -->
- <el-table-column prop="type" label="异常" align="center">
- <template #default="{ row }">
- {{ row.type }}
- </template>
- </el-table-column>
- <el-table-column prop="condition" label="数量" align="center">
- <template #default="{ row }">
- {{ row.condition }}
- </template>
- </el-table-column>
- </el-table>
- </el-col>
- </el-row>
- </el-form>
- </el-tab-pane>
- <el-tab-pane v-else-if="!shouldHideDeviceList" label="设备清单" name="third">
- <el-form :model="form" label-width="110px">
- <el-row :gutter="16">
- <el-col :span="24">
- <div style="margin: 8px 0" v-if="!isView" >
- <textarea
- ref="returnSearchInputRef"
- v-model="returnSearchText"
- class="device-code-input"
- placeholder="设备编号(支持扫码枪/RFID批量录入)"
- :disabled="loading"
- autocomplete="off"
- rows="1"
- style="width: 300px; vertical-align: top;"
- @input="handleReturnDeviceInput"
- @keydown="handleReturnRFIDKeydown"
- @blur="handleReturnDeviceBlur"
- @keydown.enter.prevent="handleReturnDeviceEnter"
- ></textarea>
- <el-button type="primary" style="margin-left: 16px" @click="handleAdd" :disabled="isView">手动归还</el-button>
- </div>
- <el-table :data="sortedReturnDeviceList" border style="width: 100%" >
- <!-- <el-table-column type="selection" width="55" align="center" />@selection-change="handleSelectionChange" -->
- <el-table-column type="index" label="序号" width="60" align="center" />
- <el-table-column prop="device_code" label="设备编号" align="center" />
- <!-- <el-table-column prop="device_type" label="设备分类" align="center" /> -->
- <el-table-column prop="device_name" label="设备名称" align="center" />
- <el-table-column label="已归还数量" width="110" align="center">
- <template #default="{ row }">
- {{ row.returned_quantity ?? 0 }}
- </template>
- </el-table-column>
- <el-table-column
- v-if="showUnreturnedReturnTableColumns"
- label="未归还可还"
- width="110"
- align="center"
- >
- <template #default="{ row }">
- {{ row.available_quantity ?? 0 }}
- </template>
- </el-table-column>
- <el-table-column
- v-if="showUnreturnedReturnTableColumns"
- prop="borrow_count"
- label="归还数量"
- align="center"
- width="150"
- >
- <template #default="{ row }">
- <el-input-number
- v-if="!isView && isReturnLinePendingReturn(row)"
- v-model="row.borrow_count"
- :min="0"
- :max="(row.available_quantity ?? 0) > 0 ? (row.available_quantity ?? 0) : 0"
- :disabled="(row.available_quantity ?? 0) <= 0"
- size="small"
- @change="() => clampReturnBorrowCount(row)"
- />
- <span
- v-else-if="isView && isReturnLinePendingReturn(row)"
- class="return-cell-text"
- >{{ row.borrow_count ?? 0 }}</span>
- <span v-else class="return-cell-placeholder">—</span>
- </template>
- </el-table-column>
- <el-table-column prop="brand" label="品牌" align="center" />
- <el-table-column prop="model" label="规格型号" align="center" />
- <!-- <el-table-column prop="warehouse" label="存放仓库" align="center" /> -->
- <el-table-column prop="status" label="状态" align="center">
- <template #default="{ row }">
- {{ row.return_status.label }}
- <!-- <el-tag v-if="!isView" :type="row.status === '已归还' ? 'success' : 'warning'">{{ row.status }}</el-tag>
- <el-tag v-else-if="['已领取', '已归还'].includes(form.status_label)">{{ form.status_label }}</el-tag> -->
- <!-- <span v-else>{{ form.status_label }}</span> -->
- </template>
- </el-table-column>
- <el-table-column prop="status" label="归还时间" align="center">
- <template #default="{ row }">
- {{ row.return_time ? dayjs(row.return_time).format('YYYY-MM-DD HH:mm:ss') : (row.return_status?.label === '已归还' ? dayjs().format('YYYY-MM-DD HH:mm:ss') : '') }}
- </template>
- </el-table-column>
- <el-table-column label="操作" width="120" align="center">
- <template #default="{ row }">
- <!-- && (!returnDeviceList[$index]?.condition || returnDeviceList[$index]?.photos?.length==0)&& row.problem_records?.length ==0 -->
- <el-button :disabled="isView" type="text" style="color: red;"
- v-if="!isView"
- @click="handleAbnormal(row)">异常操作</el-button>
- <el-button
-
- type="text"
- style="color: #409EFF;margin-left:0"
- @click="handleViewAbnormal(row)"
- v-if="row.problem_records?.length || row.condition || row.photos?.length"
- >查看异常</el-button>
- <!-- <el-button type="text" v-if="!isView" :disabled="isView" style="color: red" @click="handleReturnRemove($index)">移除</el-button> -->
- </template>
- </el-table-column>
- </el-table>
- </el-col>
- </el-row>
- <el-row :gutter="16" style="margin-top: 16px">
- <el-col :span="16">
- <div style="font-weight: bold; margin-bottom: 8px">实借配件信息</div>
- <el-input v-model="form.pre_borrow_accessories" :disabled="true" :placeholder="isView?'':'请输入实借配件信息'" />
- </el-col>
- <el-col :span="8">
- <div style="font-weight: bold; margin-bottom: 8px">当前状态</div>
- <el-input v-model="returnStatus" v-if="!isView" :disabled="true" placeholder="" style="width: 150px" />
- <el-input :value="form.status==7?'已归还':returnStatus" v-else :disabled="true" placeholder="" style="width: 150px" />
- <el-button type="primary" v-if="!isView" style="margin-left: 16px" @click="clickReturn"
- :disabled="returnStatus=='已归还'||isView">归还</el-button>
- </el-col>
- <el-col :span="24" style="margin-top: 16px">
- <div style="font-weight: bold; margin-bottom: 8px">备注</div>
- <el-input
- v-model="displayReturnRemark"
- type="textarea"
- :disabled="isView"
- :placeholder="isView?'':'请输入备注'"
- />
- </el-col>
- </el-row>
- <el-row :gutter="16" style="margin-top: 16px">
- <el-col :span="24">
- <div style="font-weight: bold; margin-bottom: 8px">异常记录 <span>{{
- returnAbnormalList?.length ?
- returnAbnormalList.reduce((sum, item) => sum + (Number(item?.condition) || 0), 0)
- : 0
- }}</span> 次</div>
- <el-table v-if="returnAbnormalList?.length > 0" :data="returnAbnormalList" border style="width: 100%">
- <!-- <el-table-column type="index" label="序号" width="60" align="center" />
- <el-table-column prop="application_no" label="借用单编号" align="center" /> -->
- <el-table-column prop="operator_name" label="借用人" align="center" />
- <el-table-column prop="user_code" label="学号" align="center" />
- <el-table-column prop="emergency_phone" label="借用人电话" align="center" />
- <!-- <el-table-column prop="time" label="发生时间" align="center" /> -->
- <el-table-column prop="type" label="异常" align="center">
- <template #default="{ row }">
- {{ row.type }}
- </template>
- </el-table-column>
- <el-table-column prop="condition" label="数量" align="center">
- <template #default="{ row }">
- {{ row.condition }}
- </template>
- </el-table-column>
- </el-table>
- </el-col>
- </el-row>
- </el-form>
- </el-tab-pane>
- </el-tabs>
- <template #footer>
- <el-button @click="onCancel">关闭</el-button>
- <el-button type="primary" @click="onSubmit" v-if="!isView"> {{ isCollect ? '提交' : '确认' }}</el-button>
- </template>
- </el-dialog>
- <SelectDeviceDialog
- v-model:visible="showSelectDeviceDialog"
- @confirm="onDeviceSelected"
- :device-ids="unreturnedDeviceIds"
- :return-mode="activeName === 'third'"
- :device-status-map="deviceStatusMap"
- :selected-device-codes="selectedDeviceCodes"
- :disabled-device-ids="disabledDeviceIds"
- />
- <SettlementDialog v-model:visible="showSettlementDialog" :settlement-data="settlementData" :modelValue="borrowForm" />
- <AbnormalDialog v-model:visible="showAbnormalDialog" @confirm="onAbnormalConfirm" />
- <ViewAbnormalDialog
- v-model:visible="showViewAbnormalDialog"
- :abnormal-data="currentAbnormalData"
- />
- <!-- 图片预览对话框 -->
- <el-dialog v-model="dialogVisible" title="图片预览" width="auto" center>
- <img width="100%" :src="dialogImageUrl" alt="Preview Image" style="max-width: 100%; max-height: 80vh;" />
- </el-dialog>
- </template>
- <script setup lang="ts">
- import { ref, watch, defineProps, defineEmits, onMounted, onBeforeUnmount, computed, nextTick } from 'vue';
- import SelectDeviceDialog from './SelectDeviceDialog/index.vue';
- import SettlementDialog from './SettlementDialog.vue';
- import AbnormalDialog from './AbnormalDialog/index.vue';
- import ViewAbnormalDialog from './ViewAbnormalDialog/index.vue';
- import dayjs from 'dayjs';
- import { ElMessage } from 'element-plus';
- import * as api from '../../api';
- import * as deviceApi from '../../../device/api';
- import { CollectEquipment, ReturnEquipment } from '../../api';
- import type { TabsPaneContext } from 'element-plus';
- import { getUserInfo } from '../../../login/api';
- import { request } from '/@/utils/service';
- // 禁止选择今天之前的日期
- const disabledDate = (time: Date) => {
- // 获取今天的开始时间(准确到日)
- const today = new Date()
- today.setHours(0, 0, 0, 0)
- // 返回true表示禁用,禁用今天之前的所有日期
- return time.getTime() < today.getTime()
- }
- /* 获取管理员列表 */
- const adminList = ref([]);
- async function getAdminList() {
- const res = await getUserInfo();
- adminList.value = res.data;
- console.log("adminList.value:::",adminList.value)
- }
- /* */
- /* 获取所有用户 */
- const allUserList = ref([]);
- let allUserLoaded = false;
- const allUserLoading = ref(false);
- async function getAllUserList() {
- if (allUserLoaded || allUserLoading.value) return;
- allUserLoading.value = true;
- try {
- // 分页拉取,避免一次性超大 limit 硬编码
- const pageSize = 100;
- let page = 1;
- const users: any[] = [];
- while (true) {
- const res = await api.GetAllUser({ page, limit: pageSize });
- const list = Array.isArray(res?.data) ? res.data : [];
- users.push(...list);
- if (list.length < pageSize) break;
- page += 1;
- }
- allUserList.value = users;
- // 设置默认选择(仅在当前未有选中时)
- if ((!form.value.app_user_borrower || !form.value.app_user_borrower.id) && allUserList.value.length > 0) {
- const first: any = allUserList.value[0];
- form.value.app_user_borrower = {
- id: first.id,
- name: first.name,
- user_code: first.user_code,
- mobile: first.mobile
- };
- }
- allUserLoaded = true;
- } catch (e) {
- /* empty */
- } finally {
- allUserLoading.value = false;
- }
- }
- interface ApiResponse {
- code: number;
- data?: any;
- message?: string;
- }
- // 用户最小结构用于表单回显
- interface AppUserBorrower {
- id: number | string;
- name?: string;
- user_code?: string;
- mobile?: string;
- }
- // 定义接口
- interface Device {
- id: string | number;
- category_name: string;
- name?: string;
- brand?: string;
- model?: string;
- warehouse: string;
- device_specification?: string;
- device_name?: string;
- }
- interface DeviceListItem {
- device_no: string | number;
- device_code?: string;
- device_type: string;
- device_name?: string; // 改为可选
- borrow_count: number;
- brand: string;
- model?: string; // 改为可选
- warehouse: string;
- status?: string;
- return_status?: {
- value?: number;
- label?: string;
- };
- return_time?: string;
- is_return?: boolean;
- condition?: string;
- photos?: Array<{
- filename: string;
- data: string;
- }>;
- device_specification?: string;
- /** 归还页签:可归还上限,来自 items.pending_quantity */
- available_quantity?: number;
- /** 截止当前已在库登记归还的数量,来自 items.returned_quantity */
- returned_quantity?: number;
- problem_records?: any[];
- damage_type?: number;
- /** 借用单明细行接口返回的更新时间,用于列表排序 */
- line_update_at?: string;
- /** 本页对行做了归还/数量等操作时的排序时间戳,与 line_update_at 取较大者参与排序 */
- sort_touched_at?: number;
- }
- interface FormItem {
- device: string | number;
- remark: string;
- quantity: number;
- location: string;
- device_name?: string;
- device_specification?: string;
- condition?: string;
- photos?: Array<{
- filename: string;
- data: string;
- }>;
- }
- interface FormData {
- application_no: string;
- emergency_contact: string;
- emergency_phone: string;
- app_user_borrower: AppUserBorrower | any;
- team_type: number;
- team_members_count: number;
- team_members: string;
- expected_start_time: string;
- expected_end_time: string;
- borrower_dept: string;
- purpose: string;
- applicant_remark_type: string;
- applicant_remark: string;
- items: FormItem[];
- accessory_info: string;
- borrow_type: number;
- return_location: string;
- status_label?: string;
- id?: number;
- records?: any[];
- borrower_info?: {
- user_code: string;
- };
- borrower_damage_count?: number;
- borrower_overdue_count?:number;
- accessories?: string;
- pre_borrow_accessories?:string;
- latest_renewal?: {
- renewal_days?: number | string;
- renewal_reason?: string;
- };
- problem_remarks?: string[];
- }
- interface AbnormalData {
- damage_type:number;
- condition: string;
- photos: Array<{
- filename: string;
- data: string;
- }>;
- }
- interface AbnormalRecord {
- application_no: string;
- operator_name: string;
- user_code: string;
- emergency_phone: string;
- type: '损坏' | '逾期';
- condition: number;
- create_time: string;
- }
- const now = dayjs().format('YYYY-MM-DD HH:mm:ss');
- const props = defineProps<{ visible: boolean; modelValue?: any }>();
- const isEdit = computed(() => props.modelValue?.mode === 'edit');
- const isView = computed(() => props.modelValue?.mode === 'view');
- const isAdd = computed(() => props.modelValue?.mode === 'add');
- const isCollect = computed(() => props.modelValue?.mode === 'collect');
- const isReturn = computed(() => props.modelValue?.mode === 'return');
- // 获取待审批人显示名称(与 buildSteps 中逻辑一致)
- // 待审批时显示当前环节审批人;审批完成后显示全部环节(老师、学院领导、管理员)的审批人
- function getPendingApproverDisplay(data: any): string {
- if (!data) return '';
- const adminInfo = data.admin_approver_info;
- const status = data.status;
- // 审批完成后:按实际审批顺序(老师→学院领导→管理员)显示
- // 优先用 approval_records 的审批顺序;否则用 all_steps_status 按 step_order
- if (status >= 2 && status !== 3) {
- const approvedRecords = data.approval_records?.filter((r: any) => r.status === 1) || [];
- if (approvedRecords.length) {
- const sorted = [...approvedRecords].sort(
- (a: any, b: any) => (a.step_order ?? 0) - (b.step_order ?? 0)
- );
- const names = sorted
- .map((r: any) => (r.approver_name || r.app_user_approver_name || r.name || '').trim())
- .filter(Boolean);
- if (names.length) return names.join('、');
- }
- if (adminInfo?.all_steps_status?.length) {
- const allNames: string[] = [];
- const seen = new Set<string>();
- const sortedSteps = [...adminInfo.all_steps_status].sort(
- (a: any, b: any) => (a.step_order ?? 0) - (b.step_order ?? 0)
- );
- for (const step of sortedSteps) {
- if (step.approvers?.length) {
- for (const a of step.approvers) {
- const name = (a.name || '').trim();
- if (name && !seen.has(name)) {
- seen.add(name);
- allNames.push(name);
- }
- }
- }
- }
- if (allNames.length) return allNames.join('、');
- }
- }
- // 待审批时:取当前待审批环节,排除已通过的步骤(API 可能将已通过步骤仍标为 is_current)
- const isApproved = (s: any) => s.status === 'approved' || s.status_label === '已通过';
- const isPendingOrCurrent = (s: any) =>
- !isApproved(s) && (
- s.status === 'pending' || s.status_label === '待审核' ||
- s.status === 'current' || s.status_label === '当前步骤' || s.is_current === true
- );
- const candidateSteps = adminInfo?.all_steps_status?.filter(isPendingOrCurrent) || [];
- const sortedCandidates = [...candidateSteps].sort((a: any, b: any) => (a.step_order ?? 0) - (b.step_order ?? 0));
- const pendingStep = sortedCandidates[0];
- if (pendingStep?.approvers?.length) {
- const stepName = pendingStep.step_name || '';
- let approvers = pendingStep.approvers;
- if (stepName.includes('老师')) {
- // 老师环节:仅显示 type 为 app_user 的审批人(老师姓名)
- approvers = approvers.filter((a: any) => a.type === 'app_user');
- } else if (stepName.includes('管理员')) {
- // 二级管理员/管理员环节:仅显示 type 为 admin 的审批人(超级管理员)
- approvers = approvers.filter((a: any) => a.type === 'admin');
- }
- const names = approvers.map((a: any) => a.name).filter((n: string) => n && n.trim());
- if (names.length) return names.join('、');
- }
- const currentApprovers = adminInfo?.current_step?.approvers;
- if (Array.isArray(currentApprovers) && currentApprovers.length) {
- const names = currentApprovers.map((a: any) => a.name).filter((n: string) => n && n.trim());
- if (names.length) return names.join('、');
- }
- const currentStep = adminInfo?.all_steps_status?.find((s: any) => s.is_current);
- if (currentStep?.approvers?.length) {
- const names = currentStep.approvers.map((a: any) => a.name).filter((n: string) => n && n.trim());
- if (names.length) return names.join('、');
- }
- if (data.approval_records?.length) {
- const pendingRecords = data.approval_records.filter(
- (item: any) => (status === 1 ? item.status !== 1 : item.status !== 0)
- );
- const names = pendingRecords
- .map((item: any) => item.approver_name || item.app_user_approver_name || item.name)
- .filter((name: string) => name && name.trim());
- if (names.length) return names.join('、');
- }
- return data.approver_info?.name || '未知';
- }
- // 表单审批人显示:待审批时与流程步骤一致,审批完成后显示管理员
- const displayApproverName = computed(() => {
- const data = form.value as any;
- if (!data?.id) return '';
- const status = data.status;
- if (status >= 2 && status !== 3) return '管理员'; // 审批通过
- if (status >= 4) return '管理员'; // 流程完成
- if (status === 1) return getPendingApproverDisplay(data); // 待审批
- if (status === 3) {
- const rejectNames = data.approval_records
- ?.filter((item: any) => item.status === 2)
- ?.map((item: any) => item.approver_name || item.app_user_approver_name || item.name)
- ?.filter((name: string) => name && name.trim()) || [];
- return rejectNames.join('、') || data.approver_info?.name || '未知';
- }
- return data.approver_info?.name || data.admin_approver_info?.name || '';
- });
- // 计算是否应该隐藏设备清单标签页
- const shouldHideDeviceList = computed(() => {
- if (!isView.value) return false;
- // 检查状态
- const status = (form.value as any).status;
- const statusLabel = (form.value as any).status_label;
- // 审批拒绝:隐藏设备清单
- const isRejected = status === 3 || (typeof statusLabel === 'string' && statusLabel.includes('拒绝'));
- if (isRejected) {
- return true;
- }
- // 强制显示:状态大于 5 或状态标签为"已借出"
- if ((typeof status === 'number' && status > 5) || statusLabel === '已借出') {
- return false;
- }
- // 审批通过:隐藏设备清单(不影响已借出/更高级状态的强制显示)
- const isApproved = typeof statusLabel === 'string' && statusLabel.includes('已批准');
- if (isApproved) {
- return true;
- }
- // 待审批状态:隐藏设备清单
- const isPendingApproval = status < 2 || statusLabel === '待审批';
- // 其他情况默认显示
- return isPendingApproval;
- });
- // 计算设备状态映射
- const deviceStatusMap = computed(() => {
- const statusMap: Record<string | number, any> = {};
- returnDeviceList.value.forEach(device => {
- if (device.device_no && device.return_status) {
- statusMap[device.device_no] = device.return_status;
- }
- });
- return statusMap;
- });
- const emit = defineEmits(['update:visible', 'update:modelValue', 'submit']);
- const visible = ref(props.visible);
- const formRef = ref();
- // 图片预览相关
- const dialogImageUrl = ref('');
- const dialogVisible = ref(false);
- const timeline = ref({
- create: '',
- approve: '',
- approver: ''
- });
- // const activeStep = ref(1);
- const activeName = ref('first');
- const returnStatus = ref('未归还'); // 添加独立的状态变量
- // 输入框引用
- const searchInputRef = ref<any>(null);
- const returnSearchInputRef = ref<any>(null);
- // 借用列表相关数据
- const searchText = ref('');
- const deviceList = ref<DeviceListItem[]>([]);
- const accessoryInfo = ref('');
- const remark = ref('');
- // 领取模式下的"实借配件信息"本地输入,不回显历史
- const collectAccessories = ref('');
- // RFID高速扫码缓冲相关
- const rfidInputBuffer = ref('');
- // RFID标签数组,用于收集批量识别的标签
- const rfidTagArray = ref<string[]>([]);
- // 当前正在输入的标签
- const currentRfidTag = ref('');
- // 正在处理的标签集合,用于去重
- const processingTags = ref<Set<string>>(new Set());
- // 是否正在处理标签数组
- const isProcessingTagArray = ref(false);
- // 待提交的设备编号数组(参考 InventoryDialog 实现)
- const pendingDeviceCodes = ref<string[]>([]);
- // 是否正在自动循环提交
- const isAutoSubmitting = ref(false);
- let rfidInputTimer: ReturnType<typeof setTimeout> | null = null;
- // 统一的标签数组处理延迟定时器,避免多次触发
- let processTagArrayTimer: ReturnType<typeof setTimeout> | null = null;
- const loading = ref(false);
- // 记录最后一次输入时间,用于检测是否是高速扫码输入
- let lastInputTime = 0;
- // 记录连续输入次数,用于判断是否是扫码输入
- let consecutiveInputCount = 0;
- // RFID读取规则配置(简化版,可根据需要扩展)
- const readRuleConfig = ref({
- enableRFIDBuffer: true, // 是否启用RFID缓冲
- rfidInputTimeout: 120, // RFID缓冲判定时间(ms)
- separator: ' ', // 分隔符
- minInputSpeed: 30, // 最小输入速度(ms),低于此值认为是扫码输入
- tagSeparatorTimeout: 100, // 标签分隔判定时间(ms),超过此时间认为是一个新标签
- });
- // 归还设备相关数据
- const returnSearchText = ref('');
- const returnDeviceList = ref<DeviceListItem[]>([]);
- const returnAccessoryInfo = ref('');
- const returnRemark = ref('');
- const selectedDevices = ref<DeviceListItem[]>([]); // 添加选中设备列表
- // 归还流程 RFID高速扫码缓冲相关
- const returnRfidInputBuffer = ref('');
- // 归还流程 RFID标签数组,用于收集批量识别的标签
- const returnRfidTagArray = ref<string[]>([]);
- // 归还流程当前正在输入的标签
- const returnCurrentRfidTag = ref('');
- // 归还流程正在处理的标签集合,用于去重
- const returnProcessingTags = ref<Set<string>>(new Set());
- // 归还流程是否正在处理标签数组
- const isProcessingReturnTagArray = ref(false);
- let returnRfidInputTimer: ReturnType<typeof setTimeout> | null = null;
- // 统一的归还标签数组处理延迟定时器,避免多次触发
- let returnProcessTagArrayTimer: ReturnType<typeof setTimeout> | null = null;
- // 记录归还流程最后一次输入时间,用于检测是否是高速扫码输入
- let returnLastInputTime = 0;
- // 记录归还流程连续输入次数,用于判断是否是扫码输入
- let returnConsecutiveInputCount = 0;
- // 备注显示值计算属性:查看模式下显示 problem_remarks[0],否则显示 returnRemark
- const displayReturnRemark = computed({
- get: () => {
- if (isView.value && form.value.problem_remarks?.[0]) {
- return form.value.problem_remarks[0];
- }
- return returnRemark.value;
- },
- set: (val: string) => {
- if (!isView.value) {
- returnRemark.value = val;
- }
- }
- });
- /** 从借用单明细行解析待归还数量:优先用 pending_quantity,缺省时用借出-已还推算(与后端 items 一致,避免硬编码) */
- function getPendingUnreturnedFromItem(item: any): number {
- if (item == null) return 0;
- const raw = item.pending_quantity;
- if (raw !== undefined && raw !== null && String(raw) !== '') {
- const n = Math.floor(Number(raw));
- if (!Number.isNaN(n)) return Math.max(0, n);
- }
- const borrowed = Number(item.borrowed_quantity) || 0;
- const returned = Number(item.returned_quantity) || 0;
- return Math.max(0, borrowed - returned);
- }
- /** 从借用单 items 行解析「明细更新时间」(兼容常见后端字段名,避免写死单一路径) */
- function getItemLineUpdateTimeForSort(item: any): string | undefined {
- if (item == null || typeof item !== 'object') return undefined;
- const v =
- item.update_datetime ?? item.update_time ?? item.modified_time ?? item.update_at;
- if (v == null || v === '') return undefined;
- return String(v);
- }
- function getReturnRowSortMs(row: DeviceListItem): number {
- const serverRaw = row.line_update_at;
- const serverMs =
- serverRaw && dayjs(serverRaw).isValid() ? dayjs(serverRaw).valueOf() : 0;
- const localMs = row.sort_touched_at ?? 0;
- return Math.max(serverMs, localMs);
- }
- function touchReturnRowSort(row: DeviceListItem) {
- row.sort_touched_at = Date.now();
- }
- /** 将 form.items 单行映射为归还列表行:上限为待归还;归还数量由扫码/手工录入,从 0 起算 */
- function mapFormItemToReturnDeviceListRow(item: any): DeviceListItem {
- const pending = getPendingUnreturnedFromItem(item);
- const lineUpdate = getItemLineUpdateTimeForSort(item);
- return {
- device_no: item.device,
- device_code: item.device_code,
- device_type: item.remark,
- device_name: item.device_name,
- borrow_count: 0,
- brand: item.brand || item.device_brand || '',
- model: item.device_specification,
- warehouse: item.location || item.device_storage_location || '',
- problem_records: item.problem_records,
- return_status: item.return_status,
- return_time: item.return_times,
- available_quantity: pending,
- returned_quantity: Math.max(0, Number(item.returned_quantity) || 0),
- line_update_at: lineUpdate,
- sort_touched_at: 0
- };
- }
- function clampReturnBorrowCount(row: DeviceListItem) {
- const max = row.available_quantity ?? 0;
- if (max <= 0) {
- row.borrow_count = 0;
- return;
- }
- let n = Number(row.borrow_count) || 0;
- if (n < 0) n = 0;
- if (n > max) n = max;
- row.borrow_count = n;
- touchReturnRowSort(row);
- }
- /** 是否仍有待归还(有未归还可还):用于表格列在「只展示已归还」与「展示待还+本次归还」间切换 */
- function isReturnLinePendingReturn(row: DeviceListItem) {
- return (Number(row.available_quantity) || 0) > 0;
- }
- /**
- * 扫码命中列表中的设备时:归还数量 +1,不超过待归还数。
- * 成功返回 null;失败返回提示文案。不在此调用 ElMessage,由扫码/RFID 批处理处统一只弹一次。
- */
- function tryApplyReturnScanIncrement(row: DeviceListItem): string | null {
- const cap = row.available_quantity ?? 0;
- if (cap <= 0) {
- return '该设备无待归还数量';
- }
- const current = Number(row.borrow_count) || 0;
- if (current >= cap) {
- return '该设备归还数量已达待归还上限';
- }
- row.borrow_count = current + 1;
- if (row.borrow_count >= cap) {
- row.is_return = true;
- row.return_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
- }
- touchReturnRowSort(row);
- return null;
- }
- // 统一判定「该明细是否已把本次可归还数记满」:用于选设备白名单/全部完成判断(不依赖硬编码业务状态值)
- const isDeviceReturned = (device: any) => {
- const cap = Number(device?.available_quantity) || 0;
- if (cap <= 0) return true;
- return (Number(device?.borrow_count) || 0) >= cap;
- };
- // 过滤未归还设备的 device_no 列表,用于设备选择弹窗的排除
- const unreturnedDeviceIds = computed(() =>
- returnDeviceList.value
- .filter((d) => !isDeviceReturned(d))
- .map((d) => d.device_no)
- );
- // 是否全部已归还(仅在归还页签生效)
- const allReturned = computed(() => unreturnedDeviceIds.value.length === 0);
- /** 列表中是否仍有「待归还」行:为 false 时整表隐藏「未归还可还」「归还数量」两列(仅保留已归还数量等) */
- const showUnreturnedReturnTableColumns = computed(() =>
- returnDeviceList.value.some((d) => (Number(d.available_quantity) || 0) > 0)
- );
- /** 归还设备表按「明细/本页最近修改时间」降序,最近在前 */
- const sortedReturnDeviceList = computed(() =>
- [...returnDeviceList.value].sort(
- (a, b) => getReturnRowSortMs(b) - getReturnRowSortMs(a)
- )
- );
- //审批步骤
- const steps = ref<any[]>([]);
- // 仓库映射(id -> name)
- const warehouseMap = ref<Record<string, string>>({});
- async function loadWarehouses() {
- try {
- const res = await request({
- url: '/api/system/warehouse/',
- method: 'get',
- params: { page: 1, limit: 999 }
- });
- if (res?.code === 2000 && Array.isArray(res.data)) {
- warehouseMap.value = Object.fromEntries(
- res.data.map((w: any) => [String(w.id), w.name])
- );
- }
- } catch (e) {
- /* empty */
- }
- }
- function getWarehouseName(id: any) {
- const key = id != null ? String(id) : '';
- return warehouseMap.value[key] ?? id;
- }
- /** 从 Promise.allSettled 单条结果安全取出 success/message,避免解构 undefined 导致整批 try 抛错、误报「处理批次时发生错误」 */
- function readSettledListStepResult(
- result: PromiseSettledResult<unknown>,
- codeLabel: string
- ): { success: boolean; message?: string } {
- if (result.status === 'rejected') {
- const err = result.reason instanceof Error ? result.reason.message : String(result.reason);
- return { success: false, message: `处理设备编号 ${codeLabel} 时发生错误: ${err}` };
- }
- const v = result.value as { success?: boolean; message?: string } | null | undefined;
- if (v == null || typeof v !== 'object' || typeof v.success !== 'boolean') {
- return { success: false, message: `处理设备编号 ${codeLabel} 时返回数据异常` };
- }
- return { success: v.success, message: v.message };
- }
- /**
- * 从设备查询接口解析可借/可用数量(领取页扫码):先取根字段,再取 inventory.available_quantity
- */
- function getDeviceAvailableQuantityForBorrow(device: any): number {
- if (device == null) return 0;
- const top = device.available_quantity;
- if (top !== undefined && top !== null && String(top) !== '') {
- const n = Number(top);
- if (!Number.isNaN(n)) return Math.max(0, Math.floor(n));
- }
- const inv = device.inventory?.available_quantity;
- if (inv !== undefined && inv !== null && String(inv) !== '') {
- const n = Number(inv);
- if (!Number.isNaN(n)) return Math.max(0, Math.floor(n));
- }
- return 0;
- }
- // 添加结算单相关的状态
- const showSettlementDialog = ref(false);
- const settlementData = ref<any>(null);
- const borrowForm = ref<any>(null);
- // 添加异常操作相关的状态
- const showAbnormalDialog = ref(false);
- const currentAbnormalDeviceNo = ref<string | number | null>(null);
- // 添加查看异常相关的状态
- const showViewAbnormalDialog = ref(false);
- const currentAbnormalData = ref<AbnormalData>({
- damage_type:0,
- condition: '',
- photos: []
- });
- //审批
- function buildSteps(data: any) {
- steps.value = [
- {
- title: '创建申请',
- description: `创建时间:${data.create_datetime ? dayjs(data.create_datetime).format('YYYY-MM-DD HH:mm:ss') : ''}`,
- status: 'finish'
- },
- {
- title: '待审批',
- description: `待审批人:${getPendingApproverDisplay(data)} 审批`,
- status: data.status >= 2 ? 'finish' : 'process'
- }
- ];
- const approverinfo = data.approver_info ?? data.admin_approver_info
- if (data.status >= 2&&data.status!=3 && data.borrow_type!=1) {
- // 将审批记录倒序排列
- const reversedApprovalRecords = [...data.approval_records]
- // 先找出所有审批通过的记录
- const approvedRecords = reversedApprovalRecords.filter((item:any) => item.status === 1)
- const lastApprovedIndex = approvedRecords.length - 1
-
- reversedApprovalRecords.forEach((item:any,index:number) => {
- if(item.status === 1){
- // 找到当前记录在审批通过记录中的索引
- const currentApprovedIndex = approvedRecords.findIndex((record:any) => record === item)
- // 判断是否是最后一个审批通过的记录
- const isLastApproved = currentApprovedIndex === lastApprovedIndex
-
- /* if(index == 1){1
- steps.value.push({
- title: '审批通过',
- description: `审批人:${item.approver_name||item.app_user_approver_name},时 间:${item.approve_time}`,
- status: 'finish'
- });
- }else{ */
- // 只在最后一个审批通过的记录中显示领取仓库
- const warehouseInfo = isLastApproved ? `,领取仓库:${getWarehouseName(data.warehouse)||'暂无仓库'}` : ''
- steps.value.push({
- title: '审批通过',
- description: `审批人:${item.approver_name||item.app_user_approver_name},时 间:${item.create_datetime ? dayjs(item.create_datetime).format('YYYY-MM-DD HH:mm:ss') : ''}${warehouseInfo}`,
- status: 'finish'
- });
- /* } */
- }
- });
- } else if (data.status === 3) {
- // console.log("data.approver_name:::",data.approver_info.name)
- const rejectNames = data.approval_records
- .filter((item:any) => item.status === 2)
- .map((item:any) => item.approver_name || item.app_user_approver_name || item.name)
- .filter((name:any) => name && name.trim());
- const rejectReason = data.approval_records
- .filter((item:any) => item.status === 2)
- .map((item:any) => item.approve_remark)
- .filter((reason:any) => reason && reason.trim());
- const rejectTime = data.approval_records
- .filter((item:any) => item.status === 2)
- .map((item:any) => item.approve_time)
- .filter((time:any) => time && time.trim());
- steps.value.push({
- title: '审批拒绝',
- description: `审批人:${rejectNames.join('、')},拒绝原因: ${rejectReason.join('、')},时间:${rejectTime.join('、')}`,
- status: 'error'
- });
- }
- if (data.status >= 4 ||data.borrow_type==1) {
- steps.value.push({
- title: '流程完成',
- description: '流程已结束',
- status: 'finish'
- });
- }
- }
- // 处理异常操作(按 device_no 定位,避免与「按时间排序的表格」下标错位)
- const handleAbnormal = (row: DeviceListItem) => {
- currentAbnormalDeviceNo.value = row.device_no;
- showAbnormalDialog.value = true;
- };
- // 处理异常操作确认
- const onAbnormalConfirm = (data: { condition: string; photos: any[]; damage_type?: number }) => {
- const key = currentAbnormalDeviceNo.value;
- if (key != null && key !== '') {
- const device = returnDeviceList.value.find((d) => d.device_no === key);
- if (device) {
- device.condition = data.condition;
- device.photos = data.photos;
- device.damage_type = data.damage_type;
- touchReturnRowSort(device);
- ElMessage.success('异常信息已保存');
- }
- }
- currentAbnormalDeviceNo.value = null;
- };
- // 处理查看异常
- const handleViewAbnormal = (row: DeviceListItem) => {
- const device = row;
- console.log("device:::",device);
- if (device) {
- if(device.problem_records?.length){
- console.log(device.problem_records?.[0].damage_type.value)
- currentAbnormalData.value = {
- damage_type: Number(device.problem_records?.[0].damage_type.value) || 0,/* ||device.damage_type.value */
- condition: device.problem_records?.[0].device_condition_after ||'',
- photos: device.problem_records?.[0].returned_images.map((item:any)=>item.image_url) ||[]
- };
- }else{
- currentAbnormalData.value = {
- damage_type: device.damage_type ||0,
- condition: device.condition ||'',
- photos: device.photos ||[]
- };
- }
- showViewAbnormalDialog.value = true;
- }
- };
- // 清理RFID输入定时器
- const clearRFIDInputTimer = () => {
- if (rfidInputTimer) {
- clearTimeout(rfidInputTimer);
- rfidInputTimer = null;
- }
- };
- // 清理标签数组处理延迟定时器
- const clearProcessTagArrayTimer = () => {
- if (processTagArrayTimer) {
- clearTimeout(processTagArrayTimer);
- processTagArrayTimer = null;
- }
- };
- // 清理归还流程RFID输入定时器
- const clearReturnRFIDInputTimer = () => {
- if (returnRfidInputTimer) {
- clearTimeout(returnRfidInputTimer);
- returnRfidInputTimer = null;
- }
- };
- // 清理归还标签数组处理延迟定时器
- const clearReturnProcessTagArrayTimer = () => {
- if (returnProcessTagArrayTimer) {
- clearTimeout(returnProcessTagArrayTimer);
- returnProcessTagArrayTimer = null;
- }
- };
- // 处理RFID标签数组,逐个检索并提交
- // 自动循环提交待提交的设备编号(参考 InventoryDialog 实现)
- const autoSubmitPendingCodes = async () => {
- // 如果正在提交或没有待提交的设备编号,直接返回
- if (isAutoSubmitting.value || pendingDeviceCodes.value.length === 0) {
- return;
- }
-
- isAutoSubmitting.value = true;
-
- try {
- // 复制待提交的设备编号数组并清空,避免在处理过程中被修改
- const codesToSubmit = [...pendingDeviceCodes.value];
- pendingDeviceCodes.value = [];
-
- console.log(`[autoSubmitPendingCodes] 开始自动提交,共 ${codesToSubmit.length} 个设备编号:`, codesToSubmit);
-
- // 逐个循环提交,每个设备编号独立处理,不受成功或失败影响
- for (let i = 0; i < codesToSubmit.length; i++) {
- const code = codesToSubmit[i];
- if (!code || !code.trim()) continue;
-
- const trimmedCode = code.trim();
-
- try {
- // 查询设备信息
- const res = await deviceApi.GetList({
- page: 1,
- limit: 1,
- code: trimmedCode,
- status: 1
- });
-
- if (res.data && res.data.length > 0) {
- const device = res.data[0];
- const avail = getDeviceAvailableQuantityForBorrow(device);
- if (avail <= 0) {
- const label = [device.name, device.code].filter(Boolean).join(' ') || trimmedCode;
- ElMessage.warning(`设备 ${label}(${trimmedCode})库存不足`);
- continue;
- }
-
- // 检查设备是否已存在于列表中
- const existingDevice = deviceList.value.find(d => d.device_no === device.id);
- if (existingDevice) {
- // 如果已存在,增加借用数量
- existingDevice.borrow_count++;
- console.log(`设备 ${trimmedCode} 已存在,借用数量+1`);
- } else {
- // 如果不存在,添加到列表
- deviceList.value.push({
- device_no: device.id,
- device_code: device.code,
- device_type: device.category_name,
- device_name: device.name || '',
- borrow_count: 1,
- brand: device.brand || device.device_brand || '',
- device_specification: device.specification,
- model: device.model || '',
- warehouse: device.warehouse,
- available_quantity: avail
- });
- console.log(`设备 ${trimmedCode} 已添加到列表`);
- }
- } else {
- console.warn(`未找到设备编号: ${trimmedCode}`);
- }
- } catch (error) {
- // 即使某个设备编号处理失败,也继续处理下一个,不受影响
- console.error(`处理设备编号 ${trimmedCode} 失败:`, error);
- }
-
- // 每个设备编号处理完后稍作延迟,避免请求过快
- if (i < codesToSubmit.length - 1) {
- await new Promise(resolve => setTimeout(resolve, 50));
- }
- }
-
- console.log(`[autoSubmitPendingCodes] 自动提交完成,共处理 ${codesToSubmit.length} 个设备编号`);
- } catch (error) {
- console.error(`[autoSubmitPendingCodes] 自动提交过程中发生错误:`, error);
- } finally {
- isAutoSubmitting.value = false;
-
- // 如果还有待提交的设备编号,继续处理
- if (pendingDeviceCodes.value.length > 0) {
- setTimeout(() => {
- autoSubmitPendingCodes();
- }, 100);
- }
- }
- };
- const processRfidTagArray = async () => {
- if (rfidTagArray.value.length === 0 || isProcessingTagArray.value) return;
-
- isProcessingTagArray.value = true;
-
- // 使用 try-finally 确保状态总是被重置
- try {
- // 复制标签数组并清空,避免在处理过程中被修改
- const tagsToProcess = [...rfidTagArray.value];
- rfidTagArray.value = [];
-
- console.log(`[processRfidTagArray] 开始处理,收到 ${tagsToProcess.length} 个标签:`, tagsToProcess);
-
- // 去重处理:过滤掉正在处理或已处理的标签
- // 注意:不要在这里就添加到 processingTags,而是在实际开始处理时才添加
- const uniqueTagsToProcess = tagsToProcess.filter(tag => {
- const trimmedTag = tag.trim();
- if (!trimmedTag) return false;
- // 只跳过正在处理的标签,不在这里添加
- const shouldProcess = !processingTags.value.has(trimmedTag);
- if (!shouldProcess) {
- console.log(`[processRfidTagArray] 标签 ${trimmedTag} 正在处理中,跳过`);
- }
- return shouldProcess;
- });
-
- console.log(`[processRfidTagArray] 去重后需要处理 ${uniqueTagsToProcess.length} 个标签:`, uniqueTagsToProcess);
-
- // 将所有标签分割后的设备编号先缓存到 pendingDeviceCodes 数组
- const allCodes: string[] = [];
-
- for (const tag of uniqueTagsToProcess) {
- const trimmedTag = tag.trim();
- if (!trimmedTag) continue;
-
- // 分割标签,可能包含多个设备编号
- const codes = splitDeviceCodes(trimmedTag);
- const uniqueCodes = Array.from(new Set(codes.map(code => code.trim()))).filter(Boolean);
-
- // 添加到缓存数组(去重)
- uniqueCodes.forEach(code => {
- if (!allCodes.includes(code) && !pendingDeviceCodes.value.includes(code)) {
- allCodes.push(code);
- }
- });
- }
-
- // 将设备编号添加到待提交列表
- if (allCodes.length > 0) {
- pendingDeviceCodes.value.push(...allCodes);
- console.log(`[processRfidTagArray] 已将 ${allCodes.length} 个设备编号添加到待提交列表:`, allCodes);
-
- // 触发自动循环提交
- if (!isAutoSubmitting.value) {
- autoSubmitPendingCodes();
- }
- }
-
- // 所有标签处理完成后,清理处理标志并重新聚焦输入框
- console.log(`[processRfidTagArray] 所有标签已缓存到待提交列表,共 ${allCodes.length} 个设备编号`);
- console.log(`[processRfidTagArray] 当前待提交列表中的设备编号数量:`, pendingDeviceCodes.value.length);
-
- } catch (outerError) {
- // 捕获整个处理过程中的任何未预期错误,确保状态被重置
- console.error(`[processRfidTagArray] 处理过程中发生未预期错误:`, outerError);
- ElMessage.error('处理标签时发生错误,但已尝试处理所有标签');
- } finally {
- // 确保无论发生什么,状态都被重置
- isProcessingTagArray.value = false;
- loading.value = false;
- searchText.value = '';
-
- // 清理处理中的标签标记(延迟清理,避免立即重复处理)
- setTimeout(() => {
- processingTags.value.clear();
- }, 1000);
-
- nextTick(() => {
- if (searchInputRef.value) {
- searchInputRef.value.focus();
- searchInputRef.value.select();
- }
- });
- }
- };
- // 提交RFID缓冲区内容
- const submitRFIDBuffer = () => {
- if (!readRuleConfig.value.enableRFIDBuffer) {
- // 如果未启用RFID缓冲,直接使用 searchText 进行搜索
- if (searchText.value.trim()) {
- handleScanSearch();
- }
- return;
- }
-
- // 如果有标签数组,优先处理标签数组
- if (rfidTagArray.value.length > 0) {
- clearRFIDInputTimer();
- consecutiveInputCount = 0;
- lastInputTime = 0;
- processRfidTagArray();
- return;
- }
-
- if (!rfidInputBuffer.value && !currentRfidTag.value) {
- // 如果没有缓冲内容,使用 searchText 进行搜索
- if (searchText.value.trim()) {
- handleScanSearch();
- }
- return;
- }
-
- // 如果有当前标签,先添加到标签数组(去重)
- if (currentRfidTag.value.trim()) {
- const tag = currentRfidTag.value.trim();
- if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
- rfidTagArray.value.push(tag);
- }
- currentRfidTag.value = '';
- }
-
- // 如果有缓冲内容,也添加到标签数组(去重)
- if (rfidInputBuffer.value.trim()) {
- const tag = rfidInputBuffer.value.trim();
- if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
- rfidTagArray.value.push(tag);
- }
- rfidInputBuffer.value = '';
- }
-
- clearRFIDInputTimer();
- consecutiveInputCount = 0;
- lastInputTime = 0;
-
- // 处理标签数组
- if (rfidTagArray.value.length > 0) {
- processRfidTagArray();
- }
- };
- // 调度RFID缓冲区提交(延迟提交)
- const scheduleRFIDBufferSubmit = () => {
- if (!readRuleConfig.value.enableRFIDBuffer) return;
- clearRFIDInputTimer();
- const delay = Math.max(readRuleConfig.value.rfidInputTimeout || 120, 30);
- rfidInputTimer = setTimeout(() => {
- console.log(`[scheduleRFIDBufferSubmit] 延迟提交触发,当前状态:`, {
- currentRfidTag: currentRfidTag.value,
- rfidInputBuffer: rfidInputBuffer.value,
- searchText: searchText.value,
- rfidTagArray: rfidTagArray.value
- });
-
- // 如果 searchText 中有内容,优先检查是否包含多个标签(通过换行、回车等分隔)
- if (searchText.value.trim()) {
- const codes = splitDeviceCodes(searchText.value);
- console.log(`[scheduleRFIDBufferSubmit] searchText 分割得到 ${codes.length} 个代码:`, codes, '原始内容长度:', searchText.value.length);
-
- // 无论有多少个标签,都添加到标签数组
- if (codes.length > 0) {
- codes.forEach(code => {
- const trimmedCode = code.trim();
- if (trimmedCode && !rfidTagArray.value.includes(trimmedCode) && !processingTags.value.has(trimmedCode)) {
- rfidTagArray.value.push(trimmedCode);
- console.log(`[scheduleRFIDBufferSubmit] 添加标签到数组: ${trimmedCode}`);
- }
- });
- searchText.value = '';
- }
- }
-
- // 如果当前标签有内容,先保存到标签数组(去重)
- if (currentRfidTag.value.trim()) {
- const tag = currentRfidTag.value.trim();
- if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
- rfidTagArray.value.push(tag);
- console.log(`[scheduleRFIDBufferSubmit] 添加当前标签到数组: ${tag}`);
- }
- currentRfidTag.value = '';
- }
- // 如果有缓冲内容,也添加到标签数组(去重)
- if (rfidInputBuffer.value.trim()) {
- const tag = rfidInputBuffer.value.trim();
- if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
- rfidTagArray.value.push(tag);
- console.log(`[scheduleRFIDBufferSubmit] 添加缓冲标签到数组: ${tag}`);
- }
- rfidInputBuffer.value = '';
- }
-
- console.log(`[scheduleRFIDBufferSubmit] 延迟提交时,标签数组共有 ${rfidTagArray.value.length} 个标签:`, rfidTagArray.value);
-
- // 处理标签数组,使用统一的延迟处理机制
- if (rfidTagArray.value.length > 0) {
- // 清除之前的延迟处理定时器(如果存在)
- clearProcessTagArrayTimer();
-
- // 设置统一的延迟处理,确保所有标签都被收集后再处理
- processTagArrayTimer = setTimeout(() => {
- processTagArrayTimer = null;
- if (rfidTagArray.value.length > 0 && !isProcessingTagArray.value) {
- console.log(`[scheduleRFIDBufferSubmit] 延迟处理,最终标签数组:`, rfidTagArray.value);
- processRfidTagArray();
- }
- }, 300); // 增加延迟时间到300ms,确保所有标签都被收集
- }
- }, delay);
- };
- // 处理设备输入(用于同步 textarea 内容,仅在缓冲模式下使用)
- const handleDeviceInput = () => {
- // 如果启用了RFID缓冲,检查 searchText 中是否包含多个标签(通过换行、回车等分隔)
- if (readRuleConfig.value.enableRFIDBuffer && searchText.value.trim()) {
- // 检查是否包含换行符或回车符
- if (/[\r\n]/.test(searchText.value)) {
- // 如果包含换行符,说明可能有多个标签
- const codes = splitDeviceCodes(searchText.value);
- console.log(`[handleDeviceInput] 检测到换行符,分割得到 ${codes.length} 个代码:`, codes, '原始内容长度:', searchText.value.length, '原始内容:', searchText.value.substring(0, 200));
-
- // 无论有多少个标签,都添加到标签数组(包括单个标签的情况)
- if (codes.length > 0) {
- codes.forEach(code => {
- const trimmedCode = code.trim();
- if (trimmedCode && !rfidTagArray.value.includes(trimmedCode) && !processingTags.value.has(trimmedCode)) {
- rfidTagArray.value.push(trimmedCode);
- console.log(`[handleDeviceInput] 添加标签到数组: ${trimmedCode}`);
- }
- });
- console.log(`[handleDeviceInput] 标签数组共有 ${rfidTagArray.value.length} 个标签:`, rfidTagArray.value);
- // 清空 searchText,避免重复处理
- searchText.value = '';
- // 清空当前标签和缓冲区,因为已经添加到数组了
- currentRfidTag.value = '';
- rfidInputBuffer.value = '';
- // 如果有标签数组且当前没有在处理,使用统一的延迟处理机制
- if (rfidTagArray.value.length > 0 && !isProcessingTagArray.value) {
- clearRFIDInputTimer();
-
- // 清除之前的延迟处理定时器(如果存在)
- clearProcessTagArrayTimer();
-
- // 设置统一的延迟处理,确保所有标签都被收集后再处理
- processTagArrayTimer = setTimeout(() => {
- processTagArrayTimer = null;
- if (rfidTagArray.value.length > 0 && !isProcessingTagArray.value) {
- console.log(`[handleDeviceInput] 延迟处理,最终标签数组:`, rfidTagArray.value);
- processRfidTagArray();
- }
- }, 300); // 增加延迟时间到300ms,确保所有标签都被收集
- }
- return;
- }
- }
- }
-
- // 如果缓冲区有内容,确保 textarea 显示与缓冲区一致
- // 这主要用于处理退格键等操作后的同步
- if (currentRfidTag.value || rfidInputBuffer.value) {
- const displayValue = currentRfidTag.value || rfidInputBuffer.value;
- if (searchText.value !== displayValue) {
- searchText.value = displayValue;
- }
- }
- // 注意:正常输入时,不干预 textarea 的内容,让默认行为处理
- };
- // 检测是否是高速扫码输入(通过输入速度判断)
- // 返回值:{ isHighSpeed: boolean, isFirstInput: boolean, isNormalInput: boolean, timeSinceLastInput: number }
- const checkInputSpeed = () => {
- const now = Date.now();
- const timeSinceLastInput = lastInputTime > 0 ? now - lastInputTime : 0;
- const isFirstInput = lastInputTime === 0;
-
- if (!isFirstInput) {
- lastInputTime = now;
- }
-
- return {
- isFirstInput,
- timeSinceLastInput,
- isHighSpeed: timeSinceLastInput > 0 && timeSinceLastInput < readRuleConfig.value.minInputSpeed,
- isNormalInput: timeSinceLastInput > 200
- };
- };
- // 处理RFID键盘输入(高速扫码)
- const handleRFIDKeydown = (event: KeyboardEvent) => {
- // 如果未启用RFID缓冲,直接返回,不拦截
- if (!readRuleConfig.value.enableRFIDBuffer) {
- return;
- }
-
- // 不拦截修饰键组合(如 Ctrl+C, Ctrl+V 等)
- if (event.ctrlKey || event.metaKey || event.altKey) {
- return;
- }
-
- // 处理回车键
- if (event.key === 'Enter') {
- // 回车键由 @keydown.enter.prevent="handleDeviceEnter" 处理
- // 这里不处理,让 handleDeviceEnter 统一处理
- return;
- }
-
- // 处理退格键
- if (event.key === 'Backspace') {
- // 如果有当前标签或缓冲内容,处理缓冲
- if (currentRfidTag.value || rfidInputBuffer.value) {
- event.preventDefault();
- if (currentRfidTag.value) {
- currentRfidTag.value = currentRfidTag.value.slice(0, -1);
- rfidInputBuffer.value = currentRfidTag.value;
- } else {
- rfidInputBuffer.value = rfidInputBuffer.value.slice(0, -1);
- }
- searchText.value = rfidInputBuffer.value || currentRfidTag.value;
- }
- // 否则让默认行为处理
- return;
- }
-
- // 处理普通字符输入
- if (event.key.length === 1) {
- const inputInfo = checkInputSpeed();
- const { isFirstInput, isHighSpeed, isNormalInput, timeSinceLastInput } = inputInfo;
-
- // 如果是第一次输入,不拦截,让默认行为处理,只记录时间戳
- if (isFirstInput) {
- lastInputTime = Date.now();
- // 不拦截,让字符正常输入到 textarea
- return;
- }
-
- // 如果检测到是正常输入(间隔 > 200ms),处理之前的缓冲内容
- if (isNormalInput) {
- // 如果之前有当前标签或缓冲内容,先保存到标签数组(去重)
- if (currentRfidTag.value.trim()) {
- const tag = currentRfidTag.value.trim();
- if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
- rfidTagArray.value.push(tag);
- }
- currentRfidTag.value = '';
- }
- if (rfidInputBuffer.value.trim()) {
- const tag = rfidInputBuffer.value.trim();
- if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
- rfidTagArray.value.push(tag);
- }
- rfidInputBuffer.value = '';
- }
- // 如果有标签数组,处理它们
- if (rfidTagArray.value.length > 0) {
- processRfidTagArray();
- }
- // 重置状态
- consecutiveInputCount = 0;
- lastInputTime = Date.now();
- // 不拦截,让字符正常输入到 textarea
- return;
- }
-
- // 如果检测到是高速输入(间隔 < 30ms),使用缓冲模式
- if (isHighSpeed) {
- event.preventDefault();
- event.stopPropagation(); // 阻止事件冒泡,避免影响其他元素
-
- // 如果输入间隔超过标签分隔时间,说明是一个新标签的开始
- // 需要保存之前的标签到数组
- if (timeSinceLastInput > readRuleConfig.value.tagSeparatorTimeout) {
- // 保存当前标签到数组(如果存在且去重)
- if (currentRfidTag.value.trim()) {
- const tag = currentRfidTag.value.trim();
- if (!rfidTagArray.value.includes(tag)) {
- rfidTagArray.value.push(tag);
- }
- currentRfidTag.value = '';
- }
- // 保存缓冲内容到数组(如果存在且去重)
- if (rfidInputBuffer.value.trim()) {
- const tag = rfidInputBuffer.value.trim();
- if (!rfidTagArray.value.includes(tag)) {
- rfidTagArray.value.push(tag);
- }
- rfidInputBuffer.value = '';
- }
- // 如果 textarea 中有内容,检查是否需要添加到数组(去重)
- if (searchText.value.trim()) {
- const codes = splitDeviceCodes(searchText.value);
- codes.forEach(code => {
- const trimmedCode = code.trim();
- if (trimmedCode && !rfidTagArray.value.includes(trimmedCode) && !processingTags.value.has(trimmedCode)) {
- rfidTagArray.value.push(trimmedCode);
- }
- });
- searchText.value = ''; // 清空 searchText,避免重复处理
- }
- // 重置,开始新标签
- currentRfidTag.value = event.key;
- rfidInputBuffer.value = event.key;
- searchText.value = event.key;
- } else {
- // 如果是第一次检测到高速输入(之前没有缓冲内容),需要将 textarea 中已有的内容也加入当前标签
- if (currentRfidTag.value === '' && rfidInputBuffer.value === '' && searchText.value) {
- // textarea 中已经有内容(第一个字符已经通过默认行为输入了)
- // 将整个内容作为当前标签的初始值,然后追加当前字符
- currentRfidTag.value = searchText.value + event.key;
- } else {
- // 否则直接追加当前字符到当前标签
- currentRfidTag.value += event.key;
- }
-
- // 同时更新缓冲区和显示
- rfidInputBuffer.value = currentRfidTag.value;
- searchText.value = currentRfidTag.value;
- }
-
- consecutiveInputCount++;
- scheduleRFIDBufferSubmit();
- return;
- }
-
- // 如果输入间隔在 30-200ms 之间,可能是正常输入,不拦截
- // 但如果之前有缓冲内容,说明高速输入已结束,先保存当前标签(去重)
- if (currentRfidTag.value.trim() || rfidInputBuffer.value.trim()) {
- if (currentRfidTag.value.trim()) {
- const tag = currentRfidTag.value.trim();
- if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
- rfidTagArray.value.push(tag);
- }
- currentRfidTag.value = '';
- }
- if (rfidInputBuffer.value.trim()) {
- const tag = rfidInputBuffer.value.trim();
- if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
- rfidTagArray.value.push(tag);
- }
- rfidInputBuffer.value = '';
- }
- // 处理标签数组
- if (rfidTagArray.value.length > 0) {
- processRfidTagArray();
- }
- consecutiveInputCount = 0;
- }
- lastInputTime = Date.now();
- // 不拦截,让字符正常输入到 textarea
- }
- };
- // 处理输入框失焦
- const handleDeviceBlur = (event: FocusEvent) => {
- // 如果焦点转移到其他输入元素(如表单输入框),不自动聚焦
- const relatedTarget = event.relatedTarget as HTMLElement;
- if (relatedTarget && (
- relatedTarget.tagName === 'INPUT' ||
- relatedTarget.tagName === 'TEXTAREA' ||
- relatedTarget.closest('.el-input') ||
- relatedTarget.closest('.el-textarea') ||
- relatedTarget.closest('form')
- )) {
- // 如果有缓冲内容,先提交
- if (rfidInputBuffer.value) {
- submitRFIDBuffer();
- }
- return;
- }
-
- // 其他情况(如点击按钮等),延迟后自动聚焦
- setTimeout(() => {
- if (searchInputRef.value && !loading.value) {
- searchInputRef.value.focus();
- }
- }, 10);
- };
- // 处理回车键
- const handleDeviceEnter = (event: KeyboardEvent) => {
- if (event.shiftKey) return;
- event.preventDefault();
-
- // 如果启用了RFID缓冲,先检查是否有当前标签或缓冲内容
- if (readRuleConfig.value.enableRFIDBuffer) {
- // 如果有当前标签,先保存到标签数组(去重)
- if (currentRfidTag.value.trim()) {
- const tag = currentRfidTag.value.trim();
- if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
- rfidTagArray.value.push(tag);
- }
- currentRfidTag.value = '';
- }
- // 如果有缓冲内容,也添加到标签数组(去重)
- if (rfidInputBuffer.value.trim()) {
- const tag = rfidInputBuffer.value.trim();
- if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
- rfidTagArray.value.push(tag);
- }
- rfidInputBuffer.value = '';
- }
- }
-
- // 检查 searchText 中是否包含多个标签(通过换行、回车等分隔)
- if (searchText.value.trim()) {
- const codes = splitDeviceCodes(searchText.value);
- console.log(`[handleDeviceEnter] 回车键提交时,searchText 分割得到 ${codes.length} 个代码:`, codes, '原始内容长度:', searchText.value.length, '原始内容:', searchText.value.substring(0, 500));
-
- // 将所有标签添加到数组(包括单个标签的情况)
- codes.forEach(code => {
- const trimmedCode = code.trim();
- if (trimmedCode && !rfidTagArray.value.includes(trimmedCode) && !processingTags.value.has(trimmedCode)) {
- rfidTagArray.value.push(trimmedCode);
- console.log(`[handleDeviceEnter] 添加标签到数组: ${trimmedCode}`);
- }
- });
- searchText.value = '';
- }
-
- console.log(`[handleDeviceEnter] 回车键提交时,标签数组共有 ${rfidTagArray.value.length} 个标签:`, rfidTagArray.value);
-
- // 如果有标签数组,使用统一的延迟处理机制,避免多次触发
- if (rfidTagArray.value.length > 0) {
- clearRFIDInputTimer();
- consecutiveInputCount = 0;
- lastInputTime = 0;
-
- // 清除之前的延迟处理定时器(如果存在)
- if (processTagArrayTimer) {
- clearTimeout(processTagArrayTimer);
- processTagArrayTimer = null;
- }
-
- // 设置统一的延迟处理,确保所有标签都被收集后再处理
- processTagArrayTimer = setTimeout(() => {
- processTagArrayTimer = null;
- if (rfidTagArray.value.length > 0 && !isProcessingTagArray.value) {
- console.log(`[handleDeviceEnter] 延迟处理,最终标签数组:`, rfidTagArray.value);
- processRfidTagArray();
- }
- }, 300); // 增加延迟时间到300ms,确保所有标签都被收集
- return;
- }
-
- // 如果没有标签数组,使用 searchText 进行搜索
- if (searchText.value.trim()) {
- handleScanSearch();
- }
- };
- // 分割多个设备编号(支持分隔符)
- const splitDeviceCodes = (input: string): string[] => {
- const trimmed = input.trim();
- if (!trimmed) return [];
-
- const { separator } = readRuleConfig.value;
-
- // 优先处理换行符
- if (/[\r\n]/.test(trimmed)) {
- return trimmed.split(/[\r\n]+/).filter(code => code.trim());
- }
-
- // 处理配置的分隔符
- if (separator && separator.trim() !== '') {
- const escapedSeparator = separator.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- const separatorPattern = new RegExp(escapedSeparator + '+', 'g');
- return trimmed.split(separatorPattern).filter(code => code.trim());
- }
-
- // 处理空格分隔
- if (/\s/.test(trimmed)) {
- return trimmed.split(/\s+/).filter(code => code.trim());
- }
-
- // 单个设备编号
- return [trimmed];
- };
- // 处理扫码搜索(支持批量,优化并发请求)
- const handleScanSearch = async (event?: Event) => {
- // 阻止默认行为,防止表单提交导致页面刷新
- if (event) {
- event.preventDefault();
- event.stopPropagation();
- }
-
- // 如果启用了RFID缓冲,先提交缓冲区
- if (readRuleConfig.value.enableRFIDBuffer) {
- // 如果有当前标签,先保存到标签数组
- if (currentRfidTag.value.trim()) {
- if (!rfidTagArray.value.includes(currentRfidTag.value.trim())) {
- rfidTagArray.value.push(currentRfidTag.value.trim());
- }
- currentRfidTag.value = '';
- }
- // 如果有缓冲内容,也添加到标签数组
- if (rfidInputBuffer.value.trim()) {
- if (!rfidTagArray.value.includes(rfidInputBuffer.value.trim())) {
- rfidTagArray.value.push(rfidInputBuffer.value.trim());
- }
- rfidInputBuffer.value = '';
- }
- clearRFIDInputTimer();
-
- // 如果 searchText 中包含多个标签,先分割并添加到数组(去重)
- if (searchText.value.trim()) {
- const codes = splitDeviceCodes(searchText.value);
- codes.forEach(code => {
- const trimmedCode = code.trim();
- if (trimmedCode && !rfidTagArray.value.includes(trimmedCode) && !processingTags.value.has(trimmedCode)) {
- rfidTagArray.value.push(trimmedCode);
- }
- });
- searchText.value = '';
- }
-
- // 如果有标签数组,优先处理标签数组
- if (rfidTagArray.value.length > 0) {
- processRfidTagArray();
- return;
- }
- }
-
- if (!searchText.value.trim()) return;
-
- // 分割多个设备编号
- const codes = splitDeviceCodes(searchText.value);
- if (codes.length === 0) return;
-
- // 去重处理,避免重复请求同一个设备编号
- const uniqueCodes = Array.from(new Set(codes.map(code => code.trim()))).filter(Boolean);
- if (uniqueCodes.length === 0) return;
-
- loading.value = true;
- let successCount = 0;
- let failCount = 0;
- const errorMessages: string[] = [];
-
- try {
- // 批量并发处理设备编号(使用 Promise.allSettled 确保所有请求都完成)
- // 限制并发数量,避免同时发起过多请求
- const batchSize = 10; // 每批处理10个
- const batches: string[][] = [];
- for (let i = 0; i < uniqueCodes.length; i += batchSize) {
- batches.push(uniqueCodes.slice(i, i + batchSize));
- }
-
- // 用于收集所有成功获取的设备数据,避免并发添加时的竞态条件
- const deviceMap = new Map<number | string, any>();
- const processedCodes = new Set<string>();
-
- // 逐批处理,每批内部并发
- for (const batch of batches) {
- const promises = batch.map(async (code) => {
- try {
- const res = await deviceApi.GetList({
- page: 1,
- limit: 1,
- code: code,
- status: 1
- });
-
- if (res.data && res.data.length > 0) {
- const device = res.data[0];
- const avail = getDeviceAvailableQuantityForBorrow(device);
- if (avail <= 0) {
- return { success: false, code, message: `设备 ${code} 可借用数量为0,无法加入领取列表` };
- }
-
- // 收集设备数据,统一处理添加逻辑
- deviceMap.set(device.id, {
- device_no: device.id,
- device_code: device.code,
- device_type: device.category_name,
- device_name: device.name || '',
- borrow_count: 1,
- brand: device.brand || device.device_brand || '',
- device_specification: device.specification,
- model: device.model || '',
- warehouse: device.warehouse,
- available_quantity: avail
- });
- processedCodes.add(code);
- return { success: true, code, deviceId: device.id };
- } else {
- return { success: false, code, message: `未找到设备编号: ${code}` };
- }
- } catch (error) {
- console.error(`处理设备编号 ${code} 失败:`, error);
- return { success: false, code, message: `处理设备编号 ${code} 失败` };
- }
- });
-
- // 等待当前批次完成
- const results = await Promise.allSettled(promises);
-
- // 统计结果(先不处理添加,只统计)
- results.forEach((result, index) => {
- const { success, message } = readSettledListStepResult(result, batch[index] ?? String(index));
- if (success) {
- /* 暂时不增加计数,等统一处理后再统计 */
- } else {
- failCount++;
- if (message) {
- errorMessages.push(message);
- }
- }
- });
- }
-
- // 统一处理设备添加,避免并发竞态条件
- deviceMap.forEach((deviceData, deviceId) => {
- // 再次检查是否已存在(防止在并发过程中被其他请求添加)
- const existingDevice = deviceList.value.find(d => d.device_no === deviceId);
- if (existingDevice) {
- // 如果已存在,增加借用数量
- existingDevice.borrow_count++;
- successCount++;
- } else {
- // 如果不存在,添加新设备
- deviceList.value.push(deviceData);
- successCount++;
- }
- });
-
- // 显示批量处理结果
- if (uniqueCodes.length > 1) {
- if (successCount > 0 && failCount === 0) {
- ElMessage.success(`成功添加 ${successCount} 个设备`);
- } else if (successCount > 0 && failCount > 0) {
- ElMessage.warning(`成功添加 ${successCount} 个设备,失败 ${failCount} 个`);
- // 只显示前3个错误信息,避免消息过多
- if (errorMessages.length > 0) {
- console.warn('批量处理错误详情:', errorMessages.slice(0, 3));
- }
- } else if (failCount > 0) {
- ElMessage.error(`添加失败,共 ${failCount} 个设备编号`);
- }
- } else if (successCount > 0) {
- ElMessage.success('设备已添加到列表');
- } else if (failCount > 0 && errorMessages.length > 0) {
- ElMessage.warning(errorMessages[0]);
- }
- } catch (error) {
- console.error('批量处理设备失败:', error);
- ElMessage.error('搜索设备失败');
- } finally {
- searchText.value = ''; // 清空搜索框
- loading.value = false;
- // 重新聚焦输入框,保持选中状态
- nextTick(() => {
- if (searchInputRef.value) {
- searchInputRef.value.focus();
- searchInputRef.value.select();
- }
- });
- }
- };
- // 处理归还流程RFID标签数组,逐个检索并提交
- const processReturnRfidTagArray = async () => {
- if (returnRfidTagArray.value.length === 0 || isProcessingReturnTagArray.value) return;
-
- isProcessingReturnTagArray.value = true;
-
- // 使用 try-finally 确保状态总是被重置
- try {
- // 复制标签数组并清空,避免在处理过程中被修改
- const tagsToProcess = [...returnRfidTagArray.value];
- returnRfidTagArray.value = [];
-
- console.log(`[processReturnRfidTagArray] 开始处理归还标签,收到 ${tagsToProcess.length} 个标签:`, tagsToProcess);
-
- // 去重处理:过滤掉正在处理或已处理的标签
- // 注意:不要在这里就添加到 returnProcessingTags,而是在实际开始处理时才添加
- const uniqueTagsToProcess = tagsToProcess.filter(tag => {
- const trimmedTag = tag.trim();
- if (!trimmedTag) return false;
- // 只跳过正在处理的标签,不在这里添加
- const shouldProcess = !returnProcessingTags.value.has(trimmedTag);
- if (!shouldProcess) {
- console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 正在处理中,跳过`);
- }
- return shouldProcess;
- });
-
- console.log(`[processReturnRfidTagArray] 去重后需要处理 ${uniqueTagsToProcess.length} 个标签:`, uniqueTagsToProcess);
-
- // 逐个处理标签
- for (let i = 0; i < uniqueTagsToProcess.length; i++) {
- const tag = uniqueTagsToProcess[i];
- if (!tag || !tag.trim()) {
- console.log(`[processReturnRfidTagArray] 跳过空标签: ${tag}`);
- continue;
- }
-
- const trimmedTag = tag.trim();
-
- // 在处理前检查并添加到 returnProcessingTags,防止重复处理
- if (returnProcessingTags.value.has(trimmedTag)) {
- console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 正在处理中,跳过`);
- continue;
- }
- returnProcessingTags.value.add(trimmedTag);
-
- console.log(`[processReturnRfidTagArray] 开始处理归还标签 ${i + 1}/${uniqueTagsToProcess.length}: ${trimmedTag}`);
-
- // 确保每个标签处理前状态都是干净的
- returnSearchText.value = '';
- loading.value = false;
-
- try {
- // 设置搜索文本
- returnSearchText.value = trimmedTag;
-
- // 分割多个设备编号
- const codes = splitDeviceCodes(returnSearchText.value);
- console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 分割后得到 ${codes.length} 个代码:`, codes);
-
- if (codes.length === 0) {
- // 如果分割后没有有效代码,从 returnProcessingTags 中移除并继续处理下一个标签
- returnProcessingTags.value.delete(trimmedTag);
- console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 分割后没有有效代码,跳过`);
- continue;
- }
-
- const uniqueCodes = Array.from(new Set(codes.map(code => code.trim()))).filter(Boolean);
- console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 去重后得到 ${uniqueCodes.length} 个唯一代码:`, uniqueCodes);
-
- if (uniqueCodes.length === 0) {
- // 如果没有有效代码,从 returnProcessingTags 中移除并继续处理下一个标签
- returnProcessingTags.value.delete(trimmedTag);
- console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 没有有效代码,跳过`);
- continue;
- }
-
- loading.value = true;
- let successCount = 0;
- let failCount = 0;
- const errorMessages: string[] = [];
-
- // 批量并发处理设备编号(使用 Promise.allSettled 确保所有请求都完成)
- const batchSize = 10;
- const batches: string[][] = [];
- for (let j = 0; j < uniqueCodes.length; j += batchSize) {
- batches.push(uniqueCodes.slice(j, j + batchSize));
- }
-
- // 逐批处理,每批内部并发
- for (const batch of batches) {
- try {
- const promises = batch.map(async (code) => {
- try {
- const res = await deviceApi.GetList({
- page: 1,
- limit: 1,
- code: code,
- status: 1
- });
-
- if (res.data && res.data.length > 0) {
- const device = res.data[0];
- // 检查是否已存在
- const existingDeviceIndex = returnDeviceList.value.findIndex(d => d.device_no === device.id);
- if (existingDeviceIndex !== -1) {
- const row = returnDeviceList.value[existingDeviceIndex];
- const errMsg = tryApplyReturnScanIncrement(row);
- if (errMsg) {
- return { success: false, code, message: errMsg };
- }
- return { success: true, code };
- } else {
- // 设备不存在于归还列表中
- return {
- success: false,
- code,
- message: `设备 ${device.code || device.category_name} 不在当前归还列表中,请先通过手动归还添加该设备`
- };
- }
- } else {
- return { success: false, code, message: `未找到设备编号: ${code}` };
- }
- } catch (error) {
- console.error(`处理设备编号 ${code} 失败:`, error);
- return { success: false, code, message: `处理设备编号 ${code} 失败` };
- }
- });
-
- // 等待当前批次完成
- const results = await Promise.allSettled(promises);
-
- // 统计结果
- results.forEach((result, index) => {
- const { success, message } = readSettledListStepResult(result, batch[index] ?? String(index));
- if (success) {
- successCount++;
- } else {
- failCount++;
- if (message) {
- errorMessages.push(message);
- }
- }
- });
- } catch (batchError) {
- // 即使某批处理失败,也继续处理下一批
- console.error(`处理批次失败:`, batchError);
- failCount += batch.length;
- errorMessages.push(
- `处理批次时发生错误${
- batchError instanceof Error ? `:${batchError.message}` : ''
- }`
- );
- }
- }
-
- // 显示处理结果
- console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 处理完成: 成功 ${successCount} 个,失败 ${failCount} 个`);
-
- if (uniqueCodes.length > 1) {
- if (successCount > 0 && failCount === 0) {
- ElMessage.success(`标签 ${trimmedTag}: 成功增加 ${successCount} 个设备的归还数量`);
- } else if (successCount > 0 && failCount > 0) {
- ElMessage.warning(`标签 ${trimmedTag}: 成功增加 ${successCount} 个设备的归还数量,失败 ${failCount} 个`);
- if (errorMessages.length > 0) {
- console.warn('[processReturnRfidTagArray] 批量处理错误详情:', errorMessages.slice(0, 3));
- }
- } else if (failCount > 0) {
- ElMessage.error(`标签 ${trimmedTag}: 处理失败,共 ${failCount} 个设备编号`);
- }
- } else if (successCount > 0) {
- ElMessage.success(`标签 ${trimmedTag}: 已增加 1 个归还数量`);
- } else if (failCount > 0 && errorMessages.length > 0) {
- ElMessage.warning(`标签 ${trimmedTag}: ${errorMessages[0]}`);
- }
-
- // 处理成功后,从 returnProcessingTags 中移除,允许后续再次处理(如果需要)
- // 但保留一段时间,防止立即重复处理
- setTimeout(() => {
- returnProcessingTags.value.delete(trimmedTag);
- }, 5000);
-
- console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 处理完成,继续处理下一个标签`);
-
- // 每个标签处理完后稍作延迟,避免请求过快
- if (uniqueTagsToProcess.length > 1 && i < uniqueTagsToProcess.length - 1) {
- await new Promise(resolve => setTimeout(resolve, 100));
- }
- } catch (error) {
- // 即使某个标签处理失败,也要继续处理其他标签
- console.error(`[processReturnRfidTagArray] 处理归还标签 ${trimmedTag} 失败:`, error);
- const errorMsg = error instanceof Error ? error.message : String(error);
- ElMessage.error(`处理标签 ${trimmedTag} 失败: ${errorMsg}`);
- // 从 returnProcessingTags 中移除失败的标签,允许后续重试
- returnProcessingTags.value.delete(trimmedTag);
- console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 处理失败,继续处理下一个标签`);
- // 确保即使出错也继续处理下一个标签
- } finally {
- // 确保每个标签处理完后都重置状态,无论成功还是失败
- try {
- returnSearchText.value = '';
- loading.value = false;
- console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 状态已重置,准备处理下一个标签`);
- } catch (stateError) {
- console.error(`[processReturnRfidTagArray] 重置状态失败:`, stateError);
- }
- }
- }
-
- // 所有标签处理完成后,清理处理标志并重新聚焦输入框
- console.log(`[processReturnRfidTagArray] 所有归还标签处理完成,共处理 ${uniqueTagsToProcess.length} 个标签,标签列表:`, uniqueTagsToProcess);
- console.log(`[processReturnRfidTagArray] 当前归还设备列表中的设备数量:`, returnDeviceList.value.length);
-
- } catch (outerError) {
- // 捕获整个处理过程中的任何未预期错误,确保状态被重置
- console.error(`[processReturnRfidTagArray] 处理过程中发生未预期错误:`, outerError);
- ElMessage.error('处理归还标签时发生错误,但已尝试处理所有标签');
- } finally {
- // 确保无论发生什么,状态都被重置
- isProcessingReturnTagArray.value = false;
- loading.value = false;
- returnSearchText.value = '';
-
- // 清理处理中的标签标记(延迟清理,避免立即重复处理)
- setTimeout(() => {
- returnProcessingTags.value.clear();
- }, 1000);
- }
-
- nextTick(() => {
- if (returnSearchInputRef.value) {
- returnSearchInputRef.value.focus();
- returnSearchInputRef.value.select();
- }
- });
- };
- // 提交归还流程RFID缓冲区内容
- const submitReturnRFIDBuffer = () => {
- if (!readRuleConfig.value.enableRFIDBuffer) {
- // 如果未启用RFID缓冲,直接使用 returnSearchText 进行搜索
- if (returnSearchText.value.trim()) {
- handleReturnScanSearch();
- }
- return;
- }
-
- // 如果有标签数组,优先处理标签数组
- if (returnRfidTagArray.value.length > 0) {
- clearReturnRFIDInputTimer();
- returnConsecutiveInputCount = 0;
- returnLastInputTime = 0;
- processReturnRfidTagArray();
- return;
- }
-
- if (!returnRfidInputBuffer.value && !returnCurrentRfidTag.value) {
- // 如果没有缓冲内容,使用 returnSearchText 进行搜索
- if (returnSearchText.value.trim()) {
- handleReturnScanSearch();
- }
- return;
- }
-
- // 如果有当前标签,先添加到标签数组(去重)
- if (returnCurrentRfidTag.value.trim()) {
- const tag = returnCurrentRfidTag.value.trim();
- if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
- returnRfidTagArray.value.push(tag);
- }
- returnCurrentRfidTag.value = '';
- }
-
- // 如果有缓冲内容,也添加到标签数组(去重)
- if (returnRfidInputBuffer.value.trim()) {
- const tag = returnRfidInputBuffer.value.trim();
- if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
- returnRfidTagArray.value.push(tag);
- }
- returnRfidInputBuffer.value = '';
- }
-
- clearReturnRFIDInputTimer();
- returnConsecutiveInputCount = 0;
- returnLastInputTime = 0;
-
- // 处理标签数组
- if (returnRfidTagArray.value.length > 0) {
- processReturnRfidTagArray();
- }
- };
- // 调度归还流程RFID缓冲区提交(延迟提交)
- const scheduleReturnRFIDBufferSubmit = () => {
- if (!readRuleConfig.value.enableRFIDBuffer) return;
- clearReturnRFIDInputTimer();
- const delay = Math.max(readRuleConfig.value.rfidInputTimeout || 120, 30);
- returnRfidInputTimer = setTimeout(() => {
- console.log(`[scheduleReturnRFIDBufferSubmit] 延迟提交触发,当前状态:`, {
- returnCurrentRfidTag: returnCurrentRfidTag.value,
- returnRfidInputBuffer: returnRfidInputBuffer.value,
- returnSearchText: returnSearchText.value,
- returnRfidTagArray: returnRfidTagArray.value
- });
-
- // 如果 returnSearchText 中有内容,优先检查是否包含多个标签(通过换行、回车等分隔)
- if (returnSearchText.value.trim()) {
- const codes = splitDeviceCodes(returnSearchText.value);
- console.log(`[scheduleReturnRFIDBufferSubmit] returnSearchText 分割得到 ${codes.length} 个代码:`, codes, '原始内容长度:', returnSearchText.value.length);
-
- // 无论有多少个标签,都添加到标签数组
- if (codes.length > 0) {
- codes.forEach(code => {
- const trimmedCode = code.trim();
- if (trimmedCode && !returnRfidTagArray.value.includes(trimmedCode) && !returnProcessingTags.value.has(trimmedCode)) {
- returnRfidTagArray.value.push(trimmedCode);
- console.log(`[scheduleReturnRFIDBufferSubmit] 添加标签到数组: ${trimmedCode}`);
- }
- });
- returnSearchText.value = '';
- }
- }
-
- // 如果当前标签有内容,先保存到标签数组(去重)
- if (returnCurrentRfidTag.value.trim()) {
- const tag = returnCurrentRfidTag.value.trim();
- if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
- returnRfidTagArray.value.push(tag);
- console.log(`[scheduleReturnRFIDBufferSubmit] 添加当前标签到数组: ${tag}`);
- }
- returnCurrentRfidTag.value = '';
- }
- // 如果有缓冲内容,也添加到标签数组(去重)
- if (returnRfidInputBuffer.value.trim()) {
- const tag = returnRfidInputBuffer.value.trim();
- if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
- returnRfidTagArray.value.push(tag);
- console.log(`[scheduleReturnRFIDBufferSubmit] 添加缓冲标签到数组: ${tag}`);
- }
- returnRfidInputBuffer.value = '';
- }
-
- console.log(`[scheduleReturnRFIDBufferSubmit] 延迟提交时,标签数组共有 ${returnRfidTagArray.value.length} 个标签:`, returnRfidTagArray.value);
-
- // 处理标签数组,使用统一的延迟处理机制
- if (returnRfidTagArray.value.length > 0) {
- // 清除之前的延迟处理定时器(如果存在)
- clearReturnProcessTagArrayTimer();
-
- // 设置统一的延迟处理,确保所有标签都被收集后再处理
- returnProcessTagArrayTimer = setTimeout(() => {
- returnProcessTagArrayTimer = null;
- if (returnRfidTagArray.value.length > 0 && !isProcessingReturnTagArray.value) {
- console.log(`[scheduleReturnRFIDBufferSubmit] 延迟处理,最终标签数组:`, returnRfidTagArray.value);
- processReturnRfidTagArray();
- }
- }, 300); // 增加延迟时间到300ms,确保所有标签都被收集
- }
- }, delay);
- };
- // 处理归还设备输入(用于同步 textarea 内容,仅在缓冲模式下使用)
- const handleReturnDeviceInput = () => {
- // 如果启用了RFID缓冲,检查 returnSearchText 中是否包含多个标签(通过换行、回车等分隔)
- if (readRuleConfig.value.enableRFIDBuffer && returnSearchText.value.trim()) {
- // 检查是否包含换行符或回车符
- if (/[\r\n]/.test(returnSearchText.value)) {
- // 如果包含换行符,说明可能有多个标签
- const codes = splitDeviceCodes(returnSearchText.value);
- console.log(`[handleReturnDeviceInput] 检测到换行符,分割得到 ${codes.length} 个代码:`, codes, '原始内容长度:', returnSearchText.value.length, '原始内容:', returnSearchText.value.substring(0, 200));
-
- // 无论有多少个标签,都添加到标签数组(包括单个标签的情况)
- if (codes.length > 0) {
- codes.forEach(code => {
- const trimmedCode = code.trim();
- if (trimmedCode && !returnRfidTagArray.value.includes(trimmedCode) && !returnProcessingTags.value.has(trimmedCode)) {
- returnRfidTagArray.value.push(trimmedCode);
- console.log(`[handleReturnDeviceInput] 添加标签到数组: ${trimmedCode}`);
- }
- });
- console.log(`[handleReturnDeviceInput] 标签数组共有 ${returnRfidTagArray.value.length} 个标签:`, returnRfidTagArray.value);
- // 清空 returnSearchText,避免重复处理
- returnSearchText.value = '';
- // 清空当前标签和缓冲区,因为已经添加到数组了
- returnCurrentRfidTag.value = '';
- returnRfidInputBuffer.value = '';
- // 如果有标签数组且当前没有在处理,使用统一的延迟处理机制
- if (returnRfidTagArray.value.length > 0 && !isProcessingReturnTagArray.value) {
- clearReturnRFIDInputTimer();
-
- // 清除之前的延迟处理定时器(如果存在)
- clearReturnProcessTagArrayTimer();
-
- // 设置统一的延迟处理,确保所有标签都被收集后再处理
- returnProcessTagArrayTimer = setTimeout(() => {
- returnProcessTagArrayTimer = null;
- if (returnRfidTagArray.value.length > 0 && !isProcessingReturnTagArray.value) {
- console.log(`[handleReturnDeviceInput] 延迟处理,最终标签数组:`, returnRfidTagArray.value);
- processReturnRfidTagArray();
- }
- }, 300); // 增加延迟时间到300ms,确保所有标签都被收集
- }
- return;
- }
- }
- }
-
- // 如果缓冲区有内容,确保 textarea 显示与缓冲区一致
- // 这主要用于处理退格键等操作后的同步
- if (returnCurrentRfidTag.value || returnRfidInputBuffer.value) {
- const displayValue = returnCurrentRfidTag.value || returnRfidInputBuffer.value;
- if (returnSearchText.value !== displayValue) {
- returnSearchText.value = displayValue;
- }
- }
- // 注意:正常输入时,不干预 textarea 的内容,让默认行为处理
- };
- // 检测归还流程是否是高速扫码输入(通过输入速度判断)
- // 返回值:{ isHighSpeed: boolean, isFirstInput: boolean, timeSinceLastInput: number }
- const checkReturnInputSpeed = () => {
- const now = Date.now();
- const timeSinceLastInput = returnLastInputTime > 0 ? now - returnLastInputTime : 0;
- const isFirstInput = returnLastInputTime === 0;
-
- if (!isFirstInput) {
- returnLastInputTime = now;
- }
-
- return {
- isFirstInput,
- timeSinceLastInput,
- isHighSpeed: timeSinceLastInput > 0 && timeSinceLastInput < readRuleConfig.value.minInputSpeed,
- isNormalInput: timeSinceLastInput > 200
- };
- };
- // 处理归还流程RFID键盘输入(高速扫码)
- const handleReturnRFIDKeydown = (event: KeyboardEvent) => {
- // 如果未启用RFID缓冲,直接返回,不拦截
- if (!readRuleConfig.value.enableRFIDBuffer) {
- return;
- }
-
- // 不拦截修饰键组合(如 Ctrl+C, Ctrl+V 等)
- if (event.ctrlKey || event.metaKey || event.altKey) {
- return;
- }
-
- // 处理回车键
- if (event.key === 'Enter') {
- // 回车键由 @keydown.enter.prevent="handleReturnDeviceEnter" 处理
- // 这里不处理,让 handleReturnDeviceEnter 统一处理
- return;
- }
-
- // 处理退格键
- if (event.key === 'Backspace') {
- // 如果有当前标签或缓冲内容,处理缓冲
- if (returnCurrentRfidTag.value || returnRfidInputBuffer.value) {
- event.preventDefault();
- if (returnCurrentRfidTag.value) {
- returnCurrentRfidTag.value = returnCurrentRfidTag.value.slice(0, -1);
- returnRfidInputBuffer.value = returnCurrentRfidTag.value;
- } else {
- returnRfidInputBuffer.value = returnRfidInputBuffer.value.slice(0, -1);
- }
- returnSearchText.value = returnRfidInputBuffer.value || returnCurrentRfidTag.value;
- }
- // 否则让默认行为处理
- return;
- }
-
- // 处理普通字符输入
- if (event.key.length === 1) {
- const inputInfo = checkReturnInputSpeed();
- const { isFirstInput, isHighSpeed, isNormalInput, timeSinceLastInput } = inputInfo;
-
- // 如果是第一次输入,不拦截,让默认行为处理,只记录时间戳
- if (isFirstInput) {
- returnLastInputTime = Date.now();
- // 不拦截,让字符正常输入到 textarea
- return;
- }
-
- // 如果检测到是正常输入(间隔 > 200ms),处理之前的缓冲内容
- if (isNormalInput) {
- // 如果之前有当前标签或缓冲内容,先保存到标签数组(去重)
- if (returnCurrentRfidTag.value.trim()) {
- const tag = returnCurrentRfidTag.value.trim();
- if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
- returnRfidTagArray.value.push(tag);
- }
- returnCurrentRfidTag.value = '';
- }
- if (returnRfidInputBuffer.value.trim()) {
- const tag = returnRfidInputBuffer.value.trim();
- if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
- returnRfidTagArray.value.push(tag);
- }
- returnRfidInputBuffer.value = '';
- }
- // 如果有标签数组,处理它们
- if (returnRfidTagArray.value.length > 0) {
- processReturnRfidTagArray();
- }
- // 重置状态
- returnConsecutiveInputCount = 0;
- returnLastInputTime = Date.now();
- // 不拦截,让字符正常输入到 textarea
- return;
- }
-
- // 如果检测到是高速输入(间隔 < 30ms),使用缓冲模式
- if (isHighSpeed) {
- event.preventDefault();
- event.stopPropagation(); // 阻止事件冒泡,避免影响其他元素
-
- // 如果输入间隔超过标签分隔时间,说明是一个新标签的开始
- // 需要保存之前的标签到数组
- if (timeSinceLastInput > readRuleConfig.value.tagSeparatorTimeout) {
- // 保存当前标签到数组(如果存在且去重)
- if (returnCurrentRfidTag.value.trim()) {
- const tag = returnCurrentRfidTag.value.trim();
- if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
- returnRfidTagArray.value.push(tag);
- }
- returnCurrentRfidTag.value = '';
- }
- // 保存缓冲内容到数组(如果存在且去重)
- if (returnRfidInputBuffer.value.trim()) {
- const tag = returnRfidInputBuffer.value.trim();
- if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
- returnRfidTagArray.value.push(tag);
- }
- returnRfidInputBuffer.value = '';
- }
- // 如果 textarea 中有内容,检查是否需要添加到数组(去重)
- if (returnSearchText.value.trim()) {
- const codes = splitDeviceCodes(returnSearchText.value);
- codes.forEach(code => {
- const trimmedCode = code.trim();
- if (trimmedCode && !returnRfidTagArray.value.includes(trimmedCode) && !returnProcessingTags.value.has(trimmedCode)) {
- returnRfidTagArray.value.push(trimmedCode);
- }
- });
- returnSearchText.value = ''; // 清空 searchText,避免重复处理
- }
- // 重置,开始新标签
- returnCurrentRfidTag.value = event.key;
- returnRfidInputBuffer.value = event.key;
- returnSearchText.value = event.key;
- } else {
- // 如果是第一次检测到高速输入(之前没有缓冲内容),需要将 textarea 中已有的内容也加入当前标签
- if (returnCurrentRfidTag.value === '' && returnRfidInputBuffer.value === '' && returnSearchText.value) {
- // textarea 中已经有内容(第一个字符已经通过默认行为输入了)
- // 将整个内容作为当前标签的初始值,然后追加当前字符
- returnCurrentRfidTag.value = returnSearchText.value + event.key;
- } else {
- // 否则直接追加当前字符到当前标签
- returnCurrentRfidTag.value += event.key;
- }
-
- // 同时更新缓冲区和显示
- returnRfidInputBuffer.value = returnCurrentRfidTag.value;
- returnSearchText.value = returnCurrentRfidTag.value;
- }
-
- returnConsecutiveInputCount++;
- scheduleReturnRFIDBufferSubmit();
- return;
- }
-
- // 如果输入间隔在 30-200ms 之间,可能是正常输入,不拦截
- // 但如果之前有缓冲内容,说明高速输入已结束,先保存当前标签(去重)
- if (returnCurrentRfidTag.value.trim() || returnRfidInputBuffer.value.trim()) {
- if (returnCurrentRfidTag.value.trim()) {
- const tag = returnCurrentRfidTag.value.trim();
- if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
- returnRfidTagArray.value.push(tag);
- }
- returnCurrentRfidTag.value = '';
- }
- if (returnRfidInputBuffer.value.trim()) {
- const tag = returnRfidInputBuffer.value.trim();
- if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
- returnRfidTagArray.value.push(tag);
- }
- returnRfidInputBuffer.value = '';
- }
- // 处理标签数组
- if (returnRfidTagArray.value.length > 0) {
- processReturnRfidTagArray();
- }
- returnConsecutiveInputCount = 0;
- }
- returnLastInputTime = Date.now();
- // 不拦截,让字符正常输入到 textarea
- }
- };
- // 处理归还输入框失焦
- const handleReturnDeviceBlur = (event: FocusEvent) => {
- // 如果焦点转移到其他输入元素(如表单输入框),不自动聚焦
- const relatedTarget = event.relatedTarget as HTMLElement;
- if (relatedTarget && (
- relatedTarget.tagName === 'INPUT' ||
- relatedTarget.tagName === 'TEXTAREA' ||
- relatedTarget.closest('.el-input') ||
- relatedTarget.closest('.el-textarea') ||
- relatedTarget.closest('form')
- )) {
- // 如果有缓冲内容,先提交
- if (returnRfidInputBuffer.value) {
- submitReturnRFIDBuffer();
- }
- return;
- }
-
- // 其他情况(如点击按钮等),延迟后自动聚焦
- setTimeout(() => {
- if (returnSearchInputRef.value && !loading.value) {
- returnSearchInputRef.value.focus();
- }
- }, 10);
- };
- // 处理归还回车键
- const handleReturnDeviceEnter = (event: KeyboardEvent) => {
- if (event.shiftKey) return;
- event.preventDefault();
-
- // 如果启用了RFID缓冲,先检查是否有当前标签或缓冲内容
- if (readRuleConfig.value.enableRFIDBuffer) {
- // 如果有当前标签,先保存到标签数组(去重)
- if (returnCurrentRfidTag.value.trim()) {
- const tag = returnCurrentRfidTag.value.trim();
- if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
- returnRfidTagArray.value.push(tag);
- }
- returnCurrentRfidTag.value = '';
- }
- // 如果有缓冲内容,也添加到标签数组(去重)
- if (returnRfidInputBuffer.value.trim()) {
- const tag = returnRfidInputBuffer.value.trim();
- if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
- returnRfidTagArray.value.push(tag);
- }
- returnRfidInputBuffer.value = '';
- }
- }
-
- // 检查 returnSearchText 中是否包含多个标签(通过换行、回车等分隔)
- if (returnSearchText.value.trim()) {
- const codes = splitDeviceCodes(returnSearchText.value);
- console.log(`[handleReturnDeviceEnter] 回车键提交时,returnSearchText 分割得到 ${codes.length} 个代码:`, codes, '原始内容长度:', returnSearchText.value.length, '原始内容:', returnSearchText.value.substring(0, 500));
-
- // 将所有标签添加到数组(包括单个标签的情况)
- codes.forEach(code => {
- const trimmedCode = code.trim();
- if (trimmedCode && !returnRfidTagArray.value.includes(trimmedCode) && !returnProcessingTags.value.has(trimmedCode)) {
- returnRfidTagArray.value.push(trimmedCode);
- console.log(`[handleReturnDeviceEnter] 添加标签到数组: ${trimmedCode}`);
- }
- });
- returnSearchText.value = '';
- }
-
- console.log(`[handleReturnDeviceEnter] 回车键提交时,标签数组共有 ${returnRfidTagArray.value.length} 个标签:`, returnRfidTagArray.value);
-
- // 如果有标签数组,使用统一的延迟处理机制,避免多次触发
- if (returnRfidTagArray.value.length > 0) {
- clearReturnRFIDInputTimer();
- returnConsecutiveInputCount = 0;
- returnLastInputTime = 0;
-
- // 清除之前的延迟处理定时器(如果存在)
- clearReturnProcessTagArrayTimer();
-
- // 设置统一的延迟处理,确保所有标签都被收集后再处理
- returnProcessTagArrayTimer = setTimeout(() => {
- returnProcessTagArrayTimer = null;
- if (returnRfidTagArray.value.length > 0 && !isProcessingReturnTagArray.value) {
- console.log(`[handleReturnDeviceEnter] 延迟处理,最终标签数组:`, returnRfidTagArray.value);
- processReturnRfidTagArray();
- }
- }, 300); // 增加延迟时间到300ms,确保所有标签都被收集
- return;
- }
-
- // 如果没有标签数组,使用 returnSearchText 进行搜索
- if (returnSearchText.value.trim()) {
- handleReturnScanSearch();
- }
- };
- // 处理归还扫码搜索(支持批量,优化并发请求)
- const handleReturnScanSearch = async (event?: Event) => {
- // 阻止默认行为,防止表单提交导致页面刷新
- if (event) {
- event.preventDefault();
- event.stopPropagation();
- }
-
- // 如果启用了RFID缓冲,先提交缓冲区
- if (readRuleConfig.value.enableRFIDBuffer && returnRfidInputBuffer.value) {
- const bufferedValue = returnRfidInputBuffer.value;
- returnRfidInputBuffer.value = '';
- clearReturnRFIDInputTimer();
- returnSearchText.value = bufferedValue;
- }
-
- if (!returnSearchText.value.trim()) return;
-
- // 分割多个设备编号
- const codes = splitDeviceCodes(returnSearchText.value);
- if (codes.length === 0) return;
-
- // 去重处理,避免重复请求同一个设备编号
- const uniqueCodes = Array.from(new Set(codes.map(code => code.trim()))).filter(Boolean);
- if (uniqueCodes.length === 0) return;
-
- loading.value = true;
- let successCount = 0;
- let failCount = 0;
- const errorMessages: string[] = [];
-
- try {
- // 批量并发处理设备编号(使用 Promise.allSettled 确保所有请求都完成)
- // 限制并发数量,避免同时发起过多请求
- const batchSize = 10; // 每批处理10个
- const batches: string[][] = [];
- for (let i = 0; i < uniqueCodes.length; i += batchSize) {
- batches.push(uniqueCodes.slice(i, i + batchSize));
- }
-
- // 逐批处理,每批内部并发
- for (const batch of batches) {
- const promises = batch.map(async (code) => {
- try {
- const res = await deviceApi.GetList({
- page: 1,
- limit: 1,
- code: code,
- status: 1
- });
-
- if (res.data && res.data.length > 0) {
- const device = res.data[0];
- const existingDeviceIndex = returnDeviceList.value.findIndex(d => d.device_no === device.id);
- if (existingDeviceIndex !== -1) {
- const row = returnDeviceList.value[existingDeviceIndex];
- const errMsg = tryApplyReturnScanIncrement(row);
- if (errMsg) {
- return { success: false, code, message: errMsg };
- }
- return { success: true, code };
- } else {
- // 设备不存在于归还列表中
- return {
- success: false,
- code,
- message: `设备 ${device.code || device.category_name} 不在当前归还列表中,请先通过手动归还添加该设备`
- };
- }
- } else {
- return { success: false, code, message: `未找到设备编号: ${code}` };
- }
- } catch (error) {
- console.error(`处理设备编号 ${code} 失败:`, error);
- return { success: false, code, message: `处理设备编号 ${code} 失败` };
- }
- });
-
- // 等待当前批次完成
- const results = await Promise.allSettled(promises);
-
- // 统计结果
- results.forEach((result, index) => {
- const { success, message } = readSettledListStepResult(result, batch[index] ?? String(index));
- if (success) {
- successCount++;
- } else {
- failCount++;
- if (message) {
- errorMessages.push(message);
- }
- }
- });
- }
-
- // 显示批量处理结果
- if (uniqueCodes.length > 1) {
- if (successCount > 0 && failCount === 0) {
- ElMessage.success(`成功增加 ${successCount} 个设备的归还数量`);
- } else if (successCount > 0 && failCount > 0) {
- ElMessage.warning(`成功增加 ${successCount} 个设备的归还数量,失败 ${failCount} 个`);
- // 只显示前3个错误信息,避免消息过多
- if (errorMessages.length > 0) {
- console.warn('批量处理错误详情:', errorMessages.slice(0, 3));
- }
- } else if (failCount > 0) {
- ElMessage.error(`处理失败,共 ${failCount} 个设备编号`);
- }
- } else if (successCount > 0) {
- ElMessage.success('已增加 1 个归还数量');
- } else if (failCount > 0 && errorMessages.length > 0) {
- ElMessage.warning(errorMessages[0]);
- }
- } catch (error) {
- console.error('批量处理设备失败:', error);
- ElMessage.error('搜索设备失败');
- } finally {
- returnSearchText.value = ''; // 清空搜索框
- loading.value = false;
- // 重新聚焦输入框,保持选中状态
- nextTick(() => {
- if (returnSearchInputRef.value) {
- returnSearchInputRef.value.focus();
- returnSearchInputRef.value.select();
- }
- });
- }
- };
- // 异常记录列表数据
- const abnormalList = ref([
- /* {
- borrowNo: '202409002',
- borrower: '张同学',
- time: '2024-09-12 10:21:32',
- type: '逾期'
- },
- {
- borrowNo: '202505013',
- borrower: '张同学',
- time: '2025-05-13 15:12:35',
- type: '损坏'
- } */
- ]);
- /* 归还设备异常记录 */
- const returnAbnormalList = ref([
-
- ]);
- // 附件文件列表
- const attachmentFileList = ref<any[]>([]);
- // 查看异常记录详情
- const handleView = (row: any) => {
- console.log('查看异常记录:', row);
- // 这里可以添加查看详情的逻辑
- };
- const selectedDeviceCodes = ref<any[]>([]);
- // 计算已选中设备的ID列表(用于禁用已选中的设备)
- const disabledDeviceIds = computed(() => {
- if (activeName.value === 'first') {
- // first tab: 从 form.value.items 中获取 device ID
- return form.value.items.map((item: any) => item.device).filter(Boolean);
- } else if (activeName.value === 'second') {
- // second tab: 从 deviceList.value 中获取 device_no ID
- return deviceList.value.map((item: any) => item.device_no).filter(Boolean);
- }
- // third tab (归还模式) 不需要禁用,因为已经有特殊的处理逻辑
- return [];
- });
- // 借用列表相关方法
- const handleAdd = () => {
- if (activeName.value === 'third' && allReturned.value) {
- ElMessage.info('当前列表设备均已归还,无可选择设备');
- return;
- }
- if(activeName.value === 'third'){
- selectedDeviceCodes.value = [];
- returnDeviceList.value.forEach(item => {
- console.log("item:::",item);
- if(item.device_no){
- selectedDeviceCodes.value.push(item.device_code);
- }
- });
- console.log("selectedDeviceCodes.value:::",selectedDeviceCodes.value);
- }
- showSelectDeviceDialog.value = true;
- };
- const handleRemove = (index: number) => {
- deviceList.value.splice(index, 1);
- };
- const handleReturnRemove = (index: number) => {
- returnDeviceList.value.splice(index, 1);
- };
- // 处理表格多选变化
- const handleSelectionChange = (selection: DeviceListItem[]) => {
- selectedDevices.value = selection;
- };
- // 设备选择处理
- function onDeviceSelected(devices: Device[]) {
- console.log("devices:::",devices,"activeName:::",activeName.value);
- if (activeName.value === 'first') {
- // 获取已存在的设备ID列表
- const existingIds = new Set(form.value.items.map((item: any) => item.device).filter(Boolean));
-
- // 过滤掉已存在的设备,只添加新的
- const newDevices = devices.filter((d) => !existingIds.has(d.id));
-
- if (newDevices.length === 0) {
- ElMessage.warning('所选设备已存在,未添加重复项');
- return;
- }
-
- // 如果有部分重复,提示用户
- if (newDevices.length < devices.length) {
- ElMessage.warning(`已过滤 ${devices.length - newDevices.length} 个重复的设备`);
- }
-
- form.value.items.push(
- ...newDevices.map((d) => ({
- device: d.id,
- device_code: d.code,
- remark: d.category_name,
- quantity: 1,
- location: d.warehouse,
- device_name: d.name,
- device_specification: d.device_specification
- }))
- );
- } else if (activeName.value === 'second') {
- // 获取已存在的设备ID列表
- const existingIds = new Set(deviceList.value.map((item: any) => item.device_no).filter(Boolean));
-
- // 过滤掉已存在的设备,只添加新的
- const newDevices = devices.filter((d) => !existingIds.has(d.id));
-
- if (newDevices.length === 0) {
- ElMessage.warning('所选设备已存在,未添加重复项');
- return;
- }
-
- // 如果有部分重复,提示用户
- if (newDevices.length < devices.length) {
- ElMessage.warning(`已过滤 ${devices.length - newDevices.length} 个重复的设备`);
- }
-
- deviceList.value.push(
- ...newDevices.map(d => ({
- device_no: d.id,
- device_code: d.code,
- device_type: d.category_name,
- device_name: d.name || '',
- borrow_count: 1,
- brand: d.brand || '',
- model: d.model,
- device_specification: d.specification,
- warehouse: d.warehouse,
- available_quantity:d.available_quantity
- }))
- );
- }else if(activeName.value === 'third'){
- // 在添加前检查每个设备是否已存在;手动选设备:将本次归还数量记满至「待归还」上限
- devices.forEach(d => {
- const existingDeviceIndex = returnDeviceList.value.findIndex(item => item.device_no === d.id);
- if (existingDeviceIndex !== -1) {
- const row = returnDeviceList.value[existingDeviceIndex];
- const cap = row.available_quantity ?? 0;
- if (cap <= 0) {
- ElMessage.warning('该设备无待归还数量');
- return;
- }
- row.borrow_count = cap;
- row.is_return = true;
- row.return_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
- row.brand = d.brand || row.brand || '';
- if (row.return_status) {
- row.return_status = { value: 2, label: '已归还' };
- }
- touchReturnRowSort(row);
- ElMessage.success(`已将该设备本次归还记为 ${cap} 件`);
- } else {
- // 如果设备不存在,添加新记录
- /* returnDeviceList.value.push({
- device_no: d.id,
- device_type: d.category_name,
- device_name: d.name || '',
- borrow_count: 1,
- brand: d.brand || '',
- model: d.model || '',
- warehouse: d.warehouse,
- status: '已归还'
- }); */
- /* ElMessage.success(`设备 ${d.category_name} 已添加到归还列表`); */
- }
- });
- }
- }
- // 移除同步相关的 watch
- // const handleClick = (tab: TabsPaneContext, event: Event) => {
- // if (tab.props.name === 'second') {
- // deviceList.value = form.value.items.map(item => ({
- // device_no: item.device,
- // device_type: item.remark,
- // device_name: '',
- // borrow_count: item.quantity,
- // brand: '',
- // model: '',
- // warehouse: item.location
- // }));
- // }
- // }
- function handleClick(tab: TabsPaneContext) {
- console.log('Tab clicked:', tab.props.name);
- // 当切换到设备清单标签页时,自动聚焦输入框
- if (tab.props.name === 'second') {
- nextTick(() => {
- if (searchInputRef.value) {
- searchInputRef.value.focus();
- searchInputRef.value.select();
- }
- });
- } else if (tab.props.name === 'third') {
- // 当切换到归还设备清单标签页时,自动聚焦输入框
- nextTick(() => {
- returnSearchInputRef.value?.focus?.();
- });
- }
- }
- function handleUploadSuccess(response: any, file: any, fileList: any) {
- // eslint-disable-next-line no-console
- console.log('上传成功:', file.name);
- }
- function handleUploadError(err: any, file: any, fileList: any) {
- // eslint-disable-next-line no-console
- console.error('上传失败:', file.name);
- }
- // 图片预览处理函数
- const handlePictureCardPreview = (uploadFile: any) => {
- dialogImageUrl.value = uploadFile.url || uploadFile.response?.url || form.value.attachments;
- dialogVisible.value = true;
- };
- // 处理附件删除
- const handleRemoves = (file: any, fileList: any) => {
- // 由于是禁用状态,这里只是示例,实际不会执行删除
- console.log('删除附件:', file.name);
- };
- const form = ref<FormData>({
- borrower_info:{
- user_code:'',
- mobile:''
- },
- application_no: '',
- emergency_contact: '',
- emergency_phone: '',
- app_user_borrower: { id: '', name: '', user_code: '', mobile: '' },
- team_type: 0,
- team_members_count: 1,
- team_members: '',
- expected_start_time:'',
- expected_end_time: '',
- borrower_dept: '',
- purpose: '',
- applicant_remark_type: "1",
- applicant_remark: '',
- items: [],
- accessory_info: '',
- borrow_type: 2,
- return_location:'',
- approver_info: {
- name: ''
- }
- });
- const showSelectDeviceDialog = ref(false);
- const rules = {
- emergency_contact: [
- { required: true, message: '请输入借用人', trigger: 'change' },
- ],
- app_user_borrower: [
- { required: true, message: '请输入学号或工号', trigger: 'change' },
- ],
- emergency_phone: [
- { required: true, message: '请输入联系电话', trigger: 'change' },
- ],
- /* borrower_dept: [
- { required: true, message: '请输入借用部门', trigger: 'change' },
- ], */
- expected_end_time: [
- { required: true, message: '请输选择归还时间', trigger: 'change' },
- ],
- team_type: [
- { required: true, message: '请选择个人或者团队', trigger: 'change' },
- ],
- purpose: [
- { required: true, message: '请输入借用原因', trigger: 'change' },
- ],
- applicant_remark_type: [
- { required: true, message: '请选择审批人', trigger: 'change' },
- ],
- applicant_remark: [
- { required: false, message: '请输入备注', trigger: 'change' },
- ],
- };
- // 自动填充用户信息
- onMounted(() => {
- loadWarehouses()
- getAdminList()
- getAllUserList()
- try {
- const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
- if (userInfo) {
- form.value.emergency_contact = userInfo.username || '';
- // 借用人从用户列表加载完成后再统一回显/设置
- form.value.emergency_phone = userInfo.mobile || '';
- form.value.borrower_dept = userInfo.dept_info?.dept_name || '';
- }
- } catch (e) {
- /* empty */
- }
- });
- watch(
- () => props.visible,
- (v) => {
- visible.value = v;
- // 当对话框打开且当前标签页是设备清单时,自动聚焦输入框
- if (v && activeName.value === 'second' && isCollect.value) {
- nextTick(() => {
- if (searchInputRef.value) {
- searchInputRef.value.focus();
- searchInputRef.value.select();
- }
- });
- } else if (v && activeName.value === 'third' && !isView.value) {
- // 当对话框打开且当前标签页是归还设备清单时,自动聚焦输入框
- nextTick(() => {
- returnSearchInputRef.value?.focus?.();
- });
- }
- // 清理RFID缓冲状态
- if (v) {
- rfidInputBuffer.value = '';
- currentRfidTag.value = '';
- rfidTagArray.value = [];
- clearRFIDInputTimer();
- consecutiveInputCount = 0;
- lastInputTime = 0;
- // 清空待提交的设备编号数组
- pendingDeviceCodes.value = [];
- isAutoSubmitting.value = false;
- // 清理归还流程RFID缓冲状态
- returnRfidInputBuffer.value = '';
- returnCurrentRfidTag.value = '';
- returnRfidTagArray.value = [];
- returnProcessingTags.value.clear();
- isProcessingReturnTagArray.value = false;
- clearReturnRFIDInputTimer();
- returnConsecutiveInputCount = 0;
- returnLastInputTime = 0;
- }
- }
- );
- watch(() => props.modelValue, async (val) => {
- if (val && val.id) {
- try {
- const res = await api.GetApplicationDetail(val.id);
- console.log("res:::::",res)
- if (res.code === 2000 && res.data) {
- const data = res.data;
- Object.assign(form.value, data);
- buildSteps(data);
- // 领取模式下不回显历史配件内容
- if (isCollect.value) {
- collectAccessories.value = '';
- }
- timeline.value.create = data.create_datetime ? dayjs(data.create_datetime).format('YYYY-MM-DD HH:mm:ss') : '';
- timeline.value.approve = data.approve_time || '';
- const approverinfo = data.approver_info ?? data.admin_approver_info
- timeline.value.approver = approverinfo?.name || '审批人'
- // timeline.value.approver = data.admin_approver_info?.name || '审批人';
- // console.log("data:::",form.value);
- // activeStep.value = 1; // 创建
- // if (data.status >= 1) activeStep.value = 2; // 待审批
- // if (data.status >= 2) activeStep.value = 3; // 审批通过
- // if (data.status >= 3) activeStep.value = 4; // 完成
- // 同步 form.items 到 returnDeviceList
- if (form.value.items && form.value.items.length > 0) {
- returnDeviceList.value = (form.value.items as any[])
- .filter((item) => item.device !== null)
- .map(mapFormItemToReturnDeviceListRow);
- }
- // 同步 form.records 到 returnAbnormalList
- if (form.value.records && form.value.records.length > 0) {
- // 添加损坏类型记录
- const damageRecord: AbnormalRecord = {
- application_no: form.value.application_no,
- operator_name: form.value.app_user_borrower?.name||form.value.external_borrower_name||'',
- user_code: form.value.borrower_info?.user_code || form.value.app_user_borrower?.user_code||'',
- emergency_phone: form.value.app_user_borrower?.mobile||form.value.external_borrower_phone || '',
- type: '损坏',
- condition: form.value.borrower_damage_count || 0,
- create_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
- };
- // 添加逾期类型记录
- const overdueRecord: AbnormalRecord = {
- application_no: form.value.application_no,
- operator_name: form.value.app_user_borrower?.name||form.value.external_borrower_name||'',
- user_code: form.value.borrower_info?.user_code || form.value.app_user_borrower?.user_code||'',
- emergency_phone: form.value.app_user_borrower?.mobile||form.value.external_borrower_phone || '',
- type: '逾期',
- condition: form.value.borrower_overdue_count || 0, // 逾期数量设为1
- create_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
- };
- returnAbnormalList.value = [damageRecord, overdueRecord];
- abnormalList.value = [damageRecord, overdueRecord];
- }
-
- // 处理附件回显
- if (data.attachments) {
- if (typeof data.attachments === 'string') {
- // 如果attachments是字符串URL
- attachmentFileList.value = [{
- name: data.attachments.split('/').pop() || '附件',
- url: data.attachments,
- status: 'success'
- }];
- } else if (Array.isArray(data.attachments)) {
- // 如果attachments是数组
- attachmentFileList.value = data.attachments.map((item: any, index: number) => {
- if (typeof item === 'string') {
- return {
- name: item.split('/').pop() || `附件${index + 1}`,
- url: item,
- status: 'success'
- };
- } else if (typeof item === 'object' && item.url) {
- return {
- name: item.name || item.url.split('/').pop() || `附件${index + 1}`,
- url: item.url,
- status: 'success'
- };
- }
- return null;
- }).filter(Boolean);
- }
- }
- }
- } catch (e) {
- console.log("审判失败:::",e)
- ElMessage.error('获取审批信息失败');
- }
- }else if(val&& isEdit.value){
- try {
- const res = await api.GetApplicationDetail(val.id);
- if (res.code === 2000 && res.data) {
- const data = res.data;
- Object.assign(form.value, data);
- // 同步 form.items 到 returnDeviceList
- if (form.value.items && form.value.items.length > 0) {
- returnDeviceList.value = (form.value.items as any[])
- .filter((item) => item.device !== null)
- .map(mapFormItemToReturnDeviceListRow);
- }
-
- // 处理附件回显 (编辑模式)
- if (data.attachments) {
- if (typeof data.attachments === 'string') {
- attachmentFileList.value = [{
- name: data.attachments.split('/').pop() || '附件',
- url: data.attachments,
- status: 'success'
- }];
- } else if (Array.isArray(data.attachments)) {
- attachmentFileList.value = data.attachments.map((item: any, index: number) => {
- if (typeof item === 'string') {
- return {
- name: item.split('/').pop() || `附件${index + 1}`,
- url: item,
- status: 'success'
- };
- } else if (typeof item === 'object' && item.url) {
- return {
- name: item.name || item.url.split('/').pop() || `附件${index + 1}`,
- url: item.url,
- status: 'success'
- };
- }
- return null;
- }).filter(Boolean);
- }
- }
- }
- } catch (e) {
- ElMessage.error('获取审批信息失败');
- }
- }
- }, { immediate: true });
- // watch(
- // () => props.modelValue,
- // (v) => {
- // if (v) {
- // // eslint-disable-next-line no-console
- // console.log("val:::::",v);
- // Object.assign(form.value, v);
- // }
- // }, { immediate: true }
- // );
- // 监听借用人选择变化
- watch(() => form.value.app_user_borrower?.id, (newId) => {
- if (!newId || allUserList.value.length === 0) return;
- const selectedUser: any = allUserList.value.find((u: any) => String(u.id) === String(newId));
- if (selectedUser) {
- form.value.app_user_borrower = {
- id: selectedUser.id,
- name: selectedUser.name,
- user_code: selectedUser.user_code || '',
- mobile: selectedUser.mobile || ''
- };
- }
- });
- function addItem() {
- if (activeName.value === 'third' && allReturned.value) {
- ElMessage.info('当前列表设备均已归还,无可选择设备');
- return;
- }
- showSelectDeviceDialog.value = true;
- }
- function removeItem(index: number) {
- form.value.items.splice(index, 1);
- }
- function onCancel() {
- // 重置标签页到第一个
- activeName.value = 'first';
- // 清理异常记录列表
- returnAbnormalList.value = [];
- abnormalList.value = [];
- // 清理设备列表
- deviceList.value = [];
- returnDeviceList.value = [];
- // 清理RFID相关定时器和状态
- clearRFIDInputTimer();
- clearProcessTagArrayTimer();
- clearReturnRFIDInputTimer();
- clearReturnProcessTagArrayTimer();
- rfidInputBuffer.value = '';
- currentRfidTag.value = '';
- rfidTagArray.value = [];
- returnRfidInputBuffer.value = '';
- returnCurrentRfidTag.value = '';
- returnRfidTagArray.value = [];
- processingTags.value.clear();
- returnProcessingTags.value.clear();
- isProcessingTagArray.value = false;
- isProcessingReturnTagArray.value = false;
- // 清空待提交的设备编号数组
- pendingDeviceCodes.value = [];
- isAutoSubmitting.value = false;
- consecutiveInputCount = 0;
- lastInputTime = 0;
- returnConsecutiveInputCount = 0;
- returnLastInputTime = 0;
- // 清理搜索框
- searchText.value = '';
- returnSearchText.value = '';
- // 清理备注
- remark.value = '';
- // 清理领取模式配件信息
- collectAccessories.value = '';
- returnRemark.value = '';
- // 重置状态
- returnStatus.value = '未归还';
- // 清理选中的设备
- selectedDevices.value = [];
- // 清理附件文件列表
- attachmentFileList.value = [];
- // 清理RFID缓冲
- rfidInputBuffer.value = '';
- currentRfidTag.value = '';
- rfidTagArray.value = [];
- clearRFIDInputTimer();
- consecutiveInputCount = 0;
- lastInputTime = 0;
- // 清理归还流程RFID缓冲
- returnRfidInputBuffer.value = '';
- returnCurrentRfidTag.value = '';
- returnRfidTagArray.value = [];
- returnProcessingTags.value.clear();
- isProcessingReturnTagArray.value = false;
- clearReturnRFIDInputTimer();
- returnConsecutiveInputCount = 0;
- returnLastInputTime = 0;
- // 关闭所有对话框
- showSelectDeviceDialog.value = false;
- showSettlementDialog.value = false;
- showAbnormalDialog.value = false;
- showViewAbnormalDialog.value = false;
- // 重置当前异常数据
- currentAbnormalData.value = {
- damage_type: 0,
- condition: '',
- photos: []
- };
- // 发出关闭事件
- emit('update:visible', false);
- }
- // 提交时合并数据
- function onSubmit() {
- if(isCollect.value){
- // 验证是否有设备信息
- const hasDevicesInFirstTab = form.value.items && form.value.items.length > 0;
- const hasDevicesInSecondTab = deviceList.value && deviceList.value.length > 0;
-
- if (!hasDevicesInFirstTab && !hasDevicesInSecondTab) {
- ElMessage.warning('请添加设备信息后再提交');
- activeName.value = 'second'; // 自动切换到借用列表标签页
- return;
- }
- // 验证设备数量
- const hasInvalidQuantityInFirstTab = form.value.items.some(item => !item.quantity || item.quantity <= 0);
- const hasInvalidQuantityInSecondTab = deviceList.value.some(item => !item.borrow_count || item.borrow_count <= 0);
- if (hasInvalidQuantityInFirstTab || hasInvalidQuantityInSecondTab) {
- ElMessage.warning('请确保所有设备的数量大于0');
- activeName.value = 'second'; // 自动切换到借用列表标签页
- return;
- }
- // 合并两个标签页的设备数据
- const allDevices = [
- ...deviceList.value.map(item => ({
- condition: remark.value,
- quantity: item.borrow_count,
- device_id: Number(item.device_no) || 0
- }))
- ];
-
- const submitData = {
- id:form.value.id,
- item_id:form.value.id,
- device_assignments: allDevices,
- remark:remark.value,
- pre_borrow_accessories: collectAccessories.value,
- };
- CollectEquipment(submitData).then((res: ApiResponse) => {
- if(res.code===2000){
- ElMessage.success("领取成功");
- // 准备结算单数据
- settlementData.value = {
- ...form.value,
- items: deviceList.value.map(item => ({
- ...item,
- device_category_name: item.device_type,
- device_name: item.device_name,
- device_specification: item.device_specification,
- device_storage_location: getWarehouseName(item.warehouse) || item.warehouse,
- remark: item.device_type,
- quantity: item.borrow_count,
- device_id: item.device_no,
- device_category: item.device_type,
- device_code: item.device_no,
- borrow_type: form.value.borrow_type,
- borrower_dept: form.value.borrower_dept,
- emergency_contact: form.value.emergency_contact,
- emergency_phone: form.value.emergency_phone,
- team_type: form.value.team_type,
- })),
- accessory_info: accessoryInfo.value,
- pre_borrow_accessories:collectAccessories.value,
- remark: remark.value,
- expected_start_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
- };
-
- // 先触发提交事件进行页面刷新
- emit('submit');
-
- // 关闭当前对话框
- emit('update:visible', false);
-
- // 使用 nextTick 确保在 DOM 更新后再显示结算单
- nextTick(() => {
- borrowForm.value = {...settlementData.value,mode: 'settlement' };
- showSettlementDialog.value = true;
- });
- }
- });
- } else {
- // 归还:按每行「归还数量」提交,须大于 0 且不超过待归还
- const toReturn = returnDeviceList.value.filter(
- (item) => (Number(item.borrow_count) || 0) > 0
- );
- if (toReturn.length === 0) {
- ElMessage.warning('请通过扫码/输入填写归还数量,或从手动归还中确认设备');
- return;
- }
- const over = toReturn.find(
- (item) => (Number(item.borrow_count) || 0) > (Number(item.available_quantity) || 0)
- );
- if (over) {
- ElMessage.error('存在归还数量超过待归还数量,请检查');
- return;
- }
- const allDevices = toReturn.map((item) => ({
- device: item.device_no,
- quantity: item.borrow_count,
- remark: returnRemark.value,
- device_id: Number(item.device_no) || 0,
- condition: item.condition,
- damage_type: item.damage_type,
- photo_urls: item.photos || [],
- }));
-
- const submitData = {
- id: form.value.id,
- items: allDevices,
- status: returnStatus.value,
- pre_borrow_accessories: form.value.pre_borrow_accessories,
- };
-
- ReturnEquipment(submitData).then(async (res: ApiResponse) => {
- if(res.code===2000){
- ElMessage.success("归还成功");
- try {
- if (form.value.id) {
- const detailRes = await api.GetApplicationDetail(form.value.id);
- if (detailRes.code === 2000 && detailRes.data) {
- returnStatus.value = detailRes.data.status_label || returnStatus.value;
- }
- }
- } catch (e) {
- ElMessage.error('获取最新状态失败');
- }
- emit('submit');
- emit('update:visible', false);
- }
- });
- }
- }
- function clickReturn(){
- returnStatus.value = '已归还';
- // 自动选择所有设备
- const tableRef = document.querySelector('.el-table__header-wrapper th.el-table__cell.is-leaf .el-checkbox');
- if (tableRef) {
- (tableRef as HTMLElement).click();
- }
- }
- // 组件卸载时清理定时器和状态
- onBeforeUnmount(() => {
- clearRFIDInputTimer();
- clearProcessTagArrayTimer();
- rfidInputBuffer.value = '';
- currentRfidTag.value = '';
- rfidTagArray.value = [];
- consecutiveInputCount = 0;
- lastInputTime = 0;
- processingTags.value.clear();
- isProcessingTagArray.value = false;
- // 清空待提交的设备编号数组
- pendingDeviceCodes.value = [];
- isAutoSubmitting.value = false;
- // 清理归还流程定时器和状态
- clearReturnRFIDInputTimer();
- clearReturnProcessTagArrayTimer();
- returnRfidInputBuffer.value = '';
- returnCurrentRfidTag.value = '';
- returnRfidTagArray.value = [];
- returnProcessingTags.value.clear();
- isProcessingReturnTagArray.value = false;
- returnConsecutiveInputCount = 0;
- returnLastInputTime = 0;
- });
- /* formRef.value.validate((valid: boolean) => {
- if (valid) {
- form.value.items = form.value.items.map(item => ({
- ...item,
- quantity: Number(item.quantity) || 0
- }));
- const firstLocation = form.value.items[0]?.location || '';
- form.value.return_location = firstLocation;
- form.value.expected_start_time = now;
- form.value.expected_end_time = dayjs(form.value.expected_end_time).format('YYYY-MM-DD HH:mm:ss')|| now;
- form.team_members_count=Number(form.team_members_count)||1;
- emit('submit', { ...form.value });
- emit('update:visible', false);
- ElMessage.success("添加成功!");
- }
- }); */
-
- </script>
- <style>
- .avatar-uploader .el-upload {
- border: 1px dashed #d9d9d9;
- border-radius: 6px;
- cursor: pointer;
- position: relative;
- overflow: hidden;
- }
- .avatar-uploader .el-upload:hover {
- border-color: #409EFF;
- }
- .avatar-uploader-icon {
- font-size: 28px;
- color: #8c939d;
- width: 178px;
- height: 178px;
- line-height: 178px;
- text-align: center;
- }
- .avatar {
- width: 178px;
- height: 178px;
- display: block;
- }
- .return-cell-placeholder {
- color: #c0c4cc;
- }
- .return-cell-text {
- color: #606266;
- }
- .device-code-input {
- padding: 8px 12px;
- font-size: 14px;
- border: 1px solid #dcdfe6;
- border-radius: 4px;
- outline: none;
- resize: vertical;
- transition: all 0.3s;
- font-family: 'Microsoft YaHei', sans-serif;
- line-height: 1.5;
- }
- .device-code-input:focus {
- border-color: #409EFF;
- box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
- }
- .device-code-input:disabled {
- background-color: #f5f7fa;
- cursor: not-allowed;
- }
- </style>
|