import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
import React from 'react';
import { useState } from 'react';
import { PHXBadge, PHXClientQueryV3, PHXEmptyRecord, PHXFuncGetLoggedInfo, PHXSpinner, PHXTooltip, } from '../../../../..';
import useBookState from './use-book-state';
import useWarehouse from './use-warehouse';
import { dateStrToDate, fomartBookCode, getCurrentDateTime, getProfile, getRoleName, getValidBookCodeLength, triggerMessage, } from '../helper';
import { getBookScanReturnQueryV2, queryGetPrefixCode } from '../query';
import { BORROWED_STATE_CODE } from '../constants';
import { Input } from './input';
import { FORM_TYPE } from '../../../constant';
const KinhLup = () => React.createElement(MagnifyingGlassIcon, { className: 'h-4 w-4' });
function ScanBookInfo({ isCurrScan = false, isDevide = false, scanInfo, }) {
    return (React.createElement("div", { className: `flex gap-x-3 ${isDevide && 'mb-3 border-b border-gray-200 pb-3'}` },
        React.createElement("div", { className: `flex shrink-0 items-center justify-center overflow-hidden rounded-lg border border-gray-200 ${isCurrScan ? 'h-10 w-10' : 'h-8 w-8'} ${!scanInfo.image && 'bg-[#F7F7F7]'}` }, scanInfo.image ? (React.createElement("img", { alt: scanInfo.title, className: 'h-full w-auto', src: scanInfo.image })) : (React.createElement("svg", { fill: 'none', height: '13', viewBox: '0 0 13 13', width: '13', xmlns: 'http://www.w3.org/2000/svg' },
            React.createElement("path", { d: 'M9 5.5C9.82843 5.5 10.5 4.82843 10.5 4C10.5 3.17157 9.82843 2.5 9 2.5C8.17157 2.5 7.5 3.17157 7.5 4C7.5 4.82843 8.17157 5.5 9 5.5Z', fill: '#8A8A8A' }),
            React.createElement("path", { clipRule: 'evenodd', d: 'M5.5179 1.86555e-07H7.48211C8.29494 -7.05843e-06 8.95056 -1.29007e-05 9.48147 0.043364C10.0281 0.088026 10.5082 0.182385 10.9525 0.408726C11.6581 0.768251 12.2317 1.34193 12.5913 2.04754C12.8176 2.49175 12.912 2.9719 12.9566 3.51853C13 4.04944 13 4.70505 13 5.51788V7.48212C13 8.29496 13 8.95056 12.9566 9.48147C12.912 10.0281 12.8176 10.5082 12.5913 10.9525C12.2317 11.6581 11.6581 12.2317 10.9525 12.5913C10.5082 12.8176 10.0281 12.912 9.48147 12.9566C8.95056 13 8.29495 13 7.48212 13H5.51788C4.70505 13 4.04944 13 3.51853 12.9566C2.9719 12.912 2.49175 12.8176 2.04754 12.5913C1.34193 12.2317 0.768251 11.6581 0.408726 10.9525C0.182385 10.5082 0.088026 10.0281 0.043364 9.48147C-1.29007e-05 8.95056 -7.05843e-06 8.29495 1.86555e-07 7.48212V5.5179C-7.05843e-06 4.70506 -1.29007e-05 4.04944 0.043364 3.51853C0.088026 2.9719 0.182385 2.49175 0.408726 2.04754C0.768251 1.34193 1.34193 0.768251 2.04754 0.408726C2.49175 0.182385 2.9719 0.088026 3.51853 0.043364C4.04944 -1.29007e-05 4.70506 -7.05843e-06 5.5179 1.86555e-07ZM3.64068 1.53838C3.18681 1.57547 2.92604 1.6446 2.72852 1.74524C2.30516 1.96095 1.96095 2.30516 1.74524 2.72852C1.6446 2.92604 1.57547 3.18681 1.53838 3.64068C1.50058 4.10331 1.5 4.69755 1.5 5.55V6.9785L2.2228 6.11114C2.88159 5.32059 4.07697 5.26637 4.80462 5.99402L7.49999 8.68939L8.67963 7.50974C9.41716 6.77222 10.632 6.8395 11.2836 7.65396L11.4997 7.92404C11.5 7.77538 11.5 7.61768 11.5 7.45V5.55C11.5 4.69755 11.4994 4.10331 11.4616 3.64068C11.4245 3.18681 11.3554 2.92604 11.2548 2.72852C11.039 2.30516 10.6948 1.96095 10.2715 1.74524C10.074 1.6446 9.8132 1.57547 9.35932 1.53838C8.89669 1.50058 8.30245 1.5 7.45 1.5H5.55C4.69755 1.5 4.10331 1.50058 3.64068 1.53838ZM1.53838 9.35932C1.53622 9.33282 1.53417 9.30589 1.53225 9.2785C1.54743 9.26317 1.56209 9.24707 1.57615 9.23019L3.37513 7.07141C3.46924 6.95848 3.64001 6.95073 3.74396 7.05468L6.96966 10.2804C7.26255 10.5733 7.73742 10.5733 8.03032 10.2804L9.74029 8.5704C9.84565 8.46504 10.0192 8.47465 10.1123 8.59101L11.3252 10.1071C11.3037 10.1674 11.2803 10.2214 11.2548 10.2715C11.039 10.6948 10.6948 11.039 10.2715 11.2548C10.074 11.3554 9.8132 11.4245 9.35932 11.4616C8.89669 11.4994 8.30245 11.5 7.45 11.5H5.55C4.69755 11.5 4.10331 11.4994 3.64068 11.4616C3.18681 11.4245 2.92604 11.3554 2.72852 11.2548C2.30516 11.039 1.96095 10.6948 1.74524 10.2715C1.6446 10.074 1.57547 9.8132 1.53838 9.35932Z', fill: '#8A8A8A', fillRule: 'evenodd' })))),
        React.createElement("div", { className: 'w-full space-y-1 truncate' },
            React.createElement(PHXTooltip, { content: scanInfo.title },
                React.createElement("p", { className: `cursor-pointer truncate text-xs text-gray-900 xl:w-[25ch] ${isCurrScan && 'font-semibold'}` }, scanInfo.title)),
            React.createElement("p", { className: 'text-xs text-gray-500' }, scanInfo.code),
            !isCurrScan && React.createElement("p", { className: 'text-xxs text-gray-500' }, scanInfo.scanDate),
            React.createElement(PHXBadge, { text: scanInfo.status.name, type: scanInfo.status.type }))));
}
export default function ScanTicketInfo({ onChangeHistory, schoolYearId, warehouseId, }) {
    const { listBookState } = useBookState();
    const [loading, setLoading] = useState(false);
    const { prefixQrCode } = useWarehouse({ warehouseId });
    const [listHisttoryScan, setListHistoryScan] = useState([]);
    const listScanLength = listHisttoryScan.length;
    const userInfo = PHXFuncGetLoggedInfo();
    const handleScan = async (searchValue, inputEvent) => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
        if (!searchValue || searchValue.length < getValidBookCodeLength(prefixQrCode)) {
            return;
        }
        const scanDate = getCurrentDateTime();
        let result = {
            title: 'Không xác định tên sách mượn',
            code: searchValue,
            scanDate,
            status: {
                name: 'Mã sách không tồn tại',
                type: 'danger',
            },
            image: '',
        };
        try {
            if (!searchValue) {
                return;
            }
            const { data: { library_dang_ki_ca_biet }, } = await PHXClientQueryV3({
                query: getBookScanReturnQueryV2,
                variables: {
                    code: searchValue,
                    school_id: userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id,
                    warehouseId,
                    currentSchoolYearId: schoolYearId,
                },
                isDelay: false,
            });
            const book = library_dang_ki_ca_biet === null || library_dang_ki_ca_biet === void 0 ? void 0 : library_dang_ki_ca_biet[0];
            if (!book) {
                return;
            }
            const { code, id, library_book_copy, library_borrow_books, pre_state, state_id } = book;
            const ticket = (_a = library_borrow_books === null || library_borrow_books === void 0 ? void 0 : library_borrow_books[0]) === null || _a === void 0 ? void 0 : _a.library_borrow_ticket;
            const user = ticket === null || ticket === void 0 ? void 0 : ticket.user;
            let totalReturned = 0;
            (_b = ticket === null || ticket === void 0 ? void 0 : ticket.library_borrow_books) === null || _b === void 0 ? void 0 : _b.forEach((borrowBook) => {
                if (borrowBook.return_date) {
                    totalReturned += 1;
                }
            });
            const existBookDefaultInfo = {
                title: (_c = library_book_copy === null || library_book_copy === void 0 ? void 0 : library_book_copy.library_book) === null || _c === void 0 ? void 0 : _c.title,
                code,
                scanDate,
                image: (_e = (_d = library_book_copy === null || library_book_copy === void 0 ? void 0 : library_book_copy.library_book_images) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.url,
                ticketId: ticket === null || ticket === void 0 ? void 0 : ticket.id,
                borrowerName: user === null || user === void 0 ? void 0 : user.full_name,
                roleName: getRoleName(user === null || user === void 0 ? void 0 : user.user_roles),
                borrowDate: dateStrToDate(ticket === null || ticket === void 0 ? void 0 : ticket.actual_borrow_date),
                classroomName: (_h = (_g = (_f = user === null || user === void 0 ? void 0 : user.classroom_students) === null || _f === void 0 ? void 0 : _f[0]) === null || _g === void 0 ? void 0 : _g.classroom) === null || _h === void 0 ? void 0 : _h.name,
                bookBorrowId: (_j = library_borrow_books === null || library_borrow_books === void 0 ? void 0 : library_borrow_books[0]) === null || _j === void 0 ? void 0 : _j.id,
                userCode: (_k = getProfile(user)) === null || _k === void 0 ? void 0 : _k.user_code,
                expectReturnDate: dateStrToDate(ticket === null || ticket === void 0 ? void 0 : ticket.expect_return_date),
                totalReturned,
                totalBorrowed: ((_l = ticket === null || ticket === void 0 ? void 0 : ticket.library_borrow_books) === null || _l === void 0 ? void 0 : _l.length) || 0,
                bookId: id,
                preStateId: pre_state,
            };
            if (state_id !== ((_m = listBookState.find((state) => state.code === BORROWED_STATE_CODE)) === null || _m === void 0 ? void 0 : _m.id)) {
                result = {
                    ...existBookDefaultInfo,
                    status: {
                        name: 'Sách chưa được mượn',
                        type: 'warning',
                    },
                };
                onChangeHistory(result, true);
                return;
            }
            result = {
                ...existBookDefaultInfo,
                status: {
                    name: 'Đã quét thành công',
                    type: 'success',
                },
            };
            onChangeHistory(result);
        }
        catch (e) {
            console.log(e);
        }
        finally {
            setLoading(false);
            setListHistoryScan((pre) => [result, ...pre]);
            inputEvent.target.value = '';
        }
    };
    const handleGetDataPrefixQrCode = async () => {
        var _a, _b;
        setLoading(true);
        try {
            const { data } = await PHXClientQueryV3({
                query: queryGetPrefixCode,
                variables: {
                    id: warehouseId,
                },
            });
            const prefix = ((_b = (_a = data === null || data === void 0 ? void 0 : data.library_warehouse) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.qr_code_prefix) || '';
            return prefix;
        }
        catch (error) {
            console.error(error);
            return '';
        }
        finally {
            setLoading(false);
        }
    };
    const handleInputChange = async (e) => {
        var _a;
        if (loading)
            return;
        const lengthValue = e.target.value.length;
        let currentPrefix = prefixQrCode;
        // Retry
        if (!currentPrefix && lengthValue >= getValidBookCodeLength(currentPrefix)) {
            currentPrefix = await handleGetDataPrefixQrCode();
            if (!currentPrefix) {
                triggerMessage({
                    type: FORM_TYPE.CUSTOM,
                    message: 'Quét mã sách thất bại, kiểm tra kết nối',
                    isFailure: true,
                });
                return;
            }
        }
        const currValue = (_a = e.target.value) === null || _a === void 0 ? void 0 : _a.trim();
        const formatedValue = fomartBookCode(currValue, currentPrefix);
        e.target.value = formatedValue;
        if (formatedValue.length >= getValidBookCodeLength(currentPrefix)) {
            setLoading(true);
            handleScan(formatedValue, e);
        }
    };
    return (React.createElement(React.Fragment, null,
        React.createElement("style", null, `
        .scrollbar-thin::-webkit-scrollbar {
          width: 8px;
          height: 8px;
        }
        .scrollbar-thin::-webkit-scrollbar-thumb {
          background: rgb(199 199 199);
          border-radius: 16px;
          border: 2px solid transparent; /* giả padding */
          background-clip: content-box; /* giúp background nằm trong border */
        }
        `),
        React.createElement("div", { className: 'relative' },
            React.createElement(Input, { autoComplete: 'off', autoFocus: true, className: 'mb-3 h-8 overflow-hidden !border-gray-200', disabled: loading, id: 'code', onChange: handleInputChange, placeholder: 'T\u00ECm ki\u1EBFm theo m\u00E3 s\u00E1ch / Qu\u00E9t m\u00E3 s\u00E1ch', prefix: React.createElement(KinhLup, null) }),
            loading && React.createElement(PHXSpinner, { className: 'absolute right-3 top-2 h-4 w-4' })),
        listScanLength > 0 && (React.createElement("div", { className: 'rounded-lg border border-gray-200 p-4' },
            React.createElement(ScanBookInfo, { isCurrScan: true, scanInfo: listHisttoryScan[0] }))),
        React.createElement("div", { className: 'mt-4 space-y-2' },
            React.createElement("p", { className: 'text-xs text-gray-900' }, "L\u1ECBch s\u1EED qu\u00E9t m\u00E3"),
            React.createElement("div", { className: `scrollbar-thin overflow-y-auto rounded-lg border border-gray-200 p-4 ${listScanLength > 0 && 'max-h-[24rem] bg-gray-50'}` }, listScanLength > 0 ? (React.createElement(React.Fragment, null, listHisttoryScan.map((item, index) => (React.createElement(ScanBookInfo, { key: index, isDevide: index !== listScanLength - 1, scanInfo: item }))))) : (React.createElement(PHXEmptyRecord, null))))));
}
//# sourceMappingURL=scan-ticket-info.js.map