"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = ModalImportUser;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importStar(require("react"));
const XLSX = tslib_1.__importStar(require("xlsx"));
const get_role_name_by_target_1 = require("../../ultis/get-role-name-by-target");
const confirm_upload_1 = require("./confirm-upload");
const preview_user_1 = require("./preview-user");
const constant_1 = require("../../constant");
const Modal_1 = require("../../../Modal");
const use_import_user_1 = require("../../hooks/use-import-user");
const BannerWithCard_1 = require("../../../BannerWithCard/BannerWithCard");
const PHXUploadFile_1 = require("../../../UploadFile/PHXUploadFile");
function ModalImportUser({ onHide, onSubmit, show, target }) {
    const [fileName, setFileName] = (0, react_1.useState)('');
    const [error, setError] = (0, react_1.useState)('');
    const [userCodes, setUserCodes] = (0, react_1.useState)([]);
    const { findUserByUserCodes } = (0, use_import_user_1.useImportUser)();
    const [step, setStep] = (0, react_1.useState)(1);
    const [loading, setLoading] = (0, react_1.useState)(false);
    const [validList, setValidList] = (0, react_1.useState)([]);
    const [invalidList, setInvalidList] = (0, react_1.useState)([]);
    const downloadLinkRef = (0, react_1.useRef)(null);
    const roleName = (0, get_role_name_by_target_1.getRoleNameByTarget)(target);
    const onHandleHide = () => {
        onHide();
    };
    const step1HandleFindUser = async (codes) => {
        if (codes.length === 0) {
            setError('user_code không được để trống');
            return;
        }
        setLoading(true);
        try {
            const response = await findUserByUserCodes(target, codes);
            const nodeMap = new Map();
            response.forEach((n) => nodeMap.set(n.code, n));
            const codeCounts = new Map();
            codes.forEach((code) => {
                codeCounts.set(code, (codeCounts.get(code) || 0) + 1);
            });
            const invalids = [];
            const valids = [];
            const seenValid = new Set();
            codes.forEach((code) => {
                if (codeCounts.get(code) > 1) {
                    invalids.push({
                        code,
                        reason: 'Trùng mã',
                        reasonDetail: `Mã ${(0, get_role_name_by_target_1.getRoleNameByTarget)(target, false)} đang bị trùng`,
                    });
                }
                else if (!nodeMap.has(code)) {
                    invalids.push({
                        code,
                        reason: 'Sai mã',
                        reasonDetail: `Mã ${(0, get_role_name_by_target_1.getRoleNameByTarget)(target, false)} không tồn tại`,
                    });
                }
                else {
                    if (!seenValid.has(code)) {
                        valids.push(nodeMap.get(code));
                        seenValid.add(code);
                    }
                }
            });
            setInvalidList(invalids);
            setValidList(valids);
            setStep(2);
        }
        catch (err) {
            console.error(err);
        }
        finally {
            setLoading(false);
        }
    };
    const step3HandleSubmit = () => {
        onSubmit(validList);
        onHide();
    };
    const handleFileChange = (e) => {
        var _a;
        const file = (_a = e.target.files) === null || _a === void 0 ? void 0 : _a[0];
        if (file) {
            setError('');
            const reader = new FileReader();
            reader.onload = (evt) => {
                var _a;
                const arrayBuffer = (_a = evt.target) === null || _a === void 0 ? void 0 : _a.result;
                if (arrayBuffer) {
                    try {
                        const workbook = XLSX.read(arrayBuffer, { type: 'array' });
                        const sheetName = workbook.SheetNames[0];
                        const worksheet = workbook.Sheets[sheetName];
                        const data = XLSX.utils.sheet_to_json(worksheet, { defval: '' });
                        if (data.length === 0) {
                            setError(constant_1.ERROR_MESSAGE_UPLOAD_FILE);
                            setFileName('');
                            return;
                        }
                        const firstRow = data[0];
                        const hasUserCode = Object.keys(firstRow).some((key) => key.trim().toLowerCase() === 'user_code');
                        if (!hasUserCode) {
                            setError(constant_1.ERROR_MESSAGE_UPLOAD_FILE);
                            setFileName('');
                            return;
                        }
                        const userCodesExcel = data.map((item) => String(item.user_code));
                        setUserCodes(userCodesExcel);
                        setFileName(file.name);
                    }
                    catch (err) {
                        setError(constant_1.ERROR_MESSAGE_UPLOAD_FILE);
                        setFileName('');
                    }
                }
            };
            reader.readAsArrayBuffer(file);
        }
        e.target.value = '';
    };
    (0, react_1.useEffect)(() => {
        if (show) {
            setStep(1);
            setFileName('');
            setError('');
            setUserCodes([]);
            setValidList([]);
            setInvalidList([]);
        }
    }, [show]);
    const STEP_CONFIG = {
        1: {
            primaryText: 'Tiếp tục',
            title: `Tải lên danh sách ${roleName}`,
            sizeModal: 'large',
            handleSubmit: () => step1HandleFindUser(userCodes),
        },
        2: {
            leftActionText: '← Quay lại',
            leftActionHandle: () => setStep(1),
            primaryText: 'Tải lên',
            title: `Xem trước danh sách ${roleName}`,
            sizeModal: 'extra-large',
            handleSubmit: () => setStep(3),
        },
        3: {
            leftActionHandle: () => setStep(2),
            handleSubmit: () => step3HandleSubmit(),
            primaryText: 'Xác nhận',
            title: 'Xác nhận tải lên',
            sizeModal: 'medium',
        },
    };
    const currentStep = STEP_CONFIG[step];
    return (react_1.default.createElement(Modal_1.PHXModal, { closeButton: true, disableSubmit: step === 1 ? !fileName || loading : false, dowloadIcon: step === 1, downloadLinkRef: step === 1 ? downloadLinkRef : undefined, downloadText: step === 1 ? 'Tải xuống file mẫu' : undefined, hrefLink: step === 1 ? constant_1.SAMPLE_FILE_URL.url : undefined, inCard: false, leftActionText: currentStep.leftActionText, onCancel: onHandleHide, onHide: onHandleHide, onLeftActionText: currentStep.leftActionHandle, onSubmit: currentStep.handleSubmit, primaryActionText: currentStep.primaryText, primaryLoading: loading, secondaryActionText: '\u0110\u00F3ng', show: show, size: currentStep.sizeModal || 'large', title: currentStep.title },
        react_1.default.createElement("div", { className: 'py-2' },
            step === 1 && (react_1.default.createElement(react_1.default.Fragment, null,
                error && react_1.default.createElement(BannerWithCard_1.PHXBannerWithCard, { className: 'mb-4', description: error, hideCloseButton: true, show: true, type: 'danger' }),
                react_1.default.createElement(PHXUploadFile_1.PHXUploadFile, { fileName: fileName, fileType: 'excel', handleFileChange: handleFileChange, type: PHXUploadFile_1.EUploadType.TO_CLIENT }))),
            step === 2 && react_1.default.createElement(preview_user_1.PreviewUser, { invalidList: invalidList, target: target, validList: validList }),
            step === 3 && react_1.default.createElement(confirm_upload_1.ConfirmUpload, { totalInvalidList: invalidList.length, totalValidList: validList.length }))));
}
//# sourceMappingURL=modal-import-user.js.map