"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = ModalSearchUser;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importStar(require("react"));
const getLoginInfo_1 = tslib_1.__importDefault(require("../../../Func/getLoginInfo"));
const PHXGrpcClientV3_1 = require("../../../Func/GRPC/PHXGrpcClientV3");
const useDebounce_1 = tslib_1.__importDefault(require("../../../Func/useDebounce"));
const Modal_1 = require("../../../Modal");
const ResourceList_1 = require("../../../ResourceList");
const query_1 = require("../../graphql/query");
const get_role_name_by_target_1 = require("../../ultis/get-role-name-by-target");
const tranform_target_user_1 = require("../../ultis/tranform-target-user");
const remove_vn_tones_1 = require("../../../SelectWithAction/remove-vn-tones");
function ModalSearchUser({ defaultSelected, handleAddList, onHide, schoolYearId, show, target, }) {
    const [listUser, setListUser] = (0, react_1.useState)([]);
    const [currPage, setCurrPage] = (0, react_1.useState)(0);
    const userInfo = (0, getLoginInfo_1.default)();
    const [searchKeyword, setSearchKeyword] = (0, react_1.useState)('');
    const [searching, setSearching] = (0, react_1.useState)(false);
    const [loadingInit, setLoadingInit] = (0, react_1.useState)(false);
    const [isAllData, setIsAllData] = (0, react_1.useState)(false);
    const [dataSelected, setDataSelected] = (0, react_1.useState)([]);
    const debounceSearchValue = (0, useDebounce_1.default)(searchKeyword, 300);
    const getUser = async () => {
        if (currPage !== 0 && isAllData)
            return;
        if (currPage !== 0 && searching)
            return;
        setSearching(true);
        try {
            const limit = 10;
            const offset = currPage * limit;
            const query = (0, query_1.queryListUserBuilder)({
                target,
                schoolYearId,
                schoolId: userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id,
            });
            const searchKeywordNormalized = (0, remove_vn_tones_1.normalizeVietnameseText)(debounceSearchValue);
            const { data: { users }, } = await (0, PHXGrpcClientV3_1.PHXClientQueryV3)({
                query,
                variables: {
                    roleCode: target,
                    limit,
                    offset,
                    searchKeyword: `%${searchKeywordNormalized}%`,
                    schoolId: userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id,
                },
            });
            const targetData = users;
            const isAllDataResult = targetData.length < limit;
            setIsAllData(isAllDataResult);
            const formatedUsers = (0, tranform_target_user_1.transformTargetUser)(targetData, target);
            if (currPage === 0) {
                setListUser(formatedUsers);
            }
            else {
                setListUser((pre) => [...pre, ...formatedUsers]);
            }
        }
        catch (e) {
            console.error(e);
        }
        finally {
            setSearching(false);
        }
    };
    const getDataInitial = async () => {
        try {
            setLoadingInit(true);
            await getUser();
        }
        catch (error) {
            console.error(error);
        }
        finally {
            setLoadingInit(false);
        }
    };
    const handleReset = () => {
        setListUser([]);
        setIsAllData(false);
        setDataSelected([]);
        setCurrPage(0);
        setSearchKeyword('');
    };
    function onHandleHide() {
        onHide();
        handleReset();
    }
    const handleSubmit = () => {
        if (dataSelected.length === 0)
            return;
        const listDelete = defaultSelected.filter((item) => !dataSelected.some((selected) => selected.id === item.id));
        const formattedData = dataSelected.map((item) => ({
            id: item.id,
            code: item.code,
            email: item.email,
            phone: item.phone,
            name: item.full_name,
            full_name: item.full_name,
            parents: item.parents || [],
            educational_level: item.educational_level,
            classroom: item.classroom,
            grade: item.grade,
        }));
        handleAddList(formattedData, listDelete);
        onHide();
    };
    (0, react_1.useEffect)(() => {
        if (show) {
            if (currPage !== 0)
                setCurrPage(0);
            handleReset();
            getDataInitial();
            setDataSelected(defaultSelected || []);
        }
        else {
            handleReset();
        }
    }, [show]);
    (0, react_1.useEffect)(() => {
        getUser();
    }, [currPage, debounceSearchValue]);
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(Modal_1.PHXModal, { closeButton: true, inCard: false, onHide: onHandleHide, onSubmit: handleSubmit, primaryActionText: 'Th\u00EAm m\u1EDBi', show: show, size: 'large', title: `Thêm mới ${(0, get_role_name_by_target_1.getRoleNameByTarget)(target)}` },
            react_1.default.createElement(ResourceList_1.PHXResourceList, { bulkActions: true, bulkActionsContent: 'Ch\u1EC9nh s\u1EEDa', getKeyword: (keyword) => {
                    setSearchKeyword((keyword === null || keyword === void 0 ? void 0 : keyword.trim()) || '');
                    setCurrPage(0);
                    setIsAllData(false);
                }, heightList: 330, hiddenBulkActionMarkup: true, list: listUser, loading: loadingInit, onScrollBottom: () => {
                    if (!searching) {
                        setCurrPage((pre) => pre + 1);
                    }
                }, onSelectedItemsChange: (data) => setDataSelected(data), paging: searching, searchResult: true, selectedItems: dataSelected }))));
}
//# sourceMappingURL=modal-search-user.js.map