import{M as C,a as T}from"./footer-0Nf1cSgs.js";import{S as h,a as u}from"./sweetalert2-Q8-u7Xo8.js";import{_ as x,m as S,q as I,c as n,a as k,b as t,r as P,g as p,k as g,s as v,h as D,v as w,t as c,F as _,d as F,n as f,o as d,j as V}from"./app-Dav-SkiH.js";const b=h.mixin({buttonsStyling:!1,showCloseButton:!0,focusConfirm:!1,backdrop:"rgba(0,0,0,0.45)",customClass:{popup:"swal2-custom-popup",title:"swal2-custom-title",htmlContainer:"swal2-custom-html",actions:"swal2-custom-actions",confirmButton:"swal2-custom-confirm-btn btn btn-success",cancelButton:"swal2-custom-cancel-btn btn btn-outline-secondary"},showClass:{popup:"swal2-show"},hideClass:{popup:"swal2-hide"}}),E={name:"ObjectDetectedLogs",components:{ManageSidebar:T,ManageFooter:C},data(){return{summary:{vehicleDetected:0,vehicleIn:0,vehicleOut:0},logs:[],currentPage:1,totalPages:1,itemsPerPage:10,totalResults:0,searchQuery:"",dateFilter:this.getTodayDate(),cameraFilter:"",serverValidationFilter:"1",platFilter:"",loading:!1,noData:!1}},computed:{...I(["user","authToken","refreshToken"]),pageRange(){const s=this.totalPages,e=this.currentPage,a=10;let l=[];if(s<=10)for(let o=1;o<=s;o++)l.push(o);else{l.push(1),e>a+2&&l.push("...");let o=Math.max(2,e-2),i=Math.min(s-1,e+2);for(let m=o;m<=i;m++)l.push(m);e<s-a-1&&l.push("..."),l.push(s)}return l}},methods:{...S(["logout","setAuthToken","setRefreshToken"]),getTodayDate(){const s=new Date,e=s.getFullYear(),a=String(s.getMonth()+1).padStart(2,"0"),l=String(s.getDate()).padStart(2,"0");return`${e}-${a}-${l}`},async fetchLogs(s=this.currentPage){this.loading=!0,this.noData=!1;try{const a=(await u.post("/api/v1/sensors/log-plat-number-detected",{page:s,limit:this.itemsPerPage,search:this.searchQuery,date:this.dateFilter,camera:this.cameraFilter,server_validation:this.serverValidationFilter,plat:this.platFilter},{headers:{Authorization:`Bearer ${this.authToken}`}}))?.data||{};this.logs=a.data||[],this.currentPage=a.pagination?.page||1,this.totalPages=a.pagination?.total_pages||1,this.totalResults=a.pagination?.total||0,this.noData=this.logs.length===0}catch(e){console.error("Failed to fetch logs:",e),h.fire("Error","Failed to fetch logs.","error")}finally{this.loading=!1}},resetFilters(){this.dateFilter=this.getTodayDate(),this.cameraFilter="",this.searchQuery="",this.serverValidationFilter="1",this.platFilter="",this.itemsPerPage=10,this.refreshAll()},changePage(s){s!=="..."&&s>0&&s<=this.totalPages&&(this.currentPage=s,this.fetchLogs(s))},isValid(s){const e=(s?.server_validation??"").toString().trim().toUpperCase();return e==="VALID"||e==="1"||e==="TRUE"||e==="YA"},escapeHtml(s){return String(s??"-").replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")},async openUserPopup(s){try{b.fire({title:"Loading detail user ...",allowOutsideClick:!1,didOpen:()=>h.showLoading(),showConfirmButton:!1}),console.log("[PLATE] request user-by-plate:",s);const e=await u.post("/api/plate-numbers/user-by-plate",{plate_number:s},{headers:{Authorization:`Bearer ${this.authToken}`}});h.close();const a=e?.data?.data||{},l=this.escapeHtml;await b.fire({title:"Detail Data User - Plat Number "+l(s),html:`
                            <div class="text-start">
                            <table class="table table-borderless">
                                <tr><th style="width:170px">Plate Number</th><td>${l(a.plate_number)}</td></tr>
                                <tr><th>Username</th><td>${l(a.username)}</td></tr>
                                <tr><th>Nama Lengkap</th><td>${l(a.nama_lengkap)}</td></tr>
                                <tr><th>NIP</th><td>${l(a.nip)}</td></tr>
                                <tr><th>Email</th><td>${l(a.email)}</td></tr>
                                <tr><th>Jabatan</th><td>${l(a.jabatan)}</td></tr>
                                <tr><th>Office</th><td>${l(a.office_name)}</td></tr>
                                <tr><th>AI Label</th><td>${l(a.ai_label)}</td></tr>
                                <tr><th>Level</th><td>${l(a.level_name??a.level_id)}</td></tr>
                            </table>
                            </div>
                        `,width:800})}catch(e){try{h.close()}catch{}const a=e?.response?.data?.message||"Tidak ada user terdaftar untuk plat ini atau terjadi kesalahan.";console.error("[PLATE] error user-by-plate:",e),await b.fire({icon:"error",title:"Gagal memuat data",text:a,confirmButtonText:"Tutup"})}},async fetchSummary(){try{const e=(await u.post("/api/v1/sensors/plate-number-summary",{date:this.dateFilter,camera:this.cameraFilter,server_validation:this.serverValidationFilter,plat:this.platFilter},{headers:{Authorization:`Bearer ${this.authToken}`}})).data?.data||{};this.summary.vehicleDetected=e.vehicleDetected||0,this.summary.vehicleIn=e.vehicleIn||0,this.summary.vehicleOut=e.vehicleOut||0}catch(s){console.error("Failed to fetch summary:",s),h.fire("Error","Failed to fetch summary data.","error")}},showAlert(s,e,a){h.fire({icon:a,title:s,text:e,toast:!0,position:"top-end",showConfirmButton:!1,timer:3e3})},async handleTokenRefresh(){try{const s=this.refreshToken;if(!s)throw new Error("No refresh token available");const e=await u.post("/api/refresh-token",{refresh_token:s}),{token:a,refresh_token:l}=e.data;return this.setAuthToken(a),this.setRefreshToken(l),this.setAxiosDefaults(a),console.log("Token refreshed successfully."),a}catch(s){console.error("Error refreshing token:",s),h.fire("Error","Session expired. Please log in again.","error"),this.logout()}},setupAxiosInterceptors(){u.interceptors.response.use(s=>s,async s=>{const{config:e,response:a}=s;if(a&&a.status===401&&!e._retry){e._retry=!0;const l=await this.handleTokenRefresh();if(l)return e.headers.Authorization=`Bearer ${l}`,u(e)}return Promise.reject(s)})},logout(){this.$store.dispatch("logout"),this.clearSession()},clearSession(){sessionStorage.removeItem("authToken"),sessionStorage.removeItem("refreshToken"),sessionStorage.removeItem("user"),localStorage.removeItem("authToken"),localStorage.removeItem("refreshToken"),localStorage.removeItem("user")},setAxiosDefaults(s){u.defaults.headers.common.Authorization=`Bearer ${s}`},showErrorAlert(s){h.fire({icon:"error",title:s,toast:!0,position:"top-end",showConfirmButton:!1,timer:3e3})},beforeDestroy(){this.tokenRefreshInterval&&clearInterval(this.tokenRefreshInterval)},created(){const s=localStorage.getItem("authToken");s?this.setAuthToken(s):console.warn("Auth token not found in localStorage.")},async refreshAll(){this.loading=!0;try{await Promise.all([this.fetchSummary(),this.fetchLogs()])}catch(s){console.error("Failed to refresh data:",s),h.fire("Error","Failed to refresh data.","error")}finally{this.loading=!1}}},mounted(){this.tokenRefreshInterval=setInterval(async()=>{try{await this.setupAxiosInterceptors()}catch(e){console.error("Error refreshing token:",e),this.logout(),this.$router.push({name:"Login"})}},36e5),this.authToken?(this.setAxiosDefaults(this.authToken),this.refreshAll()):h.fire({icon:"error",title:"Authentication Error",text:"Auth token is missing. Please log in again.",toast:!0,position:"top-end",showConfirmButton:!1,timer:3e3}).then(()=>{this.logout()})}},L={class:"page-wrapper"},R={class:"page-header d-print-none"},B={class:"container-fluid"},N={class:"row g-2 align-items-center"},O={class:"col-auto"},U=["disabled"],M={key:0},j={key:1},z={class:"page-body"},H={class:"container-fluid"},q={class:"card"},Q={class:"card-body",style:{"min-height":"78vh"}},G={class:"row justify-content-between mb-3"},Y={class:"col-auto mb-2 mb-lg-0"},J={class:"col-md-3 col-auto mb-2 mb-lg-0"},W={class:"col-md-3 col-auto mb-2 mb-lg-0"},K={class:"col-md-2 col-auto mb-2 mb-lg-0"},X={class:"col-md-2 col-auto mb-2 mb-lg-0"},Z={class:"col col-auto mb-2 mb-lg-0 d-flex align-items-end"},$={class:"row mt-1 mb-2"},ee={class:"col-lg-4 col-4"},te={class:"text-center alert alert-success"},se={class:"col-lg-4 col-4"},oe={class:"text-center alert alert-danger"},re={class:"col-lg-4 col-4"},ae={class:"text-center alert alert-primary"},le={key:0,class:"text-center my-5"},ie={key:1},ne={class:"row"},de={class:"col pb-2"},ce={class:"table-responsive"},he={class:"datatable table table-hover table-bordered"},ue={style:{"min-width":"180px"}},me={style:{"min-width":"120px"}},pe=["onClick"],ge={key:1},fe={style:{"min-width":"100px"}},ve={style:{"min-width":"100px"}},be={style:{"min-width":"300px"}},ye={style:{"min-width":"100px"}},ke={"aria-label":"Page navigation",class:"mt-3"},Pe={class:"pagination justify-content-center"},we=["disabled"],_e=["disabled"],Fe=["onClick"],Ae={key:1,class:"page-link disabled"},Ce=["disabled"],Te=["disabled"];function xe(s,e,a,l,o,i){const m=P("manage-sidebar"),A=P("manage-footer");return d(),n("div",null,[k(m),t("div",L,[t("div",R,[t("div",B,[t("div",N,[e[18]||(e[18]=t("div",{class:"col"},[t("div",{class:"page-pretitle"},"Logs"),t("h2",{class:"page-title"},"Plate Number Detection Logs")],-1)),t("div",O,[t("button",{class:"btn btn-primary",onClick:e[0]||(e[0]=(...r)=>i.refreshAll&&i.refreshAll(...r)),disabled:o.loading},[o.loading?(d(),n("span",M,e[16]||(e[16]=[t("i",{class:"fa fa-spinner fa-spin me-2"},null,-1),p(" Refreshing... ")]))):(d(),n("span",j,e[17]||(e[17]=[t("i",{class:"fa fa-refresh me-2"},null,-1),p(" Refresh ")])))],8,U)])])])]),t("div",z,[t("div",H,[t("div",q,[t("div",Q,[t("div",G,[t("div",Y,[e[20]||(e[20]=t("label",{for:"itemsPerPage",class:"form-label"},"Show:",-1)),g(t("select",{id:"itemsPerPage","onUpdate:modelValue":e[1]||(e[1]=r=>o.itemsPerPage=r),onChange:e[2]||(e[2]=r=>i.refreshAll(1)),class:"form-select w-100"},e[19]||(e[19]=[D('<option value="10">10</option><option value="20">20</option><option value="50">50</option><option value="100">100</option><option value="200">250</option><option value="500">500</option><option value="1000">1000</option><option value="">All</option>',8)]),544),[[v,o.itemsPerPage]])]),t("div",J,[e[21]||(e[21]=t("label",{for:"filterDate",class:"form-label"},"Filter by Date",-1)),g(t("input",{type:"date",id:"filterDate","onUpdate:modelValue":e[3]||(e[3]=r=>o.dateFilter=r),onChange:e[4]||(e[4]=r=>i.refreshAll(1)),class:"form-control w-100"},null,544),[[w,o.dateFilter]])]),t("div",W,[e[23]||(e[23]=t("label",{for:"filterCamera",class:"form-label"},"Filter by Camera",-1)),g(t("select",{id:"filterCamera","onUpdate:modelValue":e[5]||(e[5]=r=>o.cameraFilter=r),onChange:e[6]||(e[6]=r=>i.refreshAll(1)),class:"form-select w-100"},e[22]||(e[22]=[t("option",{value:""},"All Cameras",-1),t("option",{value:"pos-1"},"Camera POS-1 (IN)",-1),t("option",{value:"pos-2"},"Camera POS-2 (OUT)",-1)]),544),[[v,o.cameraFilter]])]),t("div",K,[e[25]||(e[25]=t("label",{for:"filterValidation",class:"form-label"},"Server Validation",-1)),g(t("select",{id:"filterValidation","onUpdate:modelValue":e[7]||(e[7]=r=>o.serverValidationFilter=r),onChange:e[8]||(e[8]=r=>i.refreshAll(1)),class:"form-select w-100"},e[24]||(e[24]=[t("option",{value:""},"All",-1),t("option",{value:"1"},"Valid",-1),t("option",{value:"0"},"Invalid",-1)]),544),[[v,o.serverValidationFilter]])]),t("div",X,[e[26]||(e[26]=t("label",{for:"searchPlat",class:"form-label"},"Plate Number",-1)),g(t("input",{type:"text",id:"searchPlat","onUpdate:modelValue":e[9]||(e[9]=r=>o.platFilter=r),onInput:e[10]||(e[10]=r=>i.refreshAll(1)),placeholder:"Search ...",class:"form-control w-100"},null,544),[[w,o.platFilter]])]),t("div",Z,[t("button",{class:"btn btn-secondary w-100",onClick:e[11]||(e[11]=(...r)=>i.resetFilters&&i.resetFilters(...r))},e[27]||(e[27]=[t("i",{class:"fa fa-times me-1"},null,-1),p(" Reset ")]))])]),t("div",$,[t("div",ee,[t("div",te,[e[28]||(e[28]=t("small",{class:"mb-3 d-block"}," VEHICLE IN OFFICE ",-1)),t("h1",null,c(o.summary.vehicleIn),1)])]),t("div",se,[t("div",oe,[e[29]||(e[29]=t("small",{class:"mb-3 d-block"}," VEHICLE LEFT ",-1)),t("h1",null,c(o.summary.vehicleOut),1)])]),t("div",re,[t("div",ae,[e[30]||(e[30]=t("small",{class:"mb-3 d-block"}," VEHICLE DETECTED ",-1)),t("h1",null,c(o.summary.vehicleDetected),1)])])]),o.loading?(d(),n("div",le,e[31]||(e[31]=[t("i",{class:"fa fa-spinner fa-spin fa-3x"},null,-1),t("p",{class:"mt-4"},"Loading data, please wait...",-1)]))):(d(),n("div",ie,[t("div",ne,[t("div",de,[e[32]||(e[32]=p(" Results: ")),t("strong",null,c(o.totalResults),1),e[33]||(e[33]=p(" data "))])]),t("div",ce,[t("table",he,[e[34]||(e[34]=t("thead",null,[t("tr",null,[t("th",null,"Datetime (WIB)"),t("th",null,"Plat Number"),t("th",null,"Confidence (%)"),t("th",null,"Server Validation"),t("th",null,"Server Message"),t("th",null,"Camera")])],-1)),t("tbody",null,[(d(!0),n(_,null,F(o.logs,(r,y)=>(d(),n("tr",{key:y},[t("td",ue,c(r.detected_at),1),t("td",me,[i.isValid(r)?(d(),n("button",{key:0,class:"btn btn-link p-0",onClick:V(Se=>i.openUserPopup(r.plat),["prevent"]),title:"Lihat detail user"},c(r.plat),9,pe)):(d(),n("span",ge,c(r.plat),1))]),t("td",fe,c(r.confidences),1),t("td",ve,c(r.server_validation),1),t("td",be,c(r.server_message),1),t("td",ye,c(r.camera),1)]))),128))])])]),t("nav",ke,[t("ul",Pe,[t("li",{class:f(["page-item",{disabled:o.currentPage===1}])},[t("button",{class:"page-link",onClick:e[12]||(e[12]=r=>i.changePage(1)),disabled:o.currentPage===1},"First",8,we)],2),t("li",{class:f(["page-item",{disabled:o.currentPage===1}])},[t("button",{class:"page-link",onClick:e[13]||(e[13]=r=>i.changePage(o.currentPage-1)),disabled:o.currentPage===1},"Prev",8,_e)],2),(d(!0),n(_,null,F(i.pageRange,r=>(d(),n("li",{class:f(["page-item",{active:o.currentPage===r}]),key:r},[r!=="..."?(d(),n("button",{key:0,class:"page-link",onClick:y=>i.changePage(r)},c(r),9,Fe)):(d(),n("span",Ae,"..."))],2))),128)),t("li",{class:f(["page-item",{disabled:o.currentPage===o.totalPages}])},[t("button",{class:"page-link",onClick:e[14]||(e[14]=r=>i.changePage(o.currentPage+1)),disabled:o.currentPage===o.totalPages}," Next ",8,Ce)],2),t("li",{class:f(["page-item",{disabled:o.currentPage===o.totalPages}])},[t("button",{class:"page-link",onClick:e[15]||(e[15]=r=>i.changePage(o.totalPages)),disabled:o.currentPage===o.totalPages},"Last",8,Te)],2)])])]))])])])]),k(A)])])}const Ee=x(E,[["render",xe]]);export{Ee as default};
