@{
    ViewData["Title"] = "QR Scanner";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<style>
    @@font-face {
        font-family: 'OCR-A';
        src: url('../assets/fonts/ocraext.ttf');
    }

    .QrPrintFont {
        font-family: 'OCR-A', monospace;
    }

    .table td img {
        display: block !important;
    }
</style>
@await Html.PartialAsync("~/Areas/Inventory/Views/_InventoryPartial.cshtml")
<div id="registerItemMovement" class="row">
    <div class="row card">
        <div v-if="thisItem" class="card-header">
            <button v-on:click="resetScanner" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Scanner
            </button>
        </div>
        
        <div class="card-body">
            <div data-aos="fade-right"></div>
            
            <select class="form-select" v-if="!thisItem"  v-model="selectedCameraId" v-on:change="updateCamera">
                <option v-for="device in videoInputDevices" :key="device.deviceId" :value="device.deviceId">
                    {{ device.label || `Camera ${videoInputDevices.indexOf(device) + 1}` }}
                </option>
            </select>

            <div id="registerItemMovement" v-if="!thisItem" data-aos="fade-right">
                <p style="text-align:center; padding:10px;">Scan QR Code Here:</p>

                <qrcode-stream :constraints="selectedConstraints"
                               :formats="['qr_code']"
                               :track="trackFunctionSelected.value"
                               v-on:camera-on="onCameraReady"
                               v-on:detect="onDecode"
                               v-on:error="onError">
                </qrcode-stream>

                <!-- Debugging: Show Processed Video -->
                <canvas ref="sharpenedCanvas" style="display:none;"></canvas>
                <video ref="preview" autoplay style="width: 100%;"></video>
                <p class="error">{{ error }}</p>
            </div>
        
            <p v-if="scanTime">Scan Time: {{ scanTime }} ms</p>
            <div v-if="thisItem" style="display: flex; justify-content: center; align-items: center;">
                <div  class="col-lg-7 col-11 border rounded p-3 shadow-sm">

                    <div class="row m-3 d-flex align-items-center justify-content-center">
                        <div class="col-lg-7 col-11 border rounded p-3 shadow-sm">
                            <div class="col-12 text-center">
                                <img :src="thisItem.imageProduct" alt="Product Image" class="img-fluid rounded" data-toggle="modal" data-target="#imageModal" style="max-height: 300px;" />
                            </div>
                            <div class="col-12 text-center mt-3">
                                <p class="h4 fw-bold text-primary">{{ thisItem.uniqueID }}</p>
                            </div>
                        </div>
                    </div>

                    <!-- Item Name -->
                    <div class="col-12 mb-3">
                        <p class="h5 fw-bold">
                            <i class="fas fa-tag me-2 text-secondary"></i>Item Name:
                            <span class="text-muted">{{ thisItem.productName }}</span>
                        </p>
                    </div>

                    <!-- Part Number -->
                    <div class="col-12 mb-3">
                        <p class="h5 fw-bold">
                            <i class="fas fa-barcode me-2 text-secondary"></i>Part Number:
                            <span class="text-muted">{{ thisItem.partNumber }}</span>
                        </p>
                    </div>

                    <!-- Serial Number -->
                    <div class="col-12 mb-3">
                        <p class="h5 fw-bold">
                            <i class="fas fa-hashtag me-2 text-secondary"></i>Serial Number:
                            <span class="text-muted">{{ thisItem.serialNumber }}</span>
                        </p>
                    </div>

                    <!-- PIC -->
                    <div class="col-12 mb-3">
                        <p class="h5 fw-bold">
                            <i class="fas fa-user-tie me-2 text-secondary"></i>PIC:
                            <span class="text-muted">Station PIC</span>
                        </p>
                    </div>

                    <!-- Current Information Card -->
                    <div class="col-12">
                        <div class="card shadow-sm border-0">
                            <div class="card-body">
                                <h5 class="card-title mb-4 text-primary">
                                    <i class="fas fa-info-circle me-2"></i>Current Information
                                </h5>
                                <ul class="list-group list-group-flush">
                                    <!-- User -->
                                    <li class="list-group-item">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <span class="fw-bold">
                                                <i class="fas fa-user me-2 text-secondary"></i>User:
                                            </span>
                                            <span class="text-muted text-end" style="max-width: 70%; word-wrap: break-word;">
                                                {{ thisItem.toUserName }}
                                            </span>
                                        </div>
                                    </li>

                                    <!-- Store -->
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <span class="fw-bold">
                                            <i class="mdi mdi-factory me-2 text-secondary"></i>Store:
                                        </span>
                                        <span class="text-muted">{{ thisItem.toStoreName }}</span>
                                    </li>

                                    <!-- Station -->
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <span class="fw-bold">
                                            <i class="fas fa-map-marker-alt me-2 text-secondary"></i>Station:
                                        </span>
                                        <span class="text-muted">{{ thisItem.toStationName || 'N/A' }}</span>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>         
            </div>

            <div v-if="thisItem" class=" register" data-aos="fade-right">
                <div class="row" data-aos="fade-right">
                    @*Right Side*@
                        <div class="col-md-12">
                            <div class="tab-content" id="myTabContent">
                                <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
                                    <div style="text-align: center; margin: 20px 0; padding: 20px;">
                                        
                                        <div v-if="itemlateststatus == 'On Delivery' && this.itemassignedtouser">
                                            <h2 class="register-heading">Item is on Delivery</h2>
                                            <div class="col-sm-3"></div>
                                            <div class="col-sm-6 offset-sm-3">
                                                <form v-on:submit.prevent="receiveItemMovement" data-aos="fade-right">
                                                    <div class="row register-form">

                                                        <div class="form-group row">
                                                            <label class="col-sm-4 col-form-label">Remark:</label>
                                                            <div class="col-sm-8">
                                                                <input type="text" id="remark" name="remark" v-model="remark" class="form-control" required />
                                                            </div>
                                                        </div>

                                                        <div style="display: flex; justify-content: center; margin-top: 20px;">
                                                            <button type="submit" class="btn btn-primary" style="width: 200px; padding: 10px; font-size: 16px;">
                                                                Cancel Item Movement
                                                            </button>
                                                        </div>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>

                                        <div v-if="(itemlateststatus == 'Repair' || itemlateststatus == 'Calibration') && this.itemassignedtouser">
                                            <h2 class="register-heading">Receive Repair / Calibration</h2>
                                            <div class="col-sm-3"></div>
                                            <div class="col-sm-6 offset-sm-3">
                                                <form v-on:submit.prevent="receiveItemMovement" data-aos="fade-right">
                                                    <div class="row register-form">

                                                        <div style="display: flex; justify-content: center; margin-top: 20px;">
                                                            <button type="submit" class="btn btn-primary" style="width: 200px; padding: 10px; font-size: 16px;">
                                                                Receive
                                                            </button>
                                                        </div>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>

                                        <div v-if="itemlateststatus == 'Delivered'">
                                            <h2 class="register-heading">Item has been Delivered</h2>
                                            <div class="col-sm-3"></div>
                                            <div class="col-sm-6 offset-sm-3">
                                            </div>
                                        </div>

                                    <div v-if="itemlateststatus == 'Return' && this.itemassignedtouser">
                                            <h2 class="register-heading">Receive Item Return</h2>
                                            <div class="col-sm-3"></div>
                                            <div class="col-sm-6 offset-sm-3">
                                                <form v-on:submit.prevent="receiveItemMovement" data-aos="fade-right">
                                                    <div class="row register-form">

                                                        <div style="display: flex; justify-content: center; margin-top: 20px;">
                                                            <button type="submit" class="btn btn-primary" style="width: 200px; padding: 10px; font-size: 16px;">
                                                                Receive 
                                                            </button>
                                                        </div>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>

                                        @* <div v-if=""> *@
                                        @*     <h2 class="register-heading">Item is not assigned to user to make movement</h2> *@
                                        @*     <div class="col-sm-3"></div> *@
                                        @*     <div class="col-sm-6 offset-sm-3"> *@
                                        @*         <form v-on:submit.prevent="receiveItemMovement" data-aos="fade-right"> *@
                                        @*             <div class="row register-form"> *@
                                        @*                 <div style="display: flex; justify-content: center; margin-top: 20px;"> *@
                                        @*                     <button type="submit" class="btn btn-primary" style="width: 200px; padding: 10px; font-size: 16px;"> *@
                                        @*                         Receive *@
                                        @*                     </button> *@
                                        @*                 </div> *@
                                        @*             </div> *@
                                        @*         </form> *@
                                        @*     </div> *@
                                        @* </div> *@

                                        <div v-if="itemlateststatus == 'Faulty'">
                                            <h2 class="register-heading">Add Item Movement</h2>
                                            <div class="col-sm-3"></div>
                                            <div class="col-sm-6 offset-sm-3">
                                                <div class="dropdown">
                                                    <select class="btn btn-primary dropdown-toggle col-md-10 " v-model="selectedAction" required>
                                                        <option class="btn-light" value="" disabled selected>Select Action</option>
                                                        <option class="btn-light" value="supplier">Assign to Supplier</option>
                                                        <option class="btn-light" value="faulty">Faulty</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div v-if="itemlateststatus == 'Ready To Deploy'">
                                            <h2 class="register-heading">Add Item Movement</h2>
                                            <div class="col-sm-3"></div>
                                            <div class="col-sm-6 offset-sm-3">
                                                <div class="dropdown">
                                                    <select class="btn btn-primary dropdown-toggle col-md-10 " v-model="selectedAction" required>
                                                        <option class="btn-light" value="" disabled selected>Select Action</option>
                                                        @* <option class="btn-light" value="user" v-if="itemlateststatus == 'Ready To Deploy'">Assign to User</option> *@
                                                        @* <option class="btn-light" value="store" v-if="itemlateststatus == 'Ready To Deploy'">Assign to Store</option> *@
                                                        @* <option class="btn-light" value="supplier" v-if="itemlateststatus != 'Delivered'">Assign to Supplier</option> *@
                                                        @* <option class="btn-light" value="faulty" v-if="itemlateststatus != 'Delivered'">Faulty</option> *@
                                                    <option class="btn-light" value="user">Assign to User</option>
                                                    <option class="btn-light" value="station">Assign to Station</option>
                                                    <option class="btn-light" value="store">Assign to Store</option>
                                                    <option class="btn-light" value="supplier">Assign to Supplier</option>
                                                    <option class="btn-light" value="faulty">Faulty</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="form-group row">
                                        <label class="col-sm-3 col-form-label"></label>
                                        
                                    </div>

                                    <form v-on:submit.prevent="addItemMovement" data-aos="fade-right">


                                        <div v-if="selectedAction === 'user'">
                                   
                                            <div class="row register-form">
                                                <div class="col-md-3"></div>
                                                <div class="col-md-6">

                                            
                                                    <div class="form-group row">
                                                        <label class="col-sm-4 col-form-label">To User:</label>
                                                        <div class="col-sm-8">
                                                            <div class="dropdown">
                                                            <select class="btn btn-primary dropdown-toggle col-md-10" v-model="selectedUser" required style="width: 100%;">
                                                                    <option class="btn-light" value="" disabled selected>Select User</option>
                                                                    <option class="btn-light" v-for="(user, index) in userlist" :key="index" :value="user.id">{{user.fullName}}</option>
                                                                </select>
                                                            </div>
                                                        </div>
                                                    </div>
                                           
                                                    <div class="form-group row"> 
                                                        <label for="invoiceDate" class="col-sm-4">Assign Date:</label> 
                                                        <div class="col-sm-8"> 
                                                            <input type="date" id="assigndate" name="assigndate" class="form-control" v-model="assigndate"> 
                                                        </div> 
                                                    </div>

                                                    <div class="form-group row">
                                                        <label class="col-sm-4 col-form-label">Consignment Note</label>
                                                        <div class="col-sm-8">
                                                            <input type="file" id="document" name="document" class="form-control-file" v-on:change="handleFileUpload" accept="image/png, image/jpeg, application/pdf" />
                                                        </div>
                                                    </div>

                                                    <div class="form-group row">
                                                        <label class="col-sm-4 col-form-label">Remark:</label>
                                                        <div class="col-sm-8">
                                                            <input type="text" id="remark" name="remark" v-model="remark" class="form-control" required />
                                                        </div>
                                                    </div>

                                                </div>

                                                @* Submit and Reset Buttons *@
                                                <div class="form-group row">
                                                    <div class="col-sm-8 offset-sm-3">
                                                        <button type="button" v-on:click="resetForm" class="btn btn-secondary m-1">Reset</button>
                                                        <button type="submit" class="btn btn-primary m-1">Submit</button>
                                                    </div>
                                                </div>
                                            </div>
                                    
                                        </div>

                                    <div v-if="selectedAction === 'station'">

                                        <div class="row register-form">
                                            <div class="col-md-3"></div>
                                            <div class="col-md-6">

                                                <div class="form-group row">
                                                    <label class="col-sm-4 col-form-label">To Station:</label>
                                                    <div class="col-sm-8">
                                                        <div class="dropdown">
                                                            <select class="btn btn-primary dropdown-toggle col-md-10" v-model="selectedStation" required style="width: 100%;">
                                                                <option class="btn-light" value="" disabled selected>Select Station</option>
                                                                <option class="btn-light" v-for="(station, index) in stationlist" :key="index" :value="station.stationId">{{station.stationName}}</option>
                                                            </select>


                                                        </div>
                                                    </div>
                                                </div>


                                                <div class="form-group row">
                                                    <label class="col-sm-4 col-form-label">To PIC:</label>
                                                    <div class="col-sm-8">
                                                        <div class="dropdown">
                                                            <input type="text" id="selectedStationPIC" name="selectedStationPIC" :value="selectedStationPicName" class="form-control" readonly />
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="form-group row">
                                                    <label for="invoiceDate" class="col-sm-4">Assign Date:</label>
                                                    <div class="col-sm-8">
                                                        <input type="date" id="assigndate" name="assigndate" class="form-control" v-model="assigndate">
                                                    </div>
                                                </div>

                                                <div class="form-group row">
                                                    <label class="col-sm-4 col-form-label">Consignment Note</label>
                                                    <div class="col-sm-8">
                                                        <input type="file" id="document" name="document" class="form-control-file" v-on:change="handleFileUpload" accept="image/png, image/jpeg, application/pdf" />
                                                    </div>
                                                </div>

                                                <div class="form-group row">
                                                    <label class="col-sm-4 col-form-label">Remark:</label>
                                                    <div class="col-sm-8">
                                                        <input type="text" id="remark" name="remark" v-model="remark" class="form-control" required />
                                                    </div>
                                                </div>

                                            </div>

                                            @* Submit and Reset Buttons *@
                                            <div class="form-group row">
                                                <div class="col-sm-8 offset-sm-3">
                                                    <button type="button" v-on:click="resetForm" class="btn btn-secondary m-1">Reset</button>
                                                    <button type="submit" class="btn btn-primary m-1">Submit</button>
                                                </div>
                                            </div>
                                        </div>

                                    </div>

                                        <div v-if="selectedAction === 'store'">

                                            <div class="row register-form">
                                                <div class="col-md-3"></div>
                                                <div class="col-md-6">

                                                    <div class="form-group row">
                                                        <label class="col-sm-4 col-form-label">To Store:</label>
                                                        <div class="col-sm-8">
                                                        <select class="btn btn-primary dropdown-toggle col-md-10" v-model="selectedStore" style="width: 100%;">
                                                                <option class="btn-light" value="" disabled selected>Select Store</option>
                                                                <option class="btn-light" v-for="(store, index) in storelist" :key="index" :value="store.id">{{ store.storeName}}</option>
                                                            </select>
                                                        </div>
                                                    </div>


                                                    <div class="form-group row">
                                                        <label for="invoiceDate" class="col-sm-4">Assign Date:</label>
                                                        <div class="col-sm-8">
                                                            <input type="date" id="assigndate" name="assigndate" class="form-control" v-model="assigndate">
                                                        </div>
                                                    </div>
                                                
                                                    <div class="form-group row">
                                                        <label class="col-sm-4 col-form-label">Consignment Note</label>
                                                        <div class="col-sm-8">
                                                            <input type="file" id="document" name="document" class="form-control-file" v-on:change="handleFileUpload" accept="image/png, image/jpeg, application/pdf" />
                                                        </div>
                                                    </div>


                                                    <div class="form-group row">
                                                        <label class="col-sm-4 col-form-label">Remark:</label>
                                                        <div class="col-sm-8">
                                                            <input type="text" id="remark" name="remark" v-model="remark" class="form-control" required />
                                                        </div>
                                                    </div>
                                                </div>

                                                @* Submit and Reset Buttons *@
                                                <div class="form-group row">
                                                    <div class="col-sm-8 offset-sm-3">
                                                        <button type="button" v-on:click="resetForm" class="btn btn-secondary m-1">Reset</button>
                                                        <button type="submit" class="btn btn-primary m-1">Submit</button>
                                                    </div>
                                                </div>
                                            </div>

                                        </div>

                                        <div v-if="selectedAction === 'supplier'">
                                            <div class="row register-form">
                                                <div class="col-md-3"></div>
                                                <div class="col-md-6">


                                                    <div class="form-group row">
                                                        <label class="col-sm-4 col-form-label">To Supplier:</label>
                                                        <div class="col-sm-8">
                                                            <div class="dropdown">
                                                                <select class="btn btn-primary dropdown-toggle col-md-10" v-model="selectedSupplier" required style="width: 100%;">
                                                                    <option class="btn-light" value="" disabled selected>Select Supplier</option>
                                                                    <option class="btn-light" v-for="(supplier, index) in supplierlist" :key="index" :value="supplier.supplierCompName">{{supplier.supplierCompName}}</option>
                                                                </select>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div class="form-group row">
                                                        <label class="col-sm-4 col-form-label">To Other:</label>
                                                        <div class="col-sm-8">
                                                            <div class="dropdown">
                                                                <select class="btn btn-primary dropdown-toggle col-md-10" v-model="selectedOther" required style="width: 100%;">
                                                                    <option class="btn-light" value="" disabled selected>Select</option>
                                                                    <option class="btn-light" value="Repair">Repair</option>
                                                                    <option class="btn-light" value="Calibration">Calibration</option>
                                                                </select>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div class="form-group row">
                                                        <label for="invoiceDate" class="col-sm-4">Assign Date:</label>
                                                        <div class="col-sm-8">
                                                            <input type="date" id="assigndate" name="assigndate" class="form-control" v-model="assigndate">
                                                        </div>
                                                    </div>

                                                    <div class="form-group row">
                                                        <label class="col-sm-4 col-form-label">Consignment Note</label>
                                                        <div class="col-sm-8">
                                                            <input type="file" id="document" name="document" class="form-control-file" v-on:change="handleFileUpload" accept="image/png, image/jpeg, application/pdf" />
                                                        </div>
                                                    </div>

                                                    <div class="form-group row">
                                                        <label class="col-sm-4 col-form-label">Remark:</label>
                                                        <div class="col-sm-8">
                                                            <input type="text" id="remark" name="remark" v-model="remark" class="form-control" required />
                                                        </div>
                                                    </div>

                                                </div>

                                                @* Submit and Reset Buttons *@
                                                <div class="form-group row">
                                                    <div class="col-sm-8 offset-sm-3">
                                                        <button type="button" v-on:click="resetForm" class="btn btn-secondary m-1">Reset</button>
                                                        <button type="submit" class="btn btn-primary m-1">Submit</button>
                                                    </div>
                                                </div>
                                            </div>
                                    
                                        </div>

                                        <div v-if="selectedAction === 'faulty'">
                                    
                                            <div class="row register-form">
                                                <div class="col-md-3"></div>
                                                <div class="col-md-6">

                                                    <div class="form-group row">
                                                        <label class="col-sm-4 col-form-label">Consignment Note</label>
                                                        <div class="col-sm-8">
                                                            <input type="file" id="document" name="document" class="form-control-file" v-on:change="handleFileUpload" accept="image/png, image/jpeg, application/pdf" />
                                                        </div>
                                                    </div>

                                                    <div class="form-group row">
                                                        <label class="col-sm-4 col-form-label">Remark:</label>
                                                        <div class="col-sm-8">
                                                            <input type="text" id="remark" name="remark" v-model="remark" class="form-control" required />
                                                        </div>
                                                    </div>


                                                </div>

                                                @* Submit and Reset Buttons *@
                                                <div class="form-group row">
                                                    <div class="col-sm-8 offset-sm-3">
                                                        <button type="button" v-on:click="resetForm" class="btn btn-secondary m-1">Reset</button>
                                                        <button type="submit" class="btn btn-primary m-1">Submit</button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    

                    @* <div v-if="selectedAction === 'receive'"> *@
                    @*     <form v-on:submit.prevent="receiveItemMovement" data-aos="fade-right"> *@
                    @*         <div class="row register-form"> *@

                    @*             <div style="display: flex; justify-content: center; margin-top: 20px;"> *@
                    @*                 <button type="submit" class="btn btn-primary" style="width: 200px; padding: 10px; font-size: 16px;"> *@
                    @*                     Receive *@
                    @*                 </button> *@
                    @*             </div> *@
                    @*         </div> *@
                    @*     </form> *@
                    @* </div> *@
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }

    <script src="~/js/vue-qrcode-reader.umd.js"></script>

    <script>
        $(function () {
                

                // Attach a click event listener to elements with the class 'btn-success'.
                $('#addItemBtn').on('click', function () {
                    // Show the modal with the ID 'addManufacturerModal'.
                    $('#registerItemModal').modal('show');
                });
                $('.closeModal').on('click', function () {
                    // Show the modal with the ID 'addManufacturerModal'.
                    $('.modal').modal('hide');
                });
        });
        const app = Vue.createApp({
            data() {
                return {
                    thisItem: null,
                    qrCodeResult: null,

                    debounceTimeout: null,
                    userlist: null,
                    stationlist: null,
                    storelist: null,
                    supplierlist: null,
                    selectedUser: "",
                    selectedStation: "",
                    selectedStationPIC: null,
                    selectedStore: "",
                    selectedAction: "",
                    assigndate: null,
                    selectedSupplier: "",
                    selectedOther: "",
                    remark: "",
                    document: null,
                    // companies: [
                    //     {
                    //         companyId: 1,
                    //         companyName: "PSTW",
                    //         departments: [{ departmentId: 1, departmentName: "Air" }, { departmentId: 2, departmentName: "Marine" }, { departmentId: 3, departmentName: "River" }]
                    //     },
                    //     {
                    //         companyId: 2,
                    //         companyName: "TES",
                    //         departments: [{ departmentId: 1, departmentName: "Air" }],
                    //     },
                    // ],
                    // company: "",
                    currentUser: null,
                    currentUserCompanyDept: null,
                    itemlateststatus: "",

                    //QR VARIABLE
                    qrCodeResult: null,
                    debounceTimeout: null,
                    error: "",
                    selectedConstraints: { facingMode: "environment" },
                    trackFunctionSelected: { text: 'outline', value: null },
                    barcodeFormats: {
                        qr_code: true,  // Hanya mendukung QR Code
                        code_128: true,
                        ean_13: true
                    },
                    constraintOptions: [
                        { label: "Rear Camera", constraints: { facingMode: "environment" } },
                        { label: "Front Camera", constraints: { facingMode: "user" } }
                    ],
                    videoInputDevices: [],
                    selectedCameraId: null,
                    scanStartTime: null,
                    scanTime: null
                }
            },
            mounted() {
                this.fetchUser();
                this.fetchSuppliers();
                this.fetchUsers();
                this.fetchStores();
                this.fetchStations();
                this.trackFunctionSelected.value = this.paintOutline;
            },
            watch: {
                selectedStation(newStationId) {
                    
                    // Find the station object that matches the selectedStation id
                    const selectedStationObj = this.stationlist.find(station => station.stationId === newStationId);
                    // Set the selectedPIC based on the stationPIC
                    this.selectedStationPIC = selectedStationObj ? selectedStationObj.stationPicID : "";
                    // this.selectedStationPIC = selectedStationObj ? selectedStationObj : null;
                }
            },
            computed: {
                selectedStationPicName() {
                    const selectedStationObj = this.stationlist.find(station => station.stationId === this.selectedStation);
                    return selectedStationObj ? selectedStationObj.stationPic.fullName : "";
                },
                filteredDepartments() {
                    if (!this.selectedCompany) {
                        return []; // No company selected, return empty list
                    }
                    const company = this.companies.find(c => c.companyId === this.selectedCompany);
                    // this.selectedDepartment = '';
                    return company ? company.departments : [];
                },
                showProduct() {
                    if (!this.selectedProduct) {
                        return []; // No company selected, return empty list
                    }
                    const product = this.products.find(c => c.productId === this.selectedProduct);
                    return product ? product : {};
                },
                showSerialNumber() {
                    return this.showProduct.category === 'Asset' || this.showProduct.category === 'Part';
                },
            },
            methods: {
                // Split Url dapatkan unique ID Je
                onDecode(detectedCodes) {
                    // const endTime = performance.now();
                    // this.scanTime = Math.round(endTime - this.scanStartTime); Calculate scan time

                    if (detectedCodes.length > 0) {
                        this.qrCodeResult = detectedCodes[0].rawValue; // Ambil URL dari rawValue
                        this.UniqueID = this.qrCodeResult.split('/').pop(); // Ambil UniqueID dari URL
                        this.fetchItem(this.UniqueID);
                    }
                },

                //Showing Qr Error
                onError(err) {
                    let message = `[${err.name}]: `;
                    if (err.name === "NotAllowedError") {
                        message += "You have to allow camera accecss.";
                    } else if (err.name === "NotFoundError") {
                        message += "There's no camera detect.";
                    } else if (err.name === "NotReadableError") {
                        message += "You are using camera on the other application.";
                    } else {
                        message += err.message;
                    }
                    this.error = message;
                },

                //Setting Camera
                async onCameraReady() {
                    // this.scanStartTime = performance.now(); Start timing
                    // this.scanTime = null; Reset previous scan time

                    try {
                        const devices = await navigator.mediaDevices.enumerateDevices();
                        this.videoInputDevices = devices.filter(device => device.kind === 'videoinput');

                        if (this.videoInputDevices.length > 0) {
                            // Keep the selected camera if already chosen
                            if (!this.selectedCameraId) {
                                this.selectedCameraId = this.videoInputDevices[0].deviceId;
                            }

                            this.selectedConstraints = { deviceId: { exact: this.selectedCameraId } };
                        } else {
                            this.error = "No camera detected.";
                        }
                    } catch (err) {
                        this.error = "Error accessing camera: " + err.message;
                    }
                },

                //Update Camera Category
                updateCamera() {
                    this.selectedConstraints = { deviceId: { exact: this.selectedCameraId } };
                },

                //Red box if QR Detect
                paintOutline(detectedCodes, ctx) {
                    for (const detectedCode of detectedCodes) {
                        const [firstPoint, ...otherPoints] = detectedCode.cornerPoints;

                        ctx.strokeStyle = 'red'; // Warna garis merah
                        ctx.lineWidth = 3;

                        ctx.beginPath();
                        ctx.moveTo(firstPoint.x, firstPoint.y);
                        for (const { x, y } of otherPoints) {
                            ctx.lineTo(x, y);
                        }
                        ctx.lineTo(firstPoint.x, firstPoint.y);
                        ctx.closePath();
                        ctx.stroke();
                    }
                },
                    resetScanner(){
                        this.thisItem = null;
                        this.resetForm();
                    },
                    handleFileUpload(event) {
                         const file = event.target.files[0];

                        if (file) {
                            const reader = new FileReader();
                            reader.onload = (e) => {
                                this.document = e.target.result.split(',')[1]; // Get Base64 string (remove metadata)
                            };
                            reader.readAsDataURL(file);
                        } else {
                            this.document = null;
                        }
                    },
                    async addItemMovement() {

                    if (this.showProduct.category == "Disposable") {
                        this.serialNumber = "";
                    }

                    const now = new Date();
                    const formData = {

                        ...(this.selectedAction === 'user' ? { toUser: this.currentUser.id, toOther: 'On Delivery', SendDate: this.assigndate, lastUser: this.selectedUser, MovementComplete: false, Remark: this.remark, ConsignmentNote: this.document} : {}),
                        ...(this.selectedAction === 'station' ? { toUser: this.currentUser.id, toOther: 'On Delivery', SendDate: this.assigndate, lastStation: this.selectedStation, lastUser: this.selectedStationPIC, MovementComplete: false, Remark: this.remark, ConsignmentNote: this.document} : {}),
                        ...(this.selectedAction === 'store' ? { toUser: this.currentUser.id, toOther: 'On Delivery', SendDate: this.assigndate, lastUser: this.selectedStore, MovementComplete: false, Remark: this.remark, ConsignmentNote: this.document} : {}),
                        ...(this.selectedAction === 'supplier' ? { toUser: this.currentUser.id, toOther: this.selectedOther, SendDate: this.assigndate, Remark: this.remark + '. Item sent to ' + this.selectedSupplier + ' for ' + this.selectedOther, ConsignmentNote: this.document, lastUser: this.currentUser.id, MovementComplete: false, } : {}),
                        ...(this.selectedAction === 'faulty' ? { toUser: this.currentUser.id,toOther: 'Faulty', Date: new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString(), Remark: this.remark, ConsignmentNote: this.document, MovementComplete: true, } : {}),

                         ItemId: this.thisItem.itemID,  
                         Action: 'Stock Out',
                         Quantity: 1,
                    };

                    

                    try {

                        // Proceed to send the data to the API
                        const response = await fetch('/InvMainAPI/AddItemMovement', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                // 'Authorization': `Bearer ${this.token}`
                            },
                            body: JSON.stringify(formData)
                        });
                        if (response.ok) {
                            // If the form submission was successful, display a success message
                            alert('Success!', 'Item form has been successfully submitted.', 'success');
                            // const updatedItem = await response.json();
                            // this.items.push(updatedItem);
                            // console.log(updatedItem);

                            // Reset the form
                            this.resetForm();
                            window.location.href = '/Inventory/InventoryMaster/ItemMovement';
                            
                        } else {
                            throw new Error('Failed to submit form.');
                        }

                    } catch (error) {
                        console.error('Error:', error);

                        // Displaying error message
                        alert('Inventory PSTW Error', `An error occurred: ${error.message}`, 'error');
                    }

                },
                async receiveItemMovement() {
                    
                    if (this.showProduct.category == "Disposable") {
                        this.serialNumber = "";
                    }

                    if(this.thisItem.toOther === "On Delivery"){
                        if(!window.confirm("Are you sure you want to cancel item delivery?")){
                            return;
                        }
                    }

                    const now = new Date();
                    const formData = {

                        Id: this.thisItem.movementId,
                        ReceiveDate: new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString(),
                        Remark: this.thisItem.toOther === "On Delivery" ? this.thisItem.remark + ". Inventory Master cancelled delivery with remark: " + this.remark : this.thisItem.remark,
                        LatestStatus: this.thisItem.toOther === "Return" ? "Faulty" : (this.thisItem.toOther === "Calibration" || this.thisItem.toOther === "Repair" || this.thisItem.toOther === "On Delivery" ) ? "Ready To Deploy" : ""
                    };



                    try {

                        // Proceed to send the data to the API
                        const response = await fetch('/InvMainAPI/UpdateItemMovementMaster', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                // 'Authorization': `Bearer ${this.token}`
                            },
                            body: JSON.stringify(formData)
                        });
                        if (response.ok) {
                            // If the form submission was successful, display a success message
                            alert('Success!', 'Item form has been successfully submitted.', 'success');
                            const updatedItem = await response.json();
                            // this.items.push(updatedItem);
                            console.log(updatedItem);

                            // Reset the form
                            this.resetForm();
                            window.location.href = '/Inventory/InventoryMaster/ItemMovement';

                        } else {
                            throw new Error('Failed to submit form.');
                        }

                    } catch (error) {
                        console.error('Error:', error);

                        // Displaying error message
                        alert('Inventory PSTW Error', `An error occurred: ${error.message}`, 'error');
                    }

                },
                async fetchItem(itemid) {
                    try {
                        const response = await fetch('/InvMainAPI/GetItem/' + itemid, {
                            method: 'POST',}
                        );
                        if (response.ok) {
                            // this.thisItem = await response.json();

                            this.thisItem = await response.json();
                            this.itemlateststatus = this.thisItem.latestStatus ? this.thisItem.latestStatus : this.thisItem.toOther;
                            this.itemassignedtouser = this.thisItem.toUser == this.currentUser.id || this.thisItem.lastUser == this.currentUser.id ? true : false;
                            console.log(this.thisItem);
                            

                            // if ((this.thisItem.toOther === "Repair" || this.thisItem.toOther === "Calibration" || this.thisItem.toOther === "Return" ) && this.thisItem.lastUser === this.currentUser.id && this.thisItem.movementComplete === false) {
                            //     this.selectedAction = "receive";
                            // }

                            // if ((this.itemlateststatus === "Repair" || this.itemlateststatus === "Calibration" || this.itemlateststatus === "Return" ) && this.thisItem.lastUser === this.currentUser.id && this.thisItem.movementComplete === false) {
                            //     this.selectedAction = "receive";
                            // }

                        } else {
                            console.error('Failed to fetch item information');
                            this.responseMessage = await response.text();
                        }
                    } catch (error) {
                        console.error('Error fetching item information:', error);
                    }
                },
                async fetchSuppliers() {
                    try {
                        const response = await fetch('/InvMainAPI/SupplierList', {
                            method: 'POST', // Specify the HTTP method
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        });
                        if (!response.ok) {
                            throw new Error('Failed to fetch suppliers');
                        }
                        this.supplierlist = await response.json(); // Get the full response object

                    } catch (error) {
                        console.error('Error fetching suppliers:', error);
                    }
                },
                resetForm() {
                    this.selectedUser = "";
                    this.selectedStore = "";
                    this.selectedSupplier = "";
                    this.remark = "";
                    this.assigndate = "";
                    this.selectedStore = "";
                    this.selectedOther = "";
                    this.selectedStation = "";
                    this.selectedStationPIC = "";
                    
                
                   
                },

                // FRONT END FUNCTIONS
                //----------------------//
                async fetchUser() {
                    try {
                        const response = await fetch(`/IdentityAPI/GetUserInformation/`, {
                            method: 'POST',
                        });
                        if (response.ok) {
                            const data = await response.json();
                            this.currentUser = data?.userInfo || null;
                            const companyDeptData = await this.currentUser.department;
                            this.currentUserCompanyDept = companyDeptData;
                            this.selectedCompany = companyDeptData?.companyId || "";
                            this.selectedDepartment = companyDeptData?.departmentId || "";
                      

                        }
                        else {
                            console.error(`Failed to fetch user: ${response.statusText}`);
                        }
                    }
                    catch (error) {
                        console.error('There was a problem with the fetch operation:', error);
                    }
                },
                async fetchUsers() {
                    try {
                        // const token = localStorage.getItem('token'); // Get the token from localStorage
                        const response = await fetch('/InvMainAPI/UserList', {
                            method: 'POST', // Specify the HTTP method
                            headers: {
                                'Content-Type': 'application/json', // Set content type
                                // 'Authorization': `Bearer ${token}` // Include the token in the headers
                            }
                        });

                        if (!response.ok) {
                            throw new Error('Failed to fetch item');
                        }
                        this.userlist = await response.json();


                    }
                    catch (error) {
                        console.error('Error fetching item:', error);
                    }
                },
                async fetchStations() {
                    try {
                        // const token = localStorage.getItem('token'); // Get the token from localStorage
                        const response = await fetch('/InvMainAPI/StationList', {
                            method: 'POST', // Specify the HTTP method
                            headers: {
                                'Content-Type': 'application/json', // Set content type
                                // 'Authorization': `Bearer ${token}` // Include the token in the headers
                            }
                        });

                        if (!response.ok) {
                            throw new Error('Failed to fetch item');
                        }
                        this.stationlist = await response.json();
                        console.log(this.stationlist);


                    }
                    catch (error) {
                        console.error('Error fetching item:', error);
                    }
                },
                async fetchStores() {
                    try {
                        // const token = localStorage.getItem('token'); // Get the token from localStorage
                        const response = await fetch('/InvMainAPI/StoreList', {
                            method: 'POST', // Specify the HTTP method
                            headers: {
                                'Content-Type': 'application/json', // Set content type
                                // 'Authorization': `Bearer ${token}` // Include the token in the headers
                            }
                        });

                        if (!response.ok) {
                            throw new Error('Failed to fetch item');
                        }
                        this.storelist = await response.json();



                    }
                    catch (error) {
                        console.error('Error fetching item:', error);
                    }
                },
            },
        });

        app.component("qrcode-stream", VueQrcodeReader.QrcodeStream);

        app.mount('#registerItemMovement');
    </script>



}