index.blade.php 40.2 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
<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>
    <style>
        body { font-family: sans-serif; background: #f5f5f5; }
        #app { display: flex; gap: 20px; padding: 20px; }
        .left-panel {
            width: 500px; background: #fff; padding: 15px;
            border-radius: 8px; box-shadow: 0 0 5px rgba(0,0,0,0.1);
        }
        .form-group { margin-bottom: 15px; }
        .form-group label { font-weight: bold; display: block; margin-bottom: 5px; }
        .form-group input { width: 100%; padding: 6px; border: 1px solid #ccc; border-radius: 4px; }
        .right-panel { flex: 1; position: relative; background: #eee; border-radius: 8px; overflow: hidden; user-select: none; }
        .pdf-container { position: relative; display: inline-block; }
        .bbox {
            position: absolute;
            border: 2px solid #ff5252;
            /*background-color: rgba(255, 82, 82, 0.2);*/
            cursor: pointer;
        }
        .bbox.active {
            border-color: #199601 !important;
            background-color: rgba(25, 150, 1, 0.4) !important;
        }

        .bbox.focus-highlight {
            animation: focusPulse 2s ease-in-out;
            /*border-color: #ff6b35 !important;*/
            /*background-color: rgba(255, 107, 53, 0.4) !important;*/
        }

        @keyframes focusPulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        select {
            position: absolute;
            z-index: 10;
            background: #fff;
            border: 1px solid #ccc;
        }
        .select-box {
            position: absolute;
            /*border: 2px dashed #2196F3;*/
            background-color: rgba(33, 150, 243, 0.2);
            pointer-events: none;
            z-index: 5;
        }
        .delete-btn {
            position: absolute;
            bottom: -10px;
            right: -10px;
            background: #ff4d4d;
            color: #fff;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            font-size: 14px;
            padding: 3px 6px;
            z-index: 20;
        }
    </style>

</head>
<body>
<meta name="csrf-token" content="{{ csrf_token() }}">
<div id="app">
    <!-- Right: PDF viewer + select tool -->
    <div class="right-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-field="item.field"
                :style="getBoxStyle(item, index)"
                @click="selectingIndex = index">

                <button v-if="item.isManual && item.showDelete"
                        class="delete-btn"
                        @click.stop="deleteBox(index)">🗑</button>
            </div>


            <!-- Dropdown OCR -->
            <select v-if="selectingIndex !== null"
                    :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 fieldData" :value="field.value">@{{ field.label }}</option>
            </select>

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

    <!-- Left: Form inputs -->
    <div class="left-panel">
        <div v-for="field in fieldOptions" :key="field.value" class="form-group">
            <label>@{{ field.label }}</label>
            <input v-model="formData[field.value]"
                   @focus="highlightField(field.value)"
                   @click="onInputClick(field.value)"
                   :readonly="field.value === 'customer_name' && !hasCustomerNameXY"
            >
        </div>
        <button @click="saveTemplate">💾Save</button>
{{--        <button @click="debugCoordinates" style="margin-left: 10px; background: #6c757d;">🐛Debug</button>--}}
{{--        <button @click="testManualBox" style="margin-left: 10px; background: #28a745;">🧪Test Box</button>--}}
    </div>

</div>


<script>
    new Vue({
        el: '#app',
        data() {
            return {
                pdfImageUrl: "",
                selectingIndex: null,
                isMappingManually: false,
                isSelecting: false,
                activeIndex: null,
                manualField: "",
                formData: {},
                fieldOptions: [],
                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
            }
        },
        created() {
            // Chỉ tạo formData cho các field cần mapping
            this.fieldOptions
                .filter(f => f.value !== "template_name")
                .forEach(f => {
                    this.$set(this.formData, f.value, "");
                });
        },
        mounted() {
            this.loadOCRData();
        },
        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");
            }
        },
        methods: {
            // Map field cho box (không set active, chỉ dùng để load data từ DB)
            mapFieldToBox(index, fieldName, text = null) {
                if (index == null) return;

                // Xóa fieldName ở box khác đảm bảo mỗi field chỉ gán cho 1 box duy nhất
                this.ocrData.forEach((box, i) => {
                    if (i !== index && box.field === fieldName) {
                        box.field = null;
                        box.field_xy = null;
                    }
                });

                // Nếu box này từng gán field khác thì bỏ reset flag và tọa độ liên quan.
                const prev = this.ocrData[index].field;
                if (prev && prev !== fieldName) {
                    if (prev === 'customer_name') {
                        this.hasCustomerNameXY = false;
                        this.customer_name_xy = '';
                    }
                    this.ocrData[index].field = null;
                    this.ocrData[index].field_xy = null;
                }

                // Gán field mới
                const bbox = this.ocrData[index].bbox; // tọa độ OCR gốc [x1, y1, x2, y2]

                const x1 = bbox[0];
                const y1 = bbox[1];
                const w = bbox[2];
                const h = bbox[3];

                const xyStr = `${x1},${y1},${w},${h}`;

                this.ocrData[index].field = fieldName;
                this.ocrData[index].field_xy = xyStr;

                // Set text
                this.formData[fieldName] = (text !== null ? text : (this.ocrData[index].text || '')).trim();

                // KHÔNG set active index (không focus)

                // Nếu là customer_name
                if (fieldName === 'customer_name') {
                    this.hasCustomerNameXY = true;
                    this.customer_name_xy = xyStr;
                }
            },

            // Assign field và set active (dùng khi user tương tác)
            assignFieldToBox(index, fieldName, text = null) {
                console.log(`Assigning field "${fieldName}" to box at index ${index} with text: "${text}"`);
                if (index == null) return;

                // Xóa fieldName ở box khác
                this.ocrData.forEach((box, i) => {
                    if (i !== index && box.field === fieldName) {
                        box.field = null;
                        box.field_xy = null;
                    }
                });

                // Nếu box này từng gán field khác thì bỏ
                const prev = this.ocrData[index].field;
                if (prev && prev !== fieldName) {
                    if (prev === 'customer_name') {
                        this.hasCustomerNameXY = false;
                        this.customer_name_xy = '';
                    }
                    this.ocrData[index].field = null;
                    this.ocrData[index].field_xy = null;
                }

                // Gán field mới
                const bbox = this.ocrData[index].bbox; // tọa độ OCR gốc [x1, y1, x2, y2]

                console.log('2222222222222222',bbox);
                const x1 = bbox[0];
                const y1 = bbox[1];
                const w = bbox[2];
                const h = bbox[3];

                const xyStr = `${x1},${y1},${w},${h}`;

                this.ocrData[index].field = fieldName;
                this.ocrData[index].field_xy = xyStr;

                // Set text
                this.formData[fieldName] = (text !== null ? text : (this.ocrData[index].text || '')).trim();

                // Active index (focus vào box này)
                this.activeIndex = index;

                // Nếu là customer_name
                if (fieldName === 'customer_name') {
                    this.hasCustomerNameXY = true;
                    this.customer_name_xy = xyStr;
                }
            },


            async saveTemplate() {

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

                // build fields array: lấy những box có field gán, map unique by field name -> sử dụng field_xy
                const fieldsByName = {};
                this.ocrData.forEach(box => {
                    if (box.field && !box.isDeleted) {
                        // chỉ giữ 1 bản ghi cuối cùng cho mỗi field (box gần nhất)
                        fieldsByName[box.field] = {
                            name: box.field,
                            xy: box.field_xy || ''
                        };
                    }
                });
                // convert to array
                const fields = Object.values(fieldsByName);

                const payload = {
                    customer_name_text: this.formData.customer_name || '',
                    template_name: this.formData.template_name || this.formData.customer_name,
                    customer_name_xy: this.customer_name_xy,
                    fields: fields
                };
                // console.log(fields);
                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');
                }
            },


            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;
                    }
                }
            },


            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.pdfImageUrl  = data.pdfImageUrl;
                    this.formData     = data.formData;
                    this.fieldOptions = data.fieldOptions;
                    // Đợi image load xong trước khi xử lý
                    if (this.$refs.pdfImage && this.$refs.pdfImage.complete) {
                        this.processLoadedData();
                    } else {
                        console.log('Image not loaded yet, waiting for onImageLoad');
                        // Image sẽ được xử lý trong onImageLoad
                    }


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

            // Xử lý data sau khi image đã load
            processLoadedData() {
                // Tự động map field cho các box OCR dựa trên formData đã load
                this.autoMapFieldsFromFormData();
                // Kiểm tra và sửa lại tọa độ của các box manual
                // this.validateManualBoxes();

                // Force re-render để đảm bảo các box được vẽ
                this.$nextTick(() => {
                    this.$forceUpdate();
                });
            },

            // Tự động map field cho các box OCR dựa trên formData đã load từ DB
            autoMapFieldsFromFormData() {
                // Duyệt qua tất cả các field trong formData
                Object.keys(this.formData).forEach(fieldName => {
                    const fieldValue = this.formData[fieldName];

                    // Chỉ xử lý các field có giá trị (không phải template_name)
                    if (fieldValue && fieldValue.trim() && fieldName !== 'template_name') {
                        // Tìm box OCR phù hợp nhất để map
                        const bestMatchIndex = this.findBestMatchingBox(fieldName, fieldValue);

                        if (bestMatchIndex !== -1) {
                            // Chỉ map field, không set active (không focus)
                            this.mapFieldToBox(bestMatchIndex, fieldName, fieldValue);
                        }
                    }
                });

            },


            // Tìm box OCR phù hợp nhất để map với field
            findBestMatchingBox(fieldName, fieldValue) {
                let bestMatchIndex = -1;
                let bestScore = 0;

                this.ocrData.forEach((item, index) => {
                    if (item.isDeleted) return;

                    // Nếu box này đã được map field khác, bỏ qua
                    if (item.field && item.field !== fieldName) return;

                    // Tính điểm phù hợp dựa trên text
                    const text = item.text || '';
                    const score = this.calculateTextSimilarity(text, fieldValue);

                    if (score > bestScore) {
                        bestScore = score;
                        bestMatchIndex = index;
                    }
                });

                // Chỉ map nếu điểm phù hợp đủ cao (ví dụ > 0.5)
                return bestScore > 0.5 ? bestMatchIndex : -1;
            },

            // Tính điểm tương đồng giữa 2 text
            calculateTextSimilarity(text1, text2) {
                if (!text1 || !text2) return 0;

                const t1 = text1.toLowerCase().trim();
                const t2 = text2.toLowerCase().trim();
                // Nếu text giống hệt nhau
                if (t1 === t2) return 1.0;

                // Nếu một text là subset của text kia
                if (t1.includes(t2) || t2.includes(t1)) return 0.8;

                // Tính điểm dựa trên số ký tự giống nhau
                let commonChars = 0;
                const minLength = Math.min(t1.length, t2.length);

                for (let i = 0; i < minLength; i++) {
                    if (t1[i] === t2[i]) commonChars++;
                }

                return commonChars / Math.max(t1.length, t2.length);
            },
            onImageLoad() {
                const img = this.$refs.pdfImage;
                this.imageWidth = img.naturalWidth;
                this.imageHeight = img.naturalHeight;
                // Nếu đã có data, xử lý ngay
                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 ? 'none' : '2px solid ' + (index === this.activeIndex ? '#199601' : '#ff5252'),
                    boxSizing: 'border-box',
                    cursor: 'pointer',
                    zIndex: item.isManual ? 30 : 10
                };
            },

            highlightField(field) {
                let idx = -1;
                console.log(`Highlighting field: ${field}`);
                for (let i = this.ocrData.length - 1; i >= 0; i--) {
                    const it = this.ocrData[i];
                    if (!it.isDeleted && it.field === field) {
                        idx = i;
                        break;
                    }
                }
                console.log('ssss', idx, this.ocrData[idx]);

                if (idx !== -1) {
                    // Set active index (chuyển trạng thái active và màu xanh)
                    this.activeIndex = idx;
                    // Scroll đến box tương ứng
                    this.scrollToBox(idx);
                    // Focus vào box để người dùng thấy rõ
                    this.focusOnBox(idx);
                } else {
                    this.activeIndex = null;
                }
            },

            // Scroll đến box tương ứng
            scrollToBox(index) {
                if (!this.$refs.pdfContainer || index < 0 || index >= this.ocrData.length) return;

                const item = this.ocrData[index];
                console.log(`Scrolling to box at index ${index}:`, item);
                if (!item || item.isDeleted) return;

                // Tính vị trí hiển thị của box
                // const [x1, y1, x2, y2] = item.bbox;
                const [x1, y1, x2, y2] = item.field_xy.split(',').map(Number);
                console.log(`Box coordinates for scrolling: [${x1}, ${y1}, ${x2}, ${y2}]`);
                if (!this.imageWidth || !this.imageHeight || !this.$refs.pdfImage) return;

                const displayedWidth = this.$refs.pdfImage.clientWidth;
                const displayedHeight = this.$refs.pdfImage.clientHeight;
                const scaleX = displayedWidth / this.imageWidth;
                const scaleY = displayedHeight / this.imageHeight;

                const displayX = Math.round(x1 * scaleX);
                const displayY = Math.round(y1 * scaleY);

                // Scroll đến vị trí box
                const container = this.$refs.pdfContainer;
                const containerRect = container.getBoundingClientRect();
                const scrollTop = container.scrollTop;
                const scrollLeft = container.scrollLeft;

                // Tính vị trí scroll để box nằm ở giữa viewport
                const targetScrollTop = scrollTop + displayY - (containerRect.height / 2);
                const targetScrollLeft = scrollLeft + displayX - (containerRect.width / 2);

                container.scrollTo({
                    top: Math.max(0, targetScrollTop),
                    left: Math.max(0, targetScrollLeft),
                    behavior: 'smooth'
                });
            },

            // Focus vào box (thêm hiệu ứng nhấp nháy)
            focusOnBox(index) {
                if (index < 0 || index >= this.ocrData.length) return;

                const item = this.ocrData[index];
                if (!item || item.isDeleted) return;

                // Thêm class để tạo hiệu ứng focus
                this.$nextTick(() => {
                    const boxElement = document.querySelector(`[data-field="${item.field}"]`);
                    if (boxElement) {
                        boxElement.classList.add('focus-highlight');
                        setTimeout(() => {
                            boxElement.classList.remove('focus-highlight');
                        }, 2000);
                    }
                });
            },

            // 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, highlight và focus vào box tương ứng
                    // Chỉ khi click vào input mới focus và chuyển trạng thái active
                    this.highlightField(fieldName);
                }
            },
            startSelect(e) {
                if (this.isMappingManually || e.button !== 0) 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,
                    isDeleted: false,
                    hideBorder: false
                });

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

                e.stopPropagation();
                e.preventDefault();
            }
            ,
            applyMapping() {
                const item = this.ocrData[this.selectingIndex];

                if (item && item.isManual) {
                    this.manualIndex = this.selectingIndex;
                    this.manualField = item.field || "";
                    this.applyManualMapping();
                    return;
                }

                if (item.field) {
                    // this.formData[item.field] = item.text;
                    // this.activeIndex = this.selectingIndex;
                    this.assignFieldToBox(this.selectingIndex, item.field, item.text);
                }
                this.selectingIndex = null;
            },
            applyManualMapping() {
                if (!this.manualField) return;
                const manualIndex = this.manualIndex;

                const newBbox = this.ocrData[manualIndex].bbox;
                console.log(`33333 ${manualIndex} with field "${this.manualField}" new box ${newBbox}`);
                // console.log('Applying manual mapping for field:', this.manualField);
                // console.log('Manual bbox:', newBbox);

                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()) {
                        foundItems.push({
                            text: item.text,
                            bbox: item.bbox,
                            index: this.ocrData.indexOf(item)
                        });
                    }
                });

                // console.log('Found OCR items in manual area:', foundItems);

                // 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(" ");
                // console.log('Combined text:', finalText);

                // Gán field và text cho box manual
                this.assignFieldToBox(manualIndex, this.manualField, finalText);

                // Reset trạng thái chọn
                this.isMappingManually = false;
                this.selectBox.show = false;
                this.selectBox.showDropdown = false;
            },

            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] || // box bên trái vùng chọn
                    inner[0] > outer[2] || // box bên phải vùng chọn
                    inner[3] < outer[1] || // box phía trên vùng chọn
                    inner[1] > outer[3]    // box phía dưới vùng chọn
                );

                // 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;

                // Chiều rộng box OCR
                const boxWidth = x2 - x1;
                const boxHeight = y2 - y1;

                // Vị trí start và end tương đối trong text
                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);

                const partialText = text.substring(startIndex, endIndex).trim();

                // console.log('Partial text calculation:', {
                //     originalText: text,
                //     bbox: bbox,
                //     selectBbox: selectBbox,
                //     startRatio, endRatio,
                //     startIndex, endIndex,
                //     partialText
                // });

                return partialText;
            },
            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
                };
            },

            // Debug method để kiểm tra tọa độ
            debugCoordinates() {
                console.log('=== DEBUG COORDINATES ===');
                console.log('Image dimensions:', {
                    natural: { width: this.imageWidth, height: this.imageHeight },
                    displayed: {
                        width: this.$refs.pdfImage?.clientWidth,
                        height: this.$refs.pdfImage?.clientHeight
                    }
                });

                console.log('Scale factors:', {
                    scaleX: this.$refs.pdfImage ? this.$refs.pdfImage.clientWidth / this.imageWidth : 'N/A',
                    scaleY: this.$refs.pdfImage ? this.$refs.pdfImage.clientHeight / this.imageHeight : 'N/A'
                });

                console.log('OCR Data with coordinates:');
                this.ocrData.forEach((item, index) => {
                    if (!item.isDeleted) {
                        console.log(`Item ${index}:`, {
                            text: item.text,
                            bbox: item.bbox,
                            field: item.field,
                            isManual: item.isManual
                        });
                    }
                });
                console.log('=== END DEBUG ===');
            },

            // Kiểm tra và sửa lại tọa độ của các box manual
            validateManualBoxes() {
                if (!this.imageWidth || !this.imageHeight) {
                    console.log('validateManualBoxes: Image not loaded yet');
                    return;
                }

                this.ocrData.forEach((item, index) => {
                    if (item.isManual && !item.isDeleted) {
                        const [x1, y1, x2, y2] = item.bbox;

                        const isValid = (
                            x1 >= 0 && y1 >= 0 &&
                            x2 > x1 && y2 > y1 &&
                            x2 <= this.imageWidth && y2 <= this.imageHeight
                        );

                        if (!isValid) {
                            // Thử sửa lại tọa độ nếu có thể
                            this.fixManualBoxCoordinates(item, index);
                        }
                    }
                });

                console.log('=== END VALIDATION ===');

                // Force re-render để đảm bảo các box được vẽ đúng
                this.$nextTick(() => {
                    this.$forceUpdate();
                });
            },

            // Sửa lại tọa độ của box manual nếu bị lỗi
            fixManualBoxCoordinates(item, index) {
                console.log(`Attempting to fix manual box ${index}:`, item);

                // Nếu tọa độ âm, đặt về 0
                let [x1, y1, x2, y2] = item.bbox;

                if (x1 < 0) x1 = 0;
                if (y1 < 0) y1 = 0;
                if (x2 <= x1) x2 = x1 + 100; // Tạo width mặc định
                if (y2 <= y1) y2 = y1 + 50;  // Tạo height mặc định

                // Đảm bảo không vượt quá image bounds
                if (x2 > this.imageWidth) x2 = this.imageWidth;
                if (y2 > this.imageHeight) y2 = this.imageHeight;

                const fixedBbox = [x1, y1, x2, y2];
                console.log(`Fixed bbox for manual box ${index}:`, {
                    original: item.bbox,
                    fixed: fixedBbox
                });

                // Cập nhật tọa độ
                this.$set(this.ocrData[index], 'bbox', fixedBbox);
            },

            // Test method để tạo box manual test
            testManualBox() {
                if (!this.imageWidth || !this.imageHeight) {
                    alert('Image chưa được load. Vui lòng đợi image load xong.');
                    return;
                }

                // Tạo một box manual test ở giữa image
                const centerX = Math.round(this.imageWidth / 2);
                const centerY = Math.round(this.imageHeight / 2);
                const boxSize = 100;

                const testBbox = [
                    centerX - boxSize/2,  // x1
                    centerY - boxSize/2,  // y1
                    centerX + boxSize/2,  // x2
                    centerY + boxSize/2   // y2
                ];

                console.log('Creating test manual box:', {
                    bbox: testBbox,
                    imageDimensions: { width: this.imageWidth, height: this.imageHeight }
                });

                // Thêm box test
                this.ocrData.push({
                    text: "TEST BOX",
                    bbox: testBbox,
                    field: "test_field",
                    isManual: true,
                    showDelete: true,
                    isDeleted: false,
                    hideBorder: false
                });

                // Force re-render
                this.$forceUpdate();
            },

            // Tạo box manual từ tọa độ trong DB
            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;

                console.log('Creating manual box from DB:', {
                    fieldName,
                    coordinates,
                    parsed: coords,
                    imageDimensions: { width: this.imageWidth, height: this.imageHeight }
                });

                // 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) {

                    // Tạo box manual
                    const manualBox = {
                        text: text || '',
                        bbox: coords,
                        field: fieldName,
                        isManual: true,
                        showDelete: true,
                        isDeleted: false,
                        hideBorder: false
                    };

                    this.ocrData.push(manualBox);
                    console.log('Manual box created successfully:', manualBox);

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

        }
    });

</script>


</body></html>