"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = ModalCreateBorrowTicket;
const tslib_1 = require("tslib");
const __1 = require("../../../../..");
const react_1 = require("react");
const react_hook_form_1 = require("react-hook-form");
const book_borrow_info_1 = tslib_1.__importDefault(require("./book-borrow-info"));
const constants_1 = require("../constants");
const use_book_state_1 = tslib_1.__importDefault(require("../library-return-ticket/use-book-state"));
const constant_1 = require("../../../constant");
const helper_1 = require("../helper");
const query_1 = require("../query");
const react_2 = tslib_1.__importDefault(require("react"));
function ModalCreateBorrowTicket({ currentSchoolYearId, educationalCodes, onHide, show, }) {
    var _a, _b;
    const { listBookState } = (0, use_book_state_1.default)();
    const [warehouseId, setWarehouseId] = (0, react_1.useState)(null);
    const studentCondition = educationalCodes.includes(constant_1.TIEU_HOC_CODE)
        ? `grade: { educational_level: { code: { _eq: ${constant_1.TIEU_HOC_CODE} } } }`
        : `grade: { educational_level: { code: { _neq: ${constant_1.TIEU_HOC_CODE} } } }`;
    const defaultFilterProfile = `
      profile_student: {
        ${studentCondition}
        student_status: { _eq: ${constants_1.KEY_STUDYING_STUDENT_STATUS} }
      }
    `;
    const [filterProfile, setFilterProfile] = (0, react_1.useState)(defaultFilterProfile);
    const { formState: { errors }, handleSubmit, register, reset, setValue, watch, } = (0, react_hook_form_1.useForm)();
    const staffAndTeacherLevel = `[${educationalCodes.join(',')}]`;
    const [defaultExpectReturnDate, setDefaultExpectReturnDate] = (0, react_1.useState)(null);
    const userInfo = (0, __1.PHXFuncGetLoggedInfo)();
    const [loading, setLoading] = (0, react_1.useState)(true);
    const [submitLoading, setSubmitLoading] = (0, react_1.useState)(false);
    const [userId, setUserId] = (0, react_1.useState)(null);
    const [bannerDescription, setBannerDescription] = (0, react_1.useState)('');
    const [bookBorrowerCode, setBookBorrowerCode] = (0, react_1.useState)(constants_1.CODE_BORROW_USER.HS);
    const [listBook, setListBook] = (0, react_1.useState)([]);
    const [dataSelect, setDataSelect] = (0, react_1.useState)({
        bookBorrower: [],
        classrooms: [],
        ticketStates: [],
        prefixQrCode: '',
    });
    const disabledSubmit = listBook.length === 0 || !userId || !watch('user_id') || !watch('expect_return_date');
    const handleRenderSelectSearchResultList = (data) => {
        var _a, _b;
        const classroom = (_b = (_a = data === null || data === void 0 ? void 0 : data.classroom_students) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.classroom;
        const profile = (0, helper_1.getProfile)(data);
        const roleName = (0, helper_1.getRoleName)(data === null || data === void 0 ? void 0 : data.user_roles);
        return `${data === null || data === void 0 ? void 0 : data.full_name} - ${profile === null || profile === void 0 ? void 0 : profile.user_code} - ${roleName}${classroom && !classroom.name ? ' - ' + (classroom === null || classroom === void 0 ? void 0 : classroom.grade.name) : ''}${classroom ? ' - ' + classroom.name : ''}`;
    };
    const defaultBookBorrower = (_a = dataSelect.bookBorrower.find((item) => item.code === constants_1.CODE_BORROW_USER.HS && item.default)) === null || _a === void 0 ? void 0 : _a.id;
    const getBorrowerRoleCode = (user) => {
        var _a, _b, _c;
        const { profile_staff, profile_student, profile_teacher } = user;
        if (profile_staff === null || profile_staff === void 0 ? void 0 : profile_staff.user_code) {
            return constants_1.CODE_BORROW_USER.NV;
        }
        if (profile_student === null || profile_student === void 0 ? void 0 : profile_student.user_code) {
            return constants_1.KEY_HOC_SINH_CODE;
        }
        if (profile_teacher === null || profile_teacher === void 0 ? void 0 : profile_teacher.user_code) {
            return constants_1.KEY_GIAO_VIEN_CODE;
        }
        return (_c = (_b = (_a = user === null || user === void 0 ? void 0 : user.user_roles) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.role) === null || _c === void 0 ? void 0 : _c.role_code;
    };
    const handleChangeBookBorrower = (user) => {
        var _a, _b, _c, _d;
        const { library_borrow_tickets: tickets } = user;
        if ((tickets === null || tickets === void 0 ? void 0 : tickets.length) > 0) {
            setBannerDescription(`Người dùng này hiện có ${tickets === null || tickets === void 0 ? void 0 : tickets.length} phiếu mượn sách`);
        }
        else {
            setBannerDescription('');
        }
        const roleCode = getBorrowerRoleCode(user);
        if (roleCode === constants_1.KEY_HOC_SINH_CODE) {
            const expectReturnDate = (0, helper_1.getDateOffsetByDays)(constants_1.TOTAL_BORROW_DAY_STUDENT, 'datePicker');
            // Lưu code của chủ thể mượn sách
            const borrowerCode = ((_b = (_a = dataSelect.bookBorrower) === null || _a === void 0 ? void 0 : _a.find((item) => item.code === constants_1.STUDENT_BORROW_INDIVIDUAL_CODE)) === null || _b === void 0 ? void 0 : _b.code) ||
                constants_1.CODE_BORROW_USER.HS;
            setBookBorrowerCode(borrowerCode);
            setValue('expect_return_date', expectReturnDate);
            setDefaultExpectReturnDate(expectReturnDate);
            return;
        }
        const expectReturnDate = (0, helper_1.getDateOffsetByDays)(constants_1.DEFAULT_TOTAL_BORROW_DAY, 'datePicker');
        const book_borrower_id = Number(watch('book_borrower_id'));
        const borrowerCode = ((_d = (_c = dataSelect.bookBorrower) === null || _c === void 0 ? void 0 : _c.find((item) => item.id === book_borrower_id)) === null || _d === void 0 ? void 0 : _d.code) ||
            (roleCode === constants_1.CODE_BORROW_USER.GV ? constants_1.CODE_BORROW_USER.GV : constants_1.CODE_BORROW_USER.NV);
        setBookBorrowerCode(borrowerCode);
        setValue('expect_return_date', expectReturnDate);
        setDefaultExpectReturnDate(expectReturnDate);
    };
    const getData = async () => {
        var _a, _b, _c;
        try {
            const { data: { classroom, library_book_borrower: bookBorrowerData, library_warehouse_educational_level, ticketStates }, } = await (0, __1.PHXClientQueryV3)({
                query: (0, query_1.getDataSelectQuery)(educationalCodes[0]),
                variables: {
                    school_id: userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id,
                    school_year_id: currentSchoolYearId,
                    educationalLevelCode: educationalCodes[0],
                },
            });
            setDataSelect({
                bookBorrower: bookBorrowerData,
                classrooms: (0, helper_1.sortClassroomByName)(classroom).map((item) => ({
                    id: item.id,
                    value: item.name,
                })),
                ticketStates,
                prefixQrCode: (_b = (_a = library_warehouse_educational_level === null || library_warehouse_educational_level === void 0 ? void 0 : library_warehouse_educational_level[0]) === null || _a === void 0 ? void 0 : _a.library_warehouse) === null || _b === void 0 ? void 0 : _b.qr_code_prefix,
            });
            setWarehouseId((_c = library_warehouse_educational_level === null || library_warehouse_educational_level === void 0 ? void 0 : library_warehouse_educational_level[0]) === null || _c === void 0 ? void 0 : _c.warehouse_id);
        }
        catch (e) {
            console.log(e);
        }
        finally {
            setLoading(false);
        }
    };
    const handleProfile = (code) => {
        if (code === constants_1.CODE_BORROW_USER.HS || code === constants_1.CODE_BORROW_USER.HS_CLASSROOM) {
            return `
      profile_student: {
        ${studentCondition}
        student_status: { _eq: ${constants_1.KEY_STUDYING_STUDENT_STATUS} }
      }
    `;
        }
        if (code === constants_1.CODE_BORROW_USER.GV || code === constants_1.CODE_BORROW_USER.GV_CLASSROOM) {
            return `
      profile_teacher: {
        educational_level_group: {
          educational_level_map_groups: {
            educational_level: {
              code: { _in: ${staffAndTeacherLevel} }
            }
          }
        }
      }
    `;
        }
        if (code === constants_1.CODE_BORROW_USER.NV) {
            return `
      profile_staff: {
        educational_level_group: {
          educational_level_map_groups: {
            educational_level: {
              code: { _in: ${staffAndTeacherLevel} }
            }
          }
        }
      }
    `;
        }
        return ``;
    };
    const handleBookBorrow = () => {
        const dataInsert = [];
        const school_id = userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id;
        listBook.forEach((book) => {
            dataInsert.push({
                created_at: 'now',
                school_id,
                dang_ki_ca_biet_id: book.id,
            });
        });
        return dataInsert;
    };
    const getPreStateBook = () => {
        const result = [];
        listBook.forEach((book) => {
            result.push({
                dang_ki_ca_biet_id: book.id,
                stateId: book.stateId,
            });
        });
        return result;
    };
    const onSubmit = async (data) => {
        var _a, _b, _c;
        setSubmitLoading(true);
        try {
            const bookBorrowInsert = handleBookBorrow();
            const bookWithPreState = getPreStateBook();
            const inWareHouseBookId = [];
            const inBookshelfBookId = [];
            bookWithPreState === null || bookWithPreState === void 0 ? void 0 : bookWithPreState.forEach((item) => {
                var _a, _b;
                const { dang_ki_ca_biet_id, stateId } = item;
                if (stateId === ((_a = listBookState.find((state) => state.code === constants_1.IN_BOOKSHELF_STATE_CODE)) === null || _a === void 0 ? void 0 : _a.id)) {
                    inBookshelfBookId.push(dang_ki_ca_biet_id);
                }
                else if (stateId === ((_b = listBookState.find((state) => state.code === constants_1.IN_WAREHOUSE_STATE_CODE)) === null || _b === void 0 ? void 0 : _b.id)) {
                    inWareHouseBookId.push(dang_ki_ca_biet_id);
                }
                else {
                    inBookshelfBookId.push(dang_ki_ca_biet_id);
                }
            });
            const dataSubmit = {
                action_code: constants_1.ACTION_LIBRARY_CREATE_TICKET,
                submitTicket: {
                    ...data,
                    total_book: [...inWareHouseBookId, ...inBookshelfBookId].length,
                    warehouse_id: warehouseId,
                    actual_borrow_date: 'now',
                    expect_return_date: (0, helper_1.formatDateMMDDYY)(data.expect_return_date),
                    user_id: userId,
                    school_id: Number(userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id),
                    created_at: 'now',
                    ticket_state_id: (_a = dataSelect.ticketStates.find((item) => item.code === constants_1.BORROWED_TICKET_CODE)) === null || _a === void 0 ? void 0 : _a.id,
                    ...(bookBorrowInsert && {
                        library_borrow_books: {
                            data: bookBorrowInsert,
                        },
                    }),
                },
                dataUpdateSateBookBorrow: {
                    inBookshelfBookId,
                    inWareHouseBookId,
                },
            };
            const resData = await __1.PHXAxiosInstance.post(`/library/borrow-ticket/create-ticket-borrow`, dataSubmit);
            const isSuccess = (_b = resData.data) === null || _b === void 0 ? void 0 : _b.success;
            const message = (_c = resData.data) === null || _c === void 0 ? void 0 : _c.message;
            if (isSuccess) {
                (0, helper_1.triggerMessage)({
                    type: constant_1.FORM_TYPE.ADD,
                });
            }
            if (!isSuccess) {
                (0, helper_1.triggerMessage)({
                    type: constant_1.FORM_TYPE.CUSTOM,
                    message,
                    isFailure: true,
                });
            }
            onHideModal();
        }
        catch (e) {
            console.error(e);
            setSubmitLoading(false);
        }
    };
    function onHideModal() {
        onHide === null || onHide === void 0 ? void 0 : onHide();
        setBannerDescription('');
        reset({
            borrow_note: '',
            borrow_reason: '',
            expect_return_date: '',
            book_borrower_id: defaultBookBorrower,
        });
        setSubmitLoading(false);
        setListBook([]);
        setDefaultExpectReturnDate(null);
    }
    (0, react_1.useEffect)(() => {
        if (bookBorrowerCode) {
            const dataFilterProfile = handleProfile(bookBorrowerCode);
            if (dataFilterProfile) {
                setFilterProfile(dataFilterProfile);
            }
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [bookBorrowerCode, setValue, warehouseId]);
    (0, react_1.useEffect)(() => {
        // fill giá trị mặc định cho lý do mượn sách
        if (show) {
            setValue('borrow_note', 'Bạn đọc đã mượn sách thành công.');
        }
    }, [show]);
    (0, react_1.useEffect)(() => {
        var _a, _b;
        const book_borrower_id = watch('book_borrower_id');
        const nextBorrowerCode = (_b = (_a = dataSelect.bookBorrower) === null || _a === void 0 ? void 0 : _a.find((item) => item.id === Number(book_borrower_id))) === null || _b === void 0 ? void 0 : _b.code;
        if (nextBorrowerCode && nextBorrowerCode !== bookBorrowerCode) {
            setBookBorrowerCode(nextBorrowerCode);
        }
    }, [watch('book_borrower_id')]);
    (0, react_1.useEffect)(() => {
        if (currentSchoolYearId && show) {
            getData();
        }
    }, [currentSchoolYearId, show]);
    return (react_2.default.createElement(__1.PHXModal, { className: 'mt-[-4rem]', disableOutsideClick: true, disableSubmit: disabledSubmit, headerClassName: 'bg-white', inCard: false, onHide: onHideModal, onSubmit: handleSubmit(onSubmit), primaryActionText: 'Th\u00EAm m\u1EDBi', primaryLoading: submitLoading, show: show, size: 'large', title: 'Th\u00EAm m\u1EDBi phi\u1EBFu m\u01B0\u1EE3n', type: 'no-padding' }, loading ? (react_2.default.createElement("div", { className: 'h-[calc(100vh-12rem)] space-y-4 bg-[#F1F1F1] p-4' },
        react_2.default.createElement(__1.PHXSkeleton, { type: 'content-modal' }),
        react_2.default.createElement(__1.PHXSkeleton, { type: 'content-modal' }),
        react_2.default.createElement(__1.PHXSkeleton, { type: 'content-modal' }))) : (react_2.default.createElement("div", { className: 'h-[calc(100vh-12rem)] space-y-4 overflow-y-auto bg-[#F1F1F1] p-4' },
        react_2.default.createElement(__1.PHXCard, { border: false, primaryHeader: true, title: 'Th\u00F4ng tin chung' },
            react_2.default.createElement("div", { className: 'space-y-4' },
                react_2.default.createElement(__1.PHXBanner, { className: 'mb-4', description: bannerDescription, hideCloseButton: true, show: !!bannerDescription, title: 'C\u1EA3nh b\u00E1o', type: 'warning' }),
                react_2.default.createElement(__1.PHXSelect, { className: 'col-span-2', defaultValue: defaultBookBorrower, label: '\u0110\u1ED1i t\u01B0\u1EE3ng m\u01B0\u1EE3n s\u00E1ch', register: register('book_borrower_id', {
                        required: true,
                    }) },
                    react_2.default.createElement("option", { value: '' }, "L\u1EF1a ch\u1ECDn"), (_b = dataSelect.bookBorrower) === null || _b === void 0 ? void 0 :
                    _b.map((item) => {
                        const { id, name } = item;
                        return (react_2.default.createElement("option", { key: id, value: id }, name));
                    })),
                react_2.default.createElement(__1.PHXSearchResultListV3, { key: bookBorrowerCode, disabled: !bookBorrowerCode, error: !!errors.user_id, errorType: 'required-field', filterArray: [
                        { keyChild: 'full_name' },
                        { keyParent: 'profile_student', keyChild: 'user_code' },
                        { keyParent: 'profile_teacher', keyChild: 'user_code' },
                        { keyParent: 'profile_staff', keyChild: 'user_code' },
                    ], getSearchResult: (value) => {
                        handleChangeBookBorrower(value);
                        setUserId(value.id);
                    }, handleCustomRender: handleRenderSelectSearchResultList, isFillInput: true, isUnaccentSearchValue: true, label: 'Ng\u01B0\u1EDDi m\u01B0\u1EE3n', name: 'user_id', placeholder: 'Nh\u1EADp t\u00EAn ho\u1EB7c m\u00E3', register: register('user_id'), search: (0, query_1.searchUserBorrow)(userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id, currentSchoolYearId, filterProfile), setValue: setValue }),
                react_2.default.createElement("div", { className: ' col-span-2' },
                    react_2.default.createElement(__1.PHXSelectBox, { data: [{ id: null, value: 'Lựa chọn' }, ...dataSelect.classrooms], 
                        // disabled={!userId}
                        label: 'Nh\u00F3m \u0111\u1ECDc gi\u1EA3', onChange: (value) => setValue('classroom_id', value.id), placeholder: 'L\u1EF1a ch\u1ECDn' })),
                defaultExpectReturnDate ? (react_2.default.createElement(__1.PHXDatePicker, { key: `visible_select_date_${defaultExpectReturnDate}`, defaultValue: defaultExpectReturnDate, error: !watch('expect_return_date'), errorType: 'required-field', id: 'expect_return_date', label: 'Ng\u00E0y tr\u1EA3 (d\u1EF1 ki\u1EBFn)', onChangeDate: ({ format }) => {
                        setValue('expect_return_date', format);
                        setDefaultExpectReturnDate(format);
                    }, placeholder: 'DD-MM-YYYY' })) : (react_2.default.createElement(__1.PHXDatePicker, { key: 'invisible_select_date', errorType: 'required-field', id: 'expect_return_date', label: 'Ng\u00E0y tr\u1EA3 (d\u1EF1 ki\u1EBFn)', placeholder: 'DD-MM-YYYY' })),
                react_2.default.createElement(__1.PHXTextarea, { className: ' col-span-2', label: 'L\u00FD do m\u01B0\u1EE3n s\u00E1ch', placeholder: 'Nh\u1EADp l\u00FD do', register: register('borrow_reason'), rows: 4 }),
                react_2.default.createElement(__1.PHXTextarea, { className: ' col-span-2', label: 'Ghi ch\u00FA l\u00FAc m\u01B0\u1EE3n', placeholder: 'Nh\u1EADp ghi ch\u00FA', register: register('borrow_note'), rows: 4 }))),
        warehouseId && (react_2.default.createElement(book_borrow_info_1.default, { bookBorrowerId: Number(watch('book_borrower_id') || defaultBookBorrower), listBookBorrower: dataSelect.bookBorrower, onChange: (data) => setListBook(data), prefixQrCode: '', warehouseId: warehouseId }))))));
}
//# sourceMappingURL=index.js.map