"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = TableCustomList;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importStar(require("react"));
const constant_1 = require("../constant");
const get_role_name_by_target_1 = require("../ultis/get-role-name-by-target");
const modal_search_user_1 = tslib_1.__importDefault(require("./modal-search-user/modal-search-user"));
const Dropdown_1 = require("../../Dropdown");
const modal_delete_1 = require("./modal-delete/modal-delete");
const modal_import_user_1 = tslib_1.__importDefault(require("./modal-import/modal-import-user"));
const Card_1 = require("../../Card");
const Notifications_1 = require("../../Notifications");
const use_show_notification_1 = require("../hooks/use-show-notification");
const TableReport_1 = require("../../TableReport");
const render_parent_cell_tooltip_1 = require("../ultis/render-parent-cell-tooltip");
function removeVietnameseTones(str) {
    return str
        .normalize('NFD') // tách dấu ra khỏi ký tự
        .replace(/[\u0300-\u036f]/g, '') // xoá dấu
        .replace(/đ/g, 'd')
        .replace(/Đ/g, 'D');
}
function TableCustomList({ defaultData, handleChange: handleTableCustomList, schoolYearId, target, }) {
    const [listSelected, setListSelected] = (0, react_1.useState)(defaultData || []);
    const [forceClearSelection, setForceClearSelection] = (0, react_1.useState)(Date.now().toString());
    const { notification, onHideNotification, onShowNotification } = (0, use_show_notification_1.useShowNotification)();
    const [showModalSearch, setShowModalSearch] = (0, react_1.useState)(false);
    const [showModalImport, setShowModalImport] = (0, react_1.useState)(false);
    const [rowSelected, setRowSelected] = (0, react_1.useState)([]);
    const [modalDelete, setModalDelete] = (0, react_1.useState)({
        deleteData: {
            ids: [],
            name: '',
        },
        show: false,
    });
    const [filterValues, setFilterValues] = (0, react_1.useState)({
        searchKeyword: '',
    });
    const roleName = (0, get_role_name_by_target_1.getRoleNameByTarget)(target);
    const defaultHeader = ['Số điện thoại', 'Email', 'Thao tác'];
    const headerTable = {
        [constant_1.ERoleCode.TEACHER]: ['Giáo viên', 'Mã giáo viên', ...defaultHeader],
        [constant_1.ERoleCode.STAFF]: ['Nhân viên', 'Mã nhân viên', ...defaultHeader],
        [constant_1.ERoleCode.STUDENT]: ['Học sinh', 'Mã học sinh', 'Cấp học', 'Khối học', 'Lớp học', 'Người thân', 'Thao tác'],
        [constant_1.ERoleCode.DEPARTMENT]: ['Phòng ban', 'Mã phòng ban', 'Thao tác'],
        [constant_1.ERoleCode.PARENT]: [...defaultHeader],
    };
    const defaultBody = ['phone', 'email', 'actions'];
    const bodyTable = {
        [constant_1.ERoleCode.TEACHER]: ['name', 'code', ...defaultBody],
        [constant_1.ERoleCode.STAFF]: ['name', 'code', ...defaultBody],
        [constant_1.ERoleCode.STUDENT]: ['name', 'code', 'educational_level', 'grade', 'classroom', 'parents', 'actions'],
        [constant_1.ERoleCode.DEPARTMENT]: ['Phòng ban', 'Mã phòng ban', ...defaultHeader],
        [constant_1.ERoleCode.PARENT]: [...defaultBody],
    };
    const createHeader = (names) => names.map((name) => ({
        name,
        col: 2,
        row: 1,
    }));
    const openDeleteModal = (ids, name = '') => {
        handleModalDelete({ ids, name });
    };
    const handleModalDelete = (deleteData) => {
        setModalDelete({
            show: true,
            deleteData,
        });
    };
    const [currentPage, setCurrentPage] = (0, react_1.useState)(1);
    const [pageSize, setPageSize] = (0, react_1.useState)(25);
    const start = (currentPage - 1) * pageSize;
    const baseThComponent = {
        actions: (_value, itemBody) => ({
            value: (react_1.default.createElement(Dropdown_1.PHXDropdown, { options: [
                    {
                        // @ts-ignore
                        content: react_1.default.createElement("p", { className: 'text-red-700' },
                            "Xo\u00E1 ",
                            roleName),
                        destructive: true,
                        onClick: () => openDeleteModal([itemBody.id], itemBody.name),
                    },
                ], type: 'ellipsis-icon' })),
            row: 1,
        }),
    };
    const thComponent = {
        ...baseThComponent,
        ...(target === constant_1.ERoleCode.STUDENT && {
            parents: (value) => ({
                value: (0, render_parent_cell_tooltip_1.renderParentCellTooltip)(value),
                row: 1,
            }),
        }),
    };
    const handleAddList = (data, listDelete) => {
        const mergedData = [...data, ...listSelected].filter((item) => !listDelete.some((deleteItem) => deleteItem.id === item.id));
        const unique = Array.from(new Map(mergedData.map((item) => [item.id, item])).values());
        setListSelected(unique);
        setFilterValues({
            searchKeyword: '',
        });
        handleTableCustomList(unique);
    };
    const openModalSearch = () => {
        setListSelected(defaultData || []);
        setShowModalSearch(true);
    };
    const hideModalSearch = () => {
        setShowModalSearch(false);
    };
    const handleDelete = () => {
        if (modalDelete.deleteData.ids.length === 0)
            return;
        const filteredData = listSelected.filter((item) => !modalDelete.deleteData.ids.includes(item.id));
        const remainingSelected = rowSelected.filter((item) => !modalDelete.deleteData.ids.includes(item.id));
        setForceClearSelection(Date.now().toString());
        setListSelected(filteredData);
        setRowSelected(remainingSelected);
        handleTableCustomList(filteredData);
        onHideModalDelete();
    };
    const getFilteredListData = () => {
        var _a, _b;
        const keyword = ((_b = (_a = filterValues.searchKeyword) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.trim()) || '';
        const keywordNoTone = removeVietnameseTones(keyword);
        return listSelected.filter((user) => {
            const code = user.code.toLowerCase();
            const name = user.name.toLowerCase();
            if (code.includes(keyword) || name.includes(keyword))
                return true;
            const codeNoTone = removeVietnameseTones(code);
            const nameNoTone = removeVietnameseTones(name);
            return codeNoTone.includes(keywordNoTone) || nameNoTone.includes(keywordNoTone);
        });
    };
    const filteredListData = getFilteredListData();
    function onHideModalDelete() {
        setModalDelete({
            deleteData: {
                ids: [],
                name: '',
            },
            show: false,
        });
    }
    (0, react_1.useEffect)(() => {
        setCurrentPage(1);
    }, [filterValues.searchKeyword, listSelected.length]);
    (0, react_1.useEffect)(() => {
        setListSelected(defaultData || []);
    }, [JSON.stringify(defaultData)]);
    const hideModalImport = () => {
        setShowModalImport(false);
    };
    const handleShowModalImport = () => {
        setShowModalImport(true);
    };
    const thHeaderReport = createHeader(headerTable[target]);
    return (react_1.default.createElement("div", null,
        react_1.default.createElement(modal_search_user_1.default, { defaultSelected: listSelected, handleAddList: handleAddList, onHide: hideModalSearch, schoolYearId: schoolYearId, show: showModalSearch, target: target }),
        react_1.default.createElement(modal_delete_1.ModalDelete, { deleteData: modalDelete.deleteData, handleDelete: handleDelete, onHide: onHideModalDelete, roleName: roleName, show: modalDelete.show }),
        react_1.default.createElement(modal_import_user_1.default, { onHide: hideModalImport, onSubmit: (data) => {
                handleAddList(data, []);
                onShowNotification({
                    message: 'Tải lên thành công',
                    type: 'custom',
                    show: true,
                });
            }, show: showModalImport, target: target }),
        react_1.default.createElement("div", { className: '-my-4 ml-4' },
            react_1.default.createElement(Card_1.PHXCard, { border: false, dropdown: {
                    data: [
                        {
                            name: `Thêm ${roleName}`,
                            onClick: openModalSearch,
                        },
                        {
                            name: `Tải lên danh sách`,
                            onClick: handleShowModalImport,
                        },
                    ],
                    title: 'Thao tác',
                }, headerAction: {}, primaryHeader: true, title: `Danh sách ${roleName} đã chọn (${defaultData.length})` },
                react_1.default.createElement(TableReport_1.PHXTableReport, { border: false, forceClearSelection: forceClearSelection, onSelectionChange: (data) => {
                        setRowSelected(data);
                    }, pagination: {
                        dataAggregate: filteredListData.length,
                        enable: true,
                        rowNumberInPage: pageSize,
                        onChange: setCurrentPage,
                        setRowNumberInPage: setPageSize,
                    }, readonly: true, search: {
                        enable: true,
                        loading: false,
                        onChange: (keyword) => setFilterValues((pre) => ({ ...pre, searchKeyword: keyword })),
                    }, selectedAllPeople: {
                        enable: true,
                        selectedAction: {
                            actions: [
                                {
                                    content: `Xóa ${roleName}`,
                                    icon: 'close-circle',
                                    onClick: () => openDeleteModal(rowSelected.map((item) => Number(item.id))),
                                },
                            ],
                            label: 'bản ghi',
                        },
                    }, tableData: filteredListData.slice(start, start + pageSize), textCenter: false, thBody: bodyTable[target], thBodyComponent: thComponent, thHeader: thHeaderReport }))),
        react_1.default.createElement(Notifications_1.PHXNotifications, { className: 'z-[9999]', customMessage: notification.message, failure: notification.isFailure, onHide: onHideNotification, show: notification.show, type: notification.type })));
}
//# sourceMappingURL=table-custom-list.js.map