index.blade.php 52.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>OCR Mapping with Manual Select Tool</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="{{ asset('css/ocr.css') }}">
</head>
<body>
<meta name="csrf-token" content="{{ csrf_token() }}">
<div id="app">
    <div class="left-panel" >
        <div class="pdf-container" ref="pdfContainer"
             @mousedown="startSelect"
             @mousemove="onSelect"
             @mouseup="endSelect">
            <img
                ref="pdfImage"
                :src="pdfImageUrl"
                @load="onImageLoad"
                style="width: 100%; height: auto;pointer-events: none;"
            />


            <!-- Vùng kéo chọn -->
            <div v-if="selectBox.show" class="select-box"
                 :style="{ left: selectBox.x + 'px', top: selectBox.y + 'px', width: selectBox.width + 'px', height: selectBox.height + 'px' }"></div>

            <!-- Vẽ bbox OCR -->
            <div
                v-for="(item, index) in ocrData"
                :key="index"
                v-if="!item.isDeleted"
                class="bbox"
                :class="{ active: index === activeIndex }"
                :data-index="index"
                :data-field="item.field"
                :style="getBoxStyle(item, index)"
                @click="onBoxClick(index)">

                <div class="edge top" data-handle="top"
                     @mousedown="startResize($event, index, 'top')">
                </div>
                <div class="edge right"  data-handle="right"
                     @mousedown="startResize($event, index, 'right')">
                </div>
                <div class="edge bottom" data-handle="bottom"
                     @mousedown="startResize($event, index, 'bottom')">
                </div>
                <div class="edge left" data-handle="left"
                     @mousedown="startResize($event, index, 'left')">
                </div>
                <!-- 4 góc -->
                <div class="corner top-left" data-handle="top-left"
                     @mousedown="startResize($event, index, 'top-left')">
                </div>
                <div class="corner top-right" data-handle="top-right"
                     @mousedown="startResize($event, index, 'top-right')">
                </div>
                <div class="corner bottom-left" data-handle="bottom-left"
                     @mousedown="startResize($event, index, 'bottom-left')">
                </div>
                <div class="corner bottom-right" data-handle="bottom-right"
                     @mousedown="startResize($event, index, 'bottom-right')">
                </div>

                <div v-if="item.isManual && item.showDelete"
                     class="delete-btn"
                     @click.stop="deleteBox(index)">
                    <img src="{{ asset('icon/btn-delete.png') }}" alt="delete box" style="width: 20px; height: 20px;">
                </div>
            </div>


            <!-- Dropdown OCR -->
            <select v-if="selectingIndex !== null && ocrData[selectingIndex]"
                    :style="getSelectStyle(ocrData[selectingIndex])"
                    v-model="ocrData[selectingIndex].field"
                    @change="applyMapping"
            >
                <option disabled value="">-- Chọn trường dữ liệu --</option>
                <option v-for="field in getAllowedOptionsForBox(ocrData[selectingIndex])" :value="field.value">@{{ field.label }}</option>
            </select>

            <!-- Dropdown thủ công -->
            <select v-if="selectBox.showDropdown"
                    class="manual-select"
                    :style="{ left: selectBox.x + 'px', top: (selectBox.y + selectBox.height) + 'px', zIndex: 10000, position: 'absolute' }"
                    v-model="manualField"
                    @change="applyManualMapping"
                    @mousedown.stop
                    @mouseup.stop
                    @click.stop
            >
                <option disabled value="">-- Chọn trường dữ liệu --</option>
                <option v-for="field in getAllowedOptionsForManual()" :value="field.value">@{{ field.label }}</option>
            </select>
        </div>
    </div>

    <div class="right-panel">
        <div v-for="field in fieldOptions" :key="field.value" class="form-group">
            <label>@{{ field.label }}</label>
            <input v-model="formData[field.value]"
                   @click="onInputClick(field.value)"
                   @blur="removeAllFocus()"
            >
        </div>

        <!-- Table mapping -->
        <table class="data-table" v-if="total_rows > 0">
            <thead>
            <tr>
                <th>Product Name</th>
                <th>Product Code</th>
                <th>Quantity</th>
            </tr>
            </thead>
            <tbody>
            <tr class="table-detail"
                v-for="(row, rowIndex) in dataRowsCount"
                :key="rowIndex"
                :data-row="rowIndex"
            >
                <td class="form-group">
                    <input
                        @click="onTableInputClick('product_name', rowIndex)"
                        v-model="tableForm[rowIndex].product_name"
                        :data-row="rowIndex"
                        :data-field="'product_name'"
                        placeholder="Enter name">
                </td>
                <td class="form-group">
                    <input
                        @click="onTableInputClick('product_code', rowIndex)"
                        v-model="tableForm[rowIndex].product_code"
                        :data-row="rowIndex"
                        :data-field="'product_code'"
                        placeholder="Enter code">
                </td>
                <td class="form-group">
                    <input
                        @click="onTableInputClick('quantity', rowIndex)"
                        v-model.number="tableForm[rowIndex].quantity"
                        :data-row="rowIndex"
                        :data-field="'quantity'"
                        type="number"
                        placeholder="0">
                </td>
            </tr>
            </tbody>
        </table>

        <button class="mt-10" @click="saveTemplate">💾Save</button>
    </div>

</div>


<script>
    new Vue({
        el: '#app',
        data() {
            return {
                pdfImageUrl: "",
                selectingIndex: null,
                isMappingManually: false,
                isSelecting: false,
                activeIndex: null,
                manualField: "",
                formData: {},
                tableInfo: {},
                total_rows: 0,
                table_box: [],
                tableColumnMapping: { product_name: null, product_code: null, quantity: null },
                tableForm: [],
                manualBoxData: {},
                fieldOptions: [],
                tempFocusIndex: null,
                customer_name_xy: '',
                hasCustomerNameXY: false,
                ocrData: [],
                selectBox: { show: false, showDropdown: false, x: 0, y: 0, width: 0, height: 0, startX: 0, startY: 0 },
                manualIndex: null,
                suppressNextDocumentClick: false
            }
        },
        created() {
            this.fieldOptions
                .forEach(f => {
                    this.$set(this.formData, f.value, "");
                });
        },
        mounted() {
            this.loadOCRData();
            // Thêm event listener để xử lý click ra ngoài
            document.addEventListener('click', (e) => {
                // Bỏ qua click ngay sau khi thả chuột tạo box
                if (this.suppressNextDocumentClick) {
                    this.suppressNextDocumentClick = false;
                    return;
                }
                // Nếu đang có box thủ công mới quét và chưa chọn field
                if (this.manualIndex !== null) {
                    const currentIdx = this.manualIndex;
                    const currentBox = this.ocrData[currentIdx];
                    if (currentBox && currentBox.isManual && !currentBox.field && !currentBox.isDeleted) {
                        const bboxEl = e.target.closest('.bbox');
                        const manualSelectEl = e.target.closest('.manual-select');
                        const clickedInsideCurrentBox = bboxEl && String(bboxEl.getAttribute('data-index')) === String(currentIdx);
                        const clickedInsideManualSelect = !!manualSelectEl;
                        if (!clickedInsideCurrentBox && !clickedInsideManualSelect) {
                            // Click ra ngoài box/ select → xóa box thủ công vừa quét
                            this.deleteBox(currentIdx);
                            // Đóng dropdown thủ công nếu còn mở
                            this.selectBox.show = false;
                            this.selectBox.showDropdown = false;
                            this.isMappingManually = false;
                            this.manualField = "";
                            this.manualIndex = null;
                            this.activeIndex = null;
                            this.selectingIndex = null;
                        }
                    }
                }
            });
        },
        computed: {
            fieldData() {
                // Lọc bỏ template_name nếu không cần cho phần form mapping
                return this.fieldOptions.filter(f => f.value !== "template_name");
            },
            dataRowsCount() {
                return this.total_rows || 0;
            }
        },
        methods: {
            onTableInputClick(field, uiRowIndex) {
                // Determine column from saved mapping
                const colIdx = this.tableColumnMapping ? this.tableColumnMapping[field] : null;
                if (colIdx === null || colIdx === undefined) return;
                // uiRowIndex starts at 0 for first data row; tableInfo row_idx=uiRowIndex+1
                const tableRowIdx = (uiRowIndex + 1);
                if (!Array.isArray(this.tableInfo) || !this.tableInfo[tableRowIdx]) return;
                const row = this.tableInfo[tableRowIdx];
                const cell = row.find(c => c && c.col_idx === colIdx);
                if (!cell || !Array.isArray(cell.cell)) return;

                const coords = cell.cell; // [x1,y1,x2,y2]
                // Remove previous temp focus
                if (this.tempFocusIndex !== null && this.ocrData[this.tempFocusIndex]) {
                    this.$set(this.ocrData[this.tempFocusIndex], 'isDeleted', true);
                    this.tempFocusIndex = null;
                }
                // Create a temporary manual focus box for highlighting
                const tmpBox = {
                    text: '',
                    bbox: coords,
                    field: field,
                    isManual: true,
                    showDelete: false,
                    isDeleted: false,
                    hideBorder: false
                };
                this.ocrData.push(tmpBox);
                this.tempFocusIndex = this.ocrData.length - 1;
                this.activeIndex = this.tempFocusIndex;
                this.selectingIndex = null;
                // Ensure it renders
                this.$nextTick(() => this.$forceUpdate());
            },
            ensureTableFormSize() {
                const rows = this.dataRowsCount;
                if (!Array.isArray(this.tableForm)) this.tableForm = [];
                for (let i = 0; i < rows; i++) {
                    if (!this.tableForm[i]) {
                        this.$set(this.tableForm, i, { product_name: '', product_code: '', quantity: null });
                    }
                }
                if (this.tableForm.length > rows) {
                    this.tableForm.splice(rows);
                }
            },
            getAllowedOptionsForBox(item) {
                const isInTable = this.isBboxInTable(item.bbox);
                if (isInTable) {
                    return [
                        { value: 'product_name', label: 'Product Name' },
                        { value: 'product_code', label: 'Product Code' },
                        { value: 'quantity', label: 'Quantity' },
                    ];
                }
                return this.fieldData;
            },
            getAllowedOptionsForManual() {
                // Use current selection box to determine
                const origBbox = this.getCurrentOrigSelectBbox();
                const isInTable = origBbox ? this.isBboxInTable(origBbox) : false;
                if (isInTable) {
                    return [
                        { value: 'product_name', label: 'Product Name' },
                        { value: 'product_code', label: 'Product Code' },
                        { value: 'quantity', label: 'Quantity' },
                    ];
                }
                return this.fieldData;
            },
            getCurrentOrigSelectBbox() {
                if (!this.$refs.pdfImage || !this.imageWidth || !this.imageHeight) return null;
                const displayedWidth = this.$refs.pdfImage.clientWidth;
                const displayedHeight = this.$refs.pdfImage.clientHeight;
                const scaleX = this.imageWidth / displayedWidth;
                const scaleY = this.imageHeight / displayedHeight;
                return [
                    Math.round(this.selectBox.x * scaleX),
                    Math.round(this.selectBox.y * scaleY),
                    Math.round((this.selectBox.x + this.selectBox.width) * scaleX),
                    Math.round((this.selectBox.y + this.selectBox.height) * scaleY)
                ];
            },
            isBboxInTable(bbox) {
                if (!this.table_box || this.table_box.length !== 4) return false;
                return this.isBoxInside(bbox, this.table_box);
            },
            getColumnIndexForBbox(bbox) {
                // Determine which column this bbox belongs to using table header row (row_idx = 0)
                if (!Array.isArray(this.tableInfo) || this.tableInfo.length === 0) return null;
                const headerRow = this.tableInfo[0];
                if (!Array.isArray(headerRow)) return null;

                // Use x-overlap with header cells to pick the best matching column
                let bestCol = null;
                let bestOverlap = 0;
                const [bx1, by1, bx2, by2] = bbox;
                headerRow.forEach(cell => {
                    if (!cell || !Array.isArray(cell.cell)) return;
                    const [cx1, cy1, cx2, cy2] = cell.cell;
                    const overlapX = Math.max(0, Math.min(bx2, cx2) - Math.max(bx1, cx1));
                    const headerWidth = cx2 - cx1;
                    const ratio = headerWidth > 0 ? overlapX / headerWidth : 0;
                    if (ratio > bestOverlap) {
                        bestOverlap = ratio;
                        bestCol = cell.col_idx;
                    }
                });
                if (bestOverlap > 0) return bestCol;
                return null;
            },
            populateTableColumn(field, colIdx) {
                // Fill tableForm values from table cells for the given column index, skipping header (row_idx 0)
                console.log(`Populating table column for field "${field}" at colIdx:`, colIdx);
                this.ensureTableFormSize();
                if (!Array.isArray(this.tableInfo)) return;
                for (let r = 1; r < this.tableInfo.length; r++) {
                    const row = this.tableInfo[r];
                    const dataRowIndex = r - 1; // because header is row 0
                    if (!row || !Array.isArray(row)) continue;
                    const cell = row.find(c => c && c.col_idx === colIdx);
                    const value = cell ? (cell.text || (Array.isArray(cell.texts) ? cell.texts.join(' ') : '')) : '';
                    if (!this.tableForm[dataRowIndex]) {
                        this.$set(this.tableForm, dataRowIndex, { product_name: '', product_code: '', quantity: null });
                    }
                    if (field === 'quantity') {
                        const num = value ? Number((value + '').replace(/[^0-9.-]/g, '')) : null;
                        this.$set(this.tableForm[dataRowIndex], field, isNaN(num) ? null : num);
                    } else {
                        this.$set(this.tableForm[dataRowIndex], field, (value || '').toString());
                    }

                    console.log(`Row ${dataRowIndex} (${field}):`, value, cell);
                }
            },
            applyTableMappingIfInTable(itemField, bbox) {
                if (!itemField) return false;
                if (!this.isBboxInTable(bbox)) return false;
                // Restrict to table fields only
                if (!['product_name','product_code','quantity'].includes(itemField)) return false;
                const colIdx = this.getColumnIndexForBbox(bbox);
                if (colIdx === null || colIdx === undefined) return false;
                this.$set(this.tableColumnMapping, itemField, colIdx);
                this.populateTableColumn(itemField, colIdx);
                return true;
            },
            startResize(e, index, handle) {
                e.stopPropagation();
                this.resizing = {
                    index,
                    handle,
                    startX: e.clientX,
                    startY: e.clientY,
                    origBox: [...this.ocrData[index].bbox], // [x1, y1, x2, y2]
                };

                document.addEventListener("mousemove", this.onResizing);
                document.addEventListener("mouseup", this.stopResize);
            },
            onResizing(e) {
                if (!this.resizing) return;

                const { index, handle, startX, startY, origBox } = this.resizing;
                const dx = (e.clientX - startX) * (this.imageWidth / this.$refs.pdfImage.clientWidth);
                const dy = (e.clientY - startY) * (this.imageHeight / this.$refs.pdfImage.clientHeight);

                let [x1, y1, x2, y2] = origBox;

                if (handle === 'top-left') {
                    x1 += dx; y1 += dy;
                } else if (handle === 'top-right') {
                    x2 += dx; y1 += dy;
                } else if (handle === 'bottom-left') {
                    x1 += dx; y2 += dy;
                } else if (handle === 'bottom-right') {
                    x2 += dx; y2 += dy;
                } else if (handle === 'top') {
                    y1 += dy;
                } else if (handle === 'bottom') {
                    y2 += dy;
                } else if (handle === 'left') {
                    x1 += dx;
                } else if (handle === 'right') {
                    x2 += dx;
                }

                // giữ không cho x1 > x2, y1 > y2
                if (x1 < x2 && y1 < y2) {
                    const scaleX = this.$refs.pdfImage.clientWidth / this.imageWidth;
                    const scaleY = this.$refs.pdfImage.clientHeight / this.imageHeight;
                    const newBbox = [
                        Math.round(x1),
                        Math.round(y1),
                        Math.round(x2),
                        Math.round(y2)
                    ];
                    if (this.ocrData[index].isManual) {
                        this.$set(this.ocrData[index], "bbox", newBbox);
                    } else {
                        this.selectBox = {
                            ...this.selectBox,
                            x: Math.round(x1 * scaleX),
                            y: Math.round(y1 * scaleY),
                            width: Math.round((x2 - x1) * scaleX),
                            height: Math.round((y2 - y1) * scaleY),
                            show: true,
                        };
                        this.resizing.newBbox = newBbox;
                    }
                }

            },
            stopResize() {
                document.removeEventListener("mousemove", this.onResizing);
                document.removeEventListener("mouseup", this.stopResize);

                if (!this.resizing) return;
                const { index, newBbox } = this.resizing;
                const targetBox = this.ocrData[index];

                if (targetBox) {
                    if (!targetBox.isManual && newBbox) {
                        const newBox = {
                            ...targetBox,
                            bbox: newBbox,
                            isManual: true,
                            isDeleted: false,
                            showDelete: true,
                            text: "",
                        };
                        this.$set(this.ocrData[index], "isDeleted", true);
                        this.ocrData.push(newBox);
                        this.selectingIndex =  this.ocrData.length - 1;
                        this.updateHiddenBorders(newBox.bbox);

                    } else if (targetBox.isManual) {
                        this.updateHiddenBorders(targetBox.bbox);
                    }
                }

                this.resizing = null;
                this.selectBox.show = false;
            },
            updateHiddenBorders(manualBox) {
                this.ocrData.forEach(item => {
                    if (!item.isManual) {
                        item.hideBorder = this.isBoxInside(item.bbox, manualBox);
                    }
                });
            },
            deleteBox(index) {
                const item = this.ocrData[index];
                if (item.isManual) {
                    const manualBbox = item.bbox;
                    // Hiện lại border các box OCR gốc nằm trong vùng thủ công
                    this.ocrData.forEach(o => {
                        if (!o.isManual && this.isBoxInside(o.bbox, manualBbox)) {
                            o.hideBorder = false;
                        }
                    });
                    // Đánh dấu xoá vùng thủ công
                    this.ocrData[index].isDeleted = true;
                    this.ocrData[index].showDelete = false;

                    // Reset trạng thái nếu đây là vùng đang chọn
                    if (this.manualIndex === index) {
                        this.isMappingManually = false;
                        this.selectBox.show = false;
                        this.selectBox.showDropdown = false;
                        this.manualField = "";
                        this.manualIndex = null;
                    }
                    this.selectingIndex = null;
                    this.activeIndex = null;
                }
            },
            // Xử lý data sau khi image đã load
            processLoadedData() {
                this.autoMapFieldsFromFormData();
                // Force re-render để đảm bảo các box được vẽ
                this.$nextTick(() => {
                    this.$forceUpdate();
                });
            },
            autoMapFieldsFromFormData() {
                this.manualBoxData = {};
                if(this.is_template) {
                    this.formData = {};
                }

                const tolerance = 20; // ngưỡng chenh lech toa do y cho cùng 1 hàng
                Object.keys(this.dataMapping).forEach(fieldName => {
                    let { coords, text } = this.dataMapping[fieldName];
                    let foundItems = this.ocrData
                        .filter(item => this.isBoxInside(item.bbox, coords) && item.text.trim())
                        .map(item => ({
                            text: this.getPartialText(item.text, item.bbox, coords),
                            bbox: item.bbox
                        }))
                        .sort((a, b) =>
                            Math.abs(a.bbox[1] - b.bbox[1]) < tolerance
                                ? a.bbox[0] - b.bbox[0] // cùng hàng → trái sang phải
                                : a.bbox[1] - b.bbox[1] // khác hàng → trên xuống dưới
                        );


                    const combinedText = foundItems.map(f => f.text.trim());
                    const finalText = combinedText.join(" ");
                    this.dataMapping[fieldName] = {
                        text: finalText,
                        coords: coords
                    };
                    if (this.is_template) {
                        this.formData[fieldName] = finalText && finalText.trim() !== "" ? finalText : text;
                    }

                    this.manualBoxData[fieldName] = {
                        text: finalText,
                        coords: coords
                    };
                });

            },
            onImageLoad() {
                const img = this.$refs.pdfImage;
                this.imageWidth = img.naturalWidth;
                this.imageHeight = img.naturalHeight;
                if (this.ocrData && this.ocrData.length > 0) {
                    console.log('Image loaded and data exists, processing now');
                    this.processLoadedData();
                } else {
                    console.log('Image loaded but no data yet');
                }
            },
            getBoxStyle(item, index) {
                if (!this.imageWidth || !this.imageHeight || !this.$refs.pdfImage) {
                    return {};
                }

                const [x1, y1, x2, y2] = item.bbox;
                const displayedWidth = this.$refs.pdfImage.clientWidth;
                const displayedHeight = this.$refs.pdfImage.clientHeight;

                const scaleX = displayedWidth / this.imageWidth;
                const scaleY = displayedHeight / this.imageHeight;

                const left = Math.round(x1 * scaleX);
                const top = Math.round(y1 * scaleY);
                const width = Math.round((x2 - x1) * scaleX);
                const height = Math.round((y2 - y1) * scaleY);

                return {
                    position: 'absolute',
                    left: `${left}px`,
                    top: `${top}px`,
                    width: `${width}px`,
                    height: `${height}px`,
                    border: item.hideBorder ? '2px solid #ccc' : '2px solid ' + (index === this.activeIndex ? '#199601' : '#ff5252'),
                    boxSizing: 'border-box',
                    cursor: 'pointer',
                    zIndex: item.isManual ? 30 : 10
                };
            },
            highlightField(field) {
                let coords, text;
                let isFromDB = false;

                // Kiểm tra xem field này có phải từ DB không
                if (this.dataMapping && this.dataMapping[field]) {
                    isFromDB = true;
                    coords = this.dataMapping[field].coords;
                    text = this.dataMapping[field].text;
                    console.log(`Using dataMapping for field "${field}":`, coords, text);
                } else {
                    // Kiểm tra xem ocrData đã có box nào với field này chưa
                    const existingBox = this.ocrData.find(b => b.field === field && !b.isDeleted);
                    if (this.manualBoxData[field]) {
                        // Nếu không có trong ocrData, dùng manualBoxData (tọa độ mới)
                        coords = this.manualBoxData[field].coords;
                        text = this.manualBoxData[field].text;
                        console.log(`Using manualBoxData (new coordinates) for field "${field}":`, coords, text);
                    }else if (existingBox) {
                        coords = existingBox.bbox;
                        text = existingBox.text;
                        console.log(`Using existing box for field "${field}":`, coords, text);
                    }
                }

                if (coords) {
                    this.createManualBoxFromDB(field, coords, text);
                }

                // Tìm lại index của box để set active
                let idx = -1;
                for (let i = this.ocrData.length - 1; i >= 0; i--) {
                    const it = this.ocrData[i];
                    if (!it.isDeleted && it.field === field) {
                        idx = i;
                        break;
                    }
                }

                if (idx !== -1) {
                    this.activeIndex = idx;
                    // Reset selectingIndex để không hiển thị dropdown khi highlight từ input
                    this.selectingIndex = null;
                } else {
                    this.activeIndex = null;
                }
            },
            // Xử lý khi click vào input
            onInputClick(fieldName) {
                // Kiểm tra xem field này có data không
                const fieldValue = this.formData[fieldName];
                if (fieldValue && fieldValue.trim()) {
                    // Nếu có data từ DB, highlight và focus vào box tương ứng
                    this.highlightField(fieldName);

                    // Không ẩn nút xóa các box khác để tránh nhầm lẫn
                    // Chỉ highlight box tương ứng
                }
            },
            // Xóa tất cả focus
            removeAllFocus() {
                // Reset active index (chỉ mất màu xanh, không xóa box)
                this.activeIndex = null;
                this.selectingIndex = null;

                // Cleanup temporary focus box if any
                if (this.tempFocusIndex !== null) {
                    const box = this.ocrData[this.tempFocusIndex];
                    if (box) this.$set(box, 'isDeleted', true);
                    this.tempFocusIndex = null;
                }

                // Không ẩn nút xóa các box để tránh nhầm lẫn
                // Chỉ reset focus
            },

            // Xóa box quét chọn chưa hoàn thành
            removeIncompleteBoxes() {
                // Xóa box quét chọn chưa hoàn thành (chưa có field)
                this.ocrData = this.ocrData.filter(item => {
                    if (item.isManual && !item.field && item.showDelete) {
                        // Chỉ xóa box manual chưa có field
                        return false;
                    }
                    return true;
                });

                // Reset trạng thái quét chọn
                this.selectBox.show = false;
                this.selectBox.showDropdown = false;
                this.isMappingManually = false;
                this.manualField = "";
                this.manualIndex = null;
            },
            // Xử lý khi click vào box
            onBoxClick(index) {
                const item = this.ocrData[index];

                // Kiểm tra xem field này có phải từ DB không
                const isFromDB = this.dataMapping && this.dataMapping[item.field];

                // Kiểm tra xem data có được ghi đè không (so sánh với data gốc từ DB)
                const isDataOverridden = item.field && isFromDB &&
                    this.formData[item.field] !== this.dataMapping[item.field].text;

                // Set active index và hiển thị nút xóa cho box được click
                this.activeIndex = index;

                // Hiển thị nút xóa cho box được click (nếu là manual box)
                if (item.isManual) {
                    item.showDelete = true;
                }

                // Không ẩn nút xóa các box khác để tránh nhầm lẫn
                // Chỉ hiển thị nút xóa cho box được click

                if (item.isManual) {
                    // Manual box
                    if (isFromDB && !isDataOverridden) {
                        // Manual box từ DB chưa ghi đè, KHÔNG cho chọn option
                        this.selectingIndex = null;
                    } else {
                        // Manual box từ DB có data ghi đè HOẶC manual box bình thường, CHO PHÉP chọn option
                        this.selectingIndex = index;
                    }
                } else if (item.field) {
                    // Box OCR có field
                    if (isFromDB && !isDataOverridden) {
                        // Box có field từ DB chưa ghi đè, KHÔNG cho chọn option
                        this.selectingIndex = null;
                    } else {
                        // Box có field từ DB đã ghi đè HOẶC field mới, CHO PHÉP chọn option
                        this.selectingIndex = index;
                    }
                } else {
                    // Box OCR thông thường (chưa có field), cho phép hiển thị dropdown
                    this.selectingIndex = index;
                }
            },
            startSelect(e) {
                if (e.button !== 0) return; // Chỉ cho phép left click
                // Bỏ qua nếu click trên dropdown thủ công
                if (e.target.closest && e.target.closest('.manual-select')) return;
                this.isSelecting = true;
                const rect = this.$refs.pdfContainer.getBoundingClientRect();
                this.selectBox.startX = e.clientX - rect.left;
                this.selectBox.startY = e.clientY - rect.top;
                this.selectBox.x = this.selectBox.startX;
                this.selectBox.y = this.selectBox.startY;
                this.selectBox.width = 0;
                this.selectBox.height = 0;
                this.selectBox.show = true;
                this.selectBox.showDropdown = false;
                this.manualField = "";
            },
            onSelect(e) {
                if (!this.isSelecting) return;
                const rect = this.$refs.pdfContainer.getBoundingClientRect();
                const currentX = e.clientX - rect.left;
                const currentY = e.clientY - rect.top;
                this.selectBox.x = Math.min(currentX, this.selectBox.startX);
                this.selectBox.y = Math.min(currentY, this.selectBox.startY);
                this.selectBox.width = Math.abs(currentX - this.selectBox.startX);
                this.selectBox.height = Math.abs(currentY - this.selectBox.startY);
            },
            endSelect(e) {
                if (!this.isSelecting) return;
                this.isSelecting = false;

                if (this.selectBox.width < 10 || this.selectBox.height < 10) {
                    this.selectBox.show = false;
                    return;
                }

                // displayed coords (như hiện tại, dùng để hiển thị select overlay)
                const dispX1 = this.selectBox.x;
                const dispY1 = this.selectBox.y;
                const dispX2 = this.selectBox.x + this.selectBox.width;
                const dispY2 = this.selectBox.y + this.selectBox.height;

                // scale: displayed -> original (sửa lại để chính xác hơn)
                const displayedWidth = this.$refs.pdfImage.clientWidth;
                const displayedHeight = this.$refs.pdfImage.clientHeight;
                const scaleX = this.imageWidth / displayedWidth;
                const scaleY = this.imageHeight / displayedHeight;

                // bbox ở hệ gốc (original image pixels) — dùng để so sánh với ocrData và lưu vào ocrData
                const origBbox = [
                    Math.round(dispX1 * scaleX),
                    Math.round(dispY1 * scaleY),
                    Math.round(dispX2 * scaleX),
                    Math.round(dispY2 * scaleY)
                ];

                // Ẩn border các box OCR gốc nằm giao nhau với vùng thủ công (dùng coords gốc)
                this.ocrData.forEach(item => {
                    if (!item.isManual && this.isBoxInside(item.bbox, origBbox)) {
                        item.hideBorder = true;
                    }
                });

                // Thêm box thủ công (lưu theo coords gốc)
                this.ocrData.push({
                    text: "",
                    bbox: origBbox,
                    field: "",
                    isManual: true,
                    showDelete: true, // Hiển thị nút xóa ngay khi quét chọn
                    isDeleted: false,
                    hideBorder: false
                });

                this.manualIndex = this.ocrData.length - 1;
                this.isMappingManually = true;
                this.selectBox.showDropdown = true;

                // Set active index cho box mới tạo
                this.activeIndex = this.ocrData.length - 1;

                // Sau khi thả chuột, bỏ qua click document kế tiếp
                this.suppressNextDocumentClick = true;

                // Không stopPropagation để event có thể lan truyền bình thường
                // e.stopPropagation();
                // e.preventDefault();

            },
            applyMapping() {
                const item = this.ocrData[this.selectingIndex];
                if (!item) return;

                console.log(`Applying mapping for index:`, item);
                this.ocrData.forEach((box, i) => {
                    if (i !== this.selectingIndex && box.field === item.field) {
                        box.field = '';
                    }
                });
                if (item.isManual) {
                    // Nếu là manual box, chuyển sang chế độ manual mapping
                    this.manualIndex = this.selectingIndex;
                    this.manualField = item.field || "";
                    // Nếu trong vùng bảng, xử lý theo bảng trước
                    const handled = this.applyTableMappingIfInTable(this.manualField, this.ocrData[this.manualIndex].bbox);
                    if (!handled) {
                        this.applyManualMapping();
                    } else {
                        // reset selectingIndex if handled by table mapping
                        this.selectingIndex = null;
                        this.selectBox.show = false;
                        this.selectBox.showDropdown = false;
                        this.isMappingManually = false;
                        this.manualField = "";
                        this.manualIndex = null;
                    }
                    return;
                }

                // Xử lý box OCR (có thể chưa có field hoặc đã có field)
                if (item.field) {
                    // Nếu trong vùng bảng, xử lý theo bảng
                    const handled = this.applyTableMappingIfInTable(item.field, item.bbox);
                    console.log(`applyMapping: field=${item.field}, handled by table=${handled}`);
                    if (handled) {
                        this.selectingIndex = null;
                        return;
                    }

                    // Cập nhật formData để hiển thị trong input
                    this.formData[item.field] = item.text || '';
                    // Cập nhật manualBoxData với tọa độ mới (box OCR không có nút xóa)
                    this.manualBoxData[item.field] = {
                        coords: item.bbox,
                        text: item.text || '',
                        isFromOCR: true  // Đánh dấu đây là box OCR, không phải quét chọn
                    };

                    // Xóa dataMapping cũ để tránh focus về tọa độ cũ
                    if (this.dataMapping && this.dataMapping[item.field]) {
                        delete this.dataMapping[item.field];
                    }
                    this.activeIndex = this.selectingIndex;
                }

                this.selectingIndex = null;
            },
            applyManualMapping() {
                if (!this.manualField) return;
                const manualIndex = this.manualIndex;

                const newBbox = this.ocrData[manualIndex].bbox;

                // Nếu trong vùng bảng, ưu tiên xử lý bảng và thoát
                const handled = this.applyTableMappingIfInTable(this.manualField, newBbox);
                if (handled) {
                    this.isMappingManually = false;
                    this.selectBox.show = false;
                    this.selectBox.showDropdown = false;
                    this.manualField = "";
                    this.manualIndex = null;
                    return;
                }

                //console.log(`manual for field "${this.manualField}" at index ${manualIndex} with bbox:`, newBbox);
                this.ocrData.forEach((box, i) => {
                    if (i !== manualIndex && box.field === this.ocrData[manualIndex].field) {
                        box.field = '';
                    }
                });

                let combinedText = [];
                let foundItems = [];

                // Tìm tất cả các box OCR nằm trong vùng manual
                this.ocrData.forEach(item => {
                    if (!item.isManual && this.isBoxInside(item.bbox, newBbox) && item.text.trim()) {
                        const partial = this.getPartialText(item.text, item.bbox, newBbox);

                        foundItems.push({
                            text: partial,
                            bbox: item.bbox,
                            index: this.ocrData.indexOf(item)
                        });
                    }
                });

                // Sắp xếp các item theo vị trí (từ trái sang phải, từ trên xuống dưới)
                foundItems.sort((a, b) => {
                    // Ưu tiên theo Y trước (hàng), sau đó theo X (cột)
                    if (Math.abs(a.bbox[1] - b.bbox[1]) < 20) { // Cùng hàng (tolerance 20px)
                        return a.bbox[0] - b.bbox[0]; // Sắp xếp theo X
                    }
                    return a.bbox[1] - b.bbox[1]; // Sắp xếp theo Y
                });

                // Gộp text theo thứ tự đã sắp xếp
                foundItems.forEach(item => {
                    combinedText.push(item.text.trim());
                });

                const finalText = combinedText.join(" ");

                this.ocrData[manualIndex].field = this.manualField;
                // this.ocrData[manualIndex].showDelete = true; // Hiển thị nút xóa sau khi hoàn thành mapping

                console.log('123',this.ocrData[manualIndex])
                this.formData[this.manualField] = finalText.trim();
                this.manualBoxData[this.manualField] = {
                    coords: newBbox,
                    text: finalText.trim(),
                    isFromOCR: false  // Đánh dấu đây là box quét chọn, không phải OCR
                };

                // Xóa dataMapping cũ để tránh focus về tọa độ cũ
                if (this.dataMapping && this.dataMapping[this.manualField]) {
                    delete this.dataMapping[this.manualField];
                }

                // Reset trạng thái chọn
                this.isMappingManually = false;
                this.selectBox.show = false;
                this.selectBox.showDropdown = false;
                this.manualField = "";
                this.manualIndex = null;

                // Giữ nguyên nút xóa cho box vừa hoàn thành
                // Không ẩn nút xóa các box khác để tránh nhầm lẫn

            },
            isBoxInside(inner, outer) {
                // inner: bbox của OCR item [x1, y1, x2, y2]
                // outer: bbox của vùng manual [x1, y1, x2, y2]

                // Kiểm tra xem box OCR có nằm hoàn toàn trong vùng manual không
                const isFullyInside = (
                    inner[0] >= outer[0] && // left edge
                    inner[1] >= outer[1] && // top edge
                    inner[2] <= outer[2] && // right edge
                    inner[3] <= outer[3]    // bottom edge
                );

                // Kiểm tra xem box OCR có giao nhau với vùng manual không
                const isOverlapping = !(
                    inner[2] < outer[0] || // inner.right < outer.left  → hoàn toàn bên trái
                    inner[0] > outer[2] || // inner.left > outer.right → hoàn toàn bên phải
                    inner[3] < outer[1] || // inner.bottom < outer.top → hoàn toàn phía trên
                    inner[1] > outer[3]    // inner.top > outer.bottom → hoàn toàn phía dưới
                );
                // console.log(`isBoxInside: inner=${inner}, outer=${outer}, isFullyInside=${isFullyInside}, isOverlapping=${isOverlapping}`);
                // Trả về true nếu box OCR nằm hoàn toàn trong hoặc giao nhau đáng kể
                return isFullyInside || isOverlapping;
            },
            getPartialText(text, bbox, selectBbox) {
                const [x1, y1, x2, y2] = bbox;
                const [sx1, sy1, sx2, sy2] = selectBbox;
                const boxWidth = x2 - x1;
                let startRatio = Math.max(0, (sx1 - x1) / boxWidth);
                let endRatio   = Math.min(1, (sx2 - x1) / boxWidth);

                const startIndex = Math.floor(startRatio * text.length);
                const endIndex   = Math.ceil(endRatio * text.length);

                return text.substring(startIndex, endIndex).trim();
            },
            getSelectStyle(item) {
                if (!this.imageWidth) return { position: 'absolute' };

                const [x1, y1, x2, y2] = item.bbox;
                const displayedWidth = this.$refs.pdfImage.clientWidth;
                const displayedHeight = this.$refs.pdfImage.clientHeight;
                const scaleX = displayedWidth / this.imageWidth;
                const scaleY = displayedHeight / this.imageHeight;

                return {
                    position: 'absolute',
                    left: `${Math.round(x1 * scaleX)}px`,
                    top: `${Math.round(y2 * scaleY)}px`,
                    zIndex: 9999
                };
            },
            createManualBoxFromDB(fieldName, coordinates, text) {
                if (!this.imageWidth || !this.imageHeight) {
                    console.log('Cannot create manual box: Image not loaded');
                    return;
                }

                // Parse coordinates từ string "x1,y1,x2,y2"
                let coords;
                if (typeof coordinates === 'string') {
                    coords = coordinates.split(',').map(Number);
                } else if (Array.isArray(coordinates)) {
                    coords = coordinates;
                } else {
                    console.error('Invalid coordinates format:', coordinates);
                    return;
                }

                const [x1, y1, x2, y2] = coords;

                // Kiểm tra tọa độ có hợp lệ không
                if (x1 >= 0 && y1 >= 0 && x2 > x1 && y2 > y1 &&
                    x2 <= this.imageWidth && y2 <= this.imageHeight) {

                    // Xóa box cũ có cùng fieldName trước khi tạo mới (chỉ xóa manual box)
                    this.ocrData = this.ocrData.filter(box => !(box.field === fieldName && box.isManual));
                    const manualBox = {
                        text: text || '',
                        bbox: coords,
                        field: fieldName,
                        isManual: true,
                        showDelete: true,
                        isDeleted: false,
                        hideBorder: true
                    };

                    this.ocrData.push(manualBox);

                    // Force re-render
                    this.$forceUpdate();
                } else {
                    console.warn('Invalid coordinates for manual box:', coords);
                }
            },
            async loadOCRData() {

                try {
                    const res = await fetch(`/ocr/data-list`);
                    const data = await res.json();

                    if (data.error) {
                        console.error('Error loading data:', data.error);
                        return;
                    }

                    this.ocrData      = data.ocrData;
                    this.tableInfo    = data.tableInfo;
                    this.table_box    = data.table_box;
                    this.total_rows   = data.total_rows;
                    this.pdfImageUrl  = data.pdfImageUrl;
                    this.fieldOptions = data.fieldOptions;
                    this.dataMapping  = data.dataMapping;
                    this.is_template  = data.is_template;
                    this.tableColumnMapping = data.tableColumnMapping || { product_name: null, product_code: null, quantity: null };

                    // Prepare table form structure
                    this.ensureTableFormSize();
                    // If template provides column mapping, populate values now
                    Object.keys(this.tableColumnMapping || {}).forEach(k => {
                        const col = this.tableColumnMapping[k];
                        if (col !== null && col !== undefined) {
                            this.populateTableColumn(k, col);
                        }
                    });
                    //console.log('Loaded OCR data:', this.ocrData);

                } catch (error) {
                    console.error('Error in loadOCRData:', error);
                }
            },
            async saveTemplate() {

                let customer_name = null;
                let customer_coords = null;
                let fields = [];
                const table_columns = this.tableColumnMapping || {};
                if (this.manualBoxData.customer_name) {
                    // Lấy từ manualBoxData nếu có
                    customer_name = this.manualBoxData.customer_name.text;
                    customer_coords = this.manualBoxData.customer_name.coords.join(',');
                    fields =  this.manualBoxData;
                    console.log('Using manualBoxData for customer_name:', customer_name, customer_coords);
                } else {
                    const found = this.ocrData.find(item => item.field === 'customer_name');
                    if (found) {
                        customer_name = found.text;
                        customer_coords = found.field_xy;
                    }

                    const fieldsByName = {};
                    this.ocrData.forEach(box => {
                        if (box.field && !box.isDeleted) {
                            fieldsByName[box.field] = {
                                text: box.field,
                                coords: box.field_xy || ''
                            };
                        }
                    });
                    fields = (fieldsByName);
                    console.log('Using ocrData for customer_name:', customer_name, customer_coords);
                }

                if (!customer_coords || !customer_name) {
                    alert("Bạn phải map customer_name (quét/select) trước khi lưu.");
                    return;
                }

                const payload = {
                    customer_name_text: customer_name || '',
                    template_name: this.formData.template_name || this.formData.customer_name,
                    customer_name_xy: customer_coords || [],
                    fields: fields,
                    table_columns: table_columns
                };

                try {
                    const res = await fetch('/ocr/save-template', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                        },
                        body: JSON.stringify(payload)
                    });
                    const json = await res.json();
                    if (json.success) {
                        alert(json.message);
                    } else {
                        alert('Save failed');
                    }
                } catch (err) {
                    console.error(err);
                    alert('Save error');
                }
            },

        }
    });

</script>


</body></html>