import React, { useEffect, useState } from 'react';
import { toVND } from '../../utils/format-number';
import { PHXSkeleton } from '../Skeleton';
import { PHXEmptyRecord } from '../EmptyRecord';
import { KEY_COEFFICIENT_SEMESTER_I, KEY_COEFFICIENT_SEMESTER_II } from '../../utils/constants';
import { PHXClientQueryV3 } from '../Func/GRPC/PHXGrpcClientV3';
import { getTuitionDebtRecordByUserCodeV3 } from '../../query';
import { LockClosedIcon } from '@heroicons/react/24/outline';
export const PHXFormTuitionV3 = ({ isProcessByMonth = false, school_id, school_year_id, setDiscountPromotionObject, setShowModalPromotionObject, setShowModalService, user_code, }) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
    const [isLoadingTable, setIsLoadingTable] = useState(false);
    const [listDebtRecordByStudent, setListDebtRecordByStudent] = useState();
    const [listDebtRecordByMonth, setListDebtRecordByMonth] = useState([]);
    const generateValueToView = (value) => {
        if (!value)
            return 0;
        return value > 0 ? toVND(value) : `(${toVND(-value)})`;
    };
    const fetchData = async () => {
        setIsLoadingTable(true);
        const res = await PHXClientQueryV3({
            query: getTuitionDebtRecordByUserCodeV3,
            variables: {
                school_id,
                user_code,
                school_year_id,
            },
        });
        if (res) {
            const { data: { tuition_fee_debt_record, tuition_fee_debt_record_by_month }, } = res;
            setListDebtRecordByStudent(tuition_fee_debt_record !== null && tuition_fee_debt_record !== void 0 ? tuition_fee_debt_record : []);
            setListDebtRecordByMonth(tuition_fee_debt_record_by_month !== null && tuition_fee_debt_record_by_month !== void 0 ? tuition_fee_debt_record_by_month : []);
        }
        setIsLoadingTable(false);
    };
    useEffect(() => {
        if (school_year_id) {
            fetchData();
        }
    }, [school_year_id, isProcessByMonth]);
    const checkIsHasPromoPolicy = (listFee) => listFee === null || listFee === void 0 ? void 0 : listFee.some((item) => item.total_promotion_tuition_policy);
    const totalFeeByCode = (listData, code) => {
        const total = listData === null || listData === void 0 ? void 0 : listData.reduce(
        // eslint-disable-next-line @typescript-eslint/no-shadow
        (total, item) => total + Number(item[code]), 0);
        return total;
    };
    const getDebtAndCreditLastYear = (listDebtRecord) => {
        // Tìm ra dư có và dư có và dư nợ của năm ngoái (chính là bản ghi học kỳ 1)
        const dataLastYear = listDebtRecord === null || listDebtRecord === void 0 ? void 0 : listDebtRecord.filter((item) => { var _a; return ((_a = item.school_term) === null || _a === void 0 ? void 0 : _a.coefficient) === KEY_COEFFICIENT_SEMESTER_I; });
        return dataLastYear || [];
    };
    const getDebtAndCreditCurrentYear = (listDebtRecord) => {
        // Tìm ra dư có và dư có và dư nợ của năm ngoái (chính là bản ghi học kỳ 1)
        const dataLastYear = listDebtRecord === null || listDebtRecord === void 0 ? void 0 : listDebtRecord.filter((item) => { var _a; return ((_a = item.school_term) === null || _a === void 0 ? void 0 : _a.coefficient) === KEY_COEFFICIENT_SEMESTER_II; });
        return dataLastYear || [];
    };
    // Tạo ra những row detail của các đầu mục lớn vd (1., 2. ...)
    const createRowDetail = (title, key) => {
        const listDebtRecord = isProcessByMonth ? listDebtRecordByMonth : listDebtRecordByStudent;
        const isHasData = listDebtRecord.some((item) => item[key]);
        if (isHasData) {
            return (React.createElement("tr", null,
                React.createElement("td", { className: 'sticky left-0 whitespace-nowrap border-r border-t bg-white pl-6 text-xs text-gray-900 drop-shadow-md' }, title), listDebtRecord === null || listDebtRecord === void 0 ? void 0 :
                listDebtRecord.map((item, index) => (React.createElement("td", { key: index, className: 'whitespace-nowrap border-r border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(item[key])))),
                React.createElement("td", { className: 'whitespace-nowrap border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(totalFeeByCode(listDebtRecordByStudent, key)))));
        }
        else {
            return React.createElement(React.Fragment, null);
        }
    };
    const generateIconLock = (isLocked) => isLocked ? React.createElement(LockClosedIcon, { "aria-hidden": 'true', className: 'ml-1 h-4 w-4' }) : React.createElement(React.Fragment, null);
    const getIsLockedYear = (listDebtRecord) => listDebtRecord.every(({ is_locked }) => is_locked === true);
    const isHasDataRecord = listDebtRecordByStudent && listDebtRecordByStudent.length > 0;
    const isLoading = Boolean(isLoadingTable || !listDebtRecordByStudent);
    return (React.createElement(React.Fragment, null, isLoading ? (React.createElement(PHXSkeleton, { type: 'table' })) : isHasDataRecord ? (React.createElement("div", { className: 'rounded-lg bg-white  shadow ring-1 ring-black ring-opacity-5' },
        React.createElement("div", { className: 'overflow-x-auto rounded-lg' },
            React.createElement("div", { className: 'min-w-full align-middle shadow  ring-black ring-opacity-5' },
                React.createElement("div", { className: 'relative overflow-auto' },
                    React.createElement("table", { className: 'w-full table-fixed border-separate border-spacing-0\t divide-y divide-gray-300' },
                        React.createElement("thead", null,
                            React.createElement("tr", null,
                                React.createElement("th", { className: 'sticky left-0 w-[210px] border-r bg-white px-3 py-2 pl-8 text-left align-top text-xs font-semibold text-gray-600 drop-shadow-md xl:drop-shadow-none', scope: 'col' }, "Chi ti\u1EBFt kho\u1EA3n ph\u00ED"), (_a = (isProcessByMonth ? listDebtRecordByMonth : listDebtRecordByStudent)) === null || _a === void 0 ? void 0 :
                                _a.map((item, index) => {
                                    var _a, _b;
                                    return (React.createElement("th", { key: index, className: 'w-[210px] border-r bg-white px-3 py-2 pl-2 text-left align-top text-xs font-semibold text-gray-600', scope: 'col' },
                                        React.createElement("p", { className: 'flex text-center' },
                                            isProcessByMonth ? (_a = item.school_month) === null || _a === void 0 ? void 0 : _a.name : (_b = item.school_term) === null || _b === void 0 ? void 0 : _b.name,
                                            generateIconLock(item.is_locked))));
                                }),
                                React.createElement("th", { className: 'w-[210px] bg-white px-3 py-2 pl-2 text-left align-top text-xs font-semibold text-gray-600', scope: 'col' },
                                    React.createElement("p", { className: 'flex text-center' },
                                        "C\u1EA3 n\u0103m",
                                        generateIconLock(getIsLockedYear(isProcessByMonth ? listDebtRecordByMonth : listDebtRecordByStudent)))))),
                        React.createElement("tbody", { className: 'divide-y divide-gray-200 bg-white' },
                            React.createElement("tr", { className: 'bg-gray-100' },
                                React.createElement("td", { className: 'sticky left-0 whitespace-nowrap border-r border-t bg-gray-100 pl-2 text-xs text-gray-900 drop-shadow-md' }, `1. Dư nợ đầu kỳ`), (_b = (isProcessByMonth ? listDebtRecordByMonth : listDebtRecordByStudent)) === null || _b === void 0 ? void 0 :
                                _b.map((item, index) => (React.createElement("td", { key: index, className: 'whitespace-nowrap border-r border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(item.last_period_debt_balance - item.last_period_credit_balance)))),
                                React.createElement("td", { className: 'whitespace-nowrap border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(totalFeeByCode(getDebtAndCreditLastYear(listDebtRecordByStudent), 'last_period_debt_balance') -
                                    totalFeeByCode(getDebtAndCreditLastYear(listDebtRecordByStudent), 'last_period_credit_balance')))),
                            React.createElement("tr", { className: 'bg-gray-100' },
                                React.createElement("td", { className: 'sticky left-0 whitespace-nowrap border-r border-t bg-gray-100 pl-2 text-xs text-gray-900 drop-shadow-md' }, "2. Kho\u1EA3n thu"), (_c = (isProcessByMonth ? listDebtRecordByMonth : listDebtRecordByStudent)) === null || _c === void 0 ? void 0 :
                                _c.map((item, index) => (React.createElement("td", { key: index, className: 'whitespace-nowrap border-r border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(item.total_tuition +
                                    item.total_required_service +
                                    item.total_not_required_service +
                                    item.total_adjustment_additional)))),
                                React.createElement("td", { className: 'whitespace-nowrap border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(totalFeeByCode(listDebtRecordByStudent, 'total_tuition') +
                                    totalFeeByCode(listDebtRecordByStudent, 'total_required_service') +
                                    totalFeeByCode(listDebtRecordByStudent, 'total_not_required_service') +
                                    totalFeeByCode(listDebtRecordByStudent, 'total_adjustment_additional')))),
                            React.createElement("tr", null,
                                React.createElement("td", { className: 'sticky left-0 whitespace-nowrap border-r border-t bg-white pl-6 text-xs text-gray-900 drop-shadow-md' }, "H\u1ECDc ph\u00ED ni\u00EAm y\u1EBFt"), (_d = (isProcessByMonth ? listDebtRecordByMonth : listDebtRecordByStudent)) === null || _d === void 0 ? void 0 :
                                _d.map((item, index) => (React.createElement("td", { key: index, className: 'whitespace-nowrap border-r border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(item.total_tuition)))),
                                React.createElement("td", { className: 'whitespace-nowrap border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(totalFeeByCode(listDebtRecordByStudent, 'total_tuition')))),
                            React.createElement("tr", { className: `${setShowModalService ? 'hover:cursor-pointer hover:bg-gray-50' : ''}`, onClick: () => {
                                    if (!setShowModalService) {
                                        return;
                                    }
                                    setShowModalService(true);
                                } },
                                React.createElement("td", { className: 'sticky left-0 whitespace-nowrap border-r border-t bg-white pl-6 text-xs text-gray-900 drop-shadow-md' }, "D\u1ECBch v\u1EE5 b\u1EAFt bu\u1ED9c"), (_e = (isProcessByMonth ? listDebtRecordByMonth : listDebtRecordByStudent)) === null || _e === void 0 ? void 0 :
                                _e.map((item, index) => (React.createElement("td", { key: index, className: 'whitespace-nowrap border-r border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(item.total_required_service)))),
                                React.createElement("td", { className: 'whitespace-nowrap border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(totalFeeByCode(listDebtRecordByStudent, 'total_required_service')))),
                            createRowDetail('Dịch vụ tuỳ chọn', 'total_not_required_service'),
                            createRowDetail('Phí phụ thu', 'total_adjustment_additional'),
                            React.createElement("tr", { className: 'bg-gray-100' },
                                React.createElement("td", { className: 'sticky left-0 whitespace-nowrap border-r border-t bg-gray-100 pl-2 text-xs text-gray-900 drop-shadow-md' }, "3. Kho\u1EA3n gi\u1EA3m tr\u1EEB"), (_f = (isProcessByMonth ? listDebtRecordByMonth : listDebtRecordByStudent)) === null || _f === void 0 ? void 0 :
                                _f.map((item, index) => (React.createElement("td", { key: index, className: 'whitespace-nowrap border-r border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(item.total_promotion_early +
                                    item.total_promotion_tuition_scholar_ship +
                                    item.total_promotion_tuition_policy +
                                    item.total_promotion_tuition_seniority +
                                    item.total_promotion_admission +
                                    item.total_promotion_service +
                                    item.total_adjustment_refund +
                                    item.total_refund)))),
                                React.createElement("td", { className: 'whitespace-nowrap border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(totalFeeByCode(listDebtRecordByStudent, 'total_promotion_early') +
                                    totalFeeByCode(listDebtRecordByStudent, 'total_promotion_tuition_scholar_ship') +
                                    totalFeeByCode(listDebtRecordByStudent, 'total_promotion_tuition_policy') +
                                    totalFeeByCode(listDebtRecordByStudent, 'total_promotion_tuition_seniority') +
                                    totalFeeByCode(listDebtRecordByStudent, 'total_promotion_admission') +
                                    totalFeeByCode(listDebtRecordByStudent, 'total_promotion_service') +
                                    totalFeeByCode(listDebtRecordByStudent, 'total_adjustment_refund') +
                                    totalFeeByCode(listDebtRecordByStudent, 'total_refund')))),
                            createRowDetail('Ưu đãi đóng sớm', 'total_promotion_early'),
                            createRowDetail('Ưu đãi học bổng', 'total_promotion_tuition_scholar_ship'),
                            checkIsHasPromoPolicy(listDebtRecordByStudent) && (React.createElement("tr", { className: `${setShowModalPromotionObject ? 'hover:cursor-pointer hover:bg-gray-50' : ''}`, onClick: () => {
                                    if (!setShowModalPromotionObject) {
                                        return;
                                    }
                                    setShowModalPromotionObject(true);
                                    setDiscountPromotionObject(Number((totalFeeByCode(listDebtRecordByStudent, 'total_promotion_tuition_policy') /
                                        totalFeeByCode(listDebtRecordByStudent, 'total_tuition')) *
                                        100).toFixed(1));
                                } },
                                React.createElement("td", { className: 'sticky left-0 whitespace-nowrap border-r border-t bg-white pl-6 text-xs text-gray-900 drop-shadow-md' }, "\u01AFu \u0111\u00E3i \u0111\u1ED1i t\u01B0\u1EE3ng"), (_g = (isProcessByMonth ? listDebtRecordByMonth : listDebtRecordByStudent)) === null || _g === void 0 ? void 0 :
                                _g.map((item, index) => (React.createElement("td", { key: index, className: 'whitespace-nowrap border-r border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(item.total_promotion_tuition_policy)))),
                                React.createElement("td", { className: 'whitespace-nowrap border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(totalFeeByCode(listDebtRecordByStudent, 'total_promotion_tuition_policy'))))),
                            createRowDetail('Ưu đãi thâm niên', 'total_promotion_tuition_seniority'),
                            createRowDetail('Ưu đãi tuyển sinh', 'total_promotion_admission'),
                            createRowDetail('Ưu đãi phí dịch vụ', 'total_promotion_service'),
                            createRowDetail('Giảm trừ bổ sung', 'total_adjustment_refund'),
                            createRowDetail('Hoàn tiền dịch vụ', 'total_refund'),
                            React.createElement("tr", { className: 'bg-gray-100' },
                                React.createElement("td", { className: 'sticky left-0 whitespace-nowrap border-r border-t bg-gray-100 pl-2 text-xs text-gray-900 drop-shadow-md' }, "4. Ph\u1EA3i thu (4=1+2-3)"), (_h = (isProcessByMonth ? listDebtRecordByMonth : listDebtRecordByStudent)) === null || _h === void 0 ? void 0 :
                                _h.map((item, index) => (React.createElement("td", { key: index, className: 'whitespace-nowrap border-r border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(item.last_period_debt_balance +
                                    item.total_tuition +
                                    item.total_required_service +
                                    item.total_not_required_service +
                                    item.total_adjustment_additional -
                                    item.total_promotion_early -
                                    item.total_promotion_tuition_scholar_ship -
                                    item.total_promotion_tuition_policy -
                                    item.total_promotion_tuition_seniority -
                                    item.total_promotion_admission -
                                    item.total_promotion_service -
                                    item.total_adjustment_refund -
                                    item.total_refund -
                                    item.last_period_credit_balance)))),
                                React.createElement("td", { className: 'whitespace-nowrap border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(totalFeeByCode(getDebtAndCreditLastYear(listDebtRecordByStudent), 'last_period_debt_balance') +
                                    totalFeeByCode(listDebtRecordByStudent, 'total_tuition') +
                                    totalFeeByCode(listDebtRecordByStudent, 'total_required_service') +
                                    totalFeeByCode(listDebtRecordByStudent, 'total_not_required_service') +
                                    totalFeeByCode(listDebtRecordByStudent, 'total_adjustment_additional') -
                                    totalFeeByCode(listDebtRecordByStudent, 'total_promotion_early') -
                                    totalFeeByCode(listDebtRecordByStudent, 'total_promotion_tuition_scholar_ship') -
                                    totalFeeByCode(listDebtRecordByStudent, 'total_promotion_tuition_policy') -
                                    totalFeeByCode(listDebtRecordByStudent, 'total_promotion_tuition_seniority') -
                                    totalFeeByCode(listDebtRecordByStudent, 'total_promotion_admission') -
                                    totalFeeByCode(listDebtRecordByStudent, 'total_promotion_service') -
                                    totalFeeByCode(listDebtRecordByStudent, 'total_adjustment_refund') -
                                    totalFeeByCode(listDebtRecordByStudent, 'total_refund') -
                                    totalFeeByCode(getDebtAndCreditLastYear(listDebtRecordByStudent), 'last_period_credit_balance')))),
                            React.createElement("tr", { className: 'border-t  bg-gray-100' },
                                React.createElement("td", { className: 'sticky left-0 whitespace-nowrap border-r border-t bg-gray-100 pl-2 text-xs text-gray-900 drop-shadow-md' }, "5. \u0110\u00E3 \u0111\u00F3ng"), (_j = (isProcessByMonth ? listDebtRecordByMonth : listDebtRecordByStudent)) === null || _j === void 0 ? void 0 :
                                _j.map((item, index) => (React.createElement("td", { key: index, className: 'whitespace-nowrap border-r border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(item.total_payment)))),
                                React.createElement("td", { className: 'whitespace-nowrap border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(totalFeeByCode(listDebtRecordByStudent, 'total_payment')))),
                            React.createElement("tr", { className: 'border-t  bg-gray-100' },
                                React.createElement("td", { className: 'sticky left-0 whitespace-nowrap border-r border-t bg-gray-100 pl-2 text-xs text-gray-900 drop-shadow-md' }, "6. Ti\u1EC1n thi\u1EBFu/(th\u1EEBa)"), (_k = (isProcessByMonth ? listDebtRecordByMonth : listDebtRecordByStudent)) === null || _k === void 0 ? void 0 :
                                _k.map((item, index) => (React.createElement("td", { key: index, className: 'whitespace-nowrap border-r border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(item.last_debt_balance - item.last_credit_balance)))),
                                React.createElement("td", { className: 'whitespace-nowrap border-t px-2 py-2 text-xs text-gray-900' }, generateValueToView(totalFeeByCode(getDebtAndCreditCurrentYear(listDebtRecordByStudent), 'last_debt_balance') -
                                    totalFeeByCode(getDebtAndCreditCurrentYear(listDebtRecordByStudent), 'last_credit_balance')))),
                            !isProcessByMonth && (React.createElement("tr", null,
                                React.createElement("td", { className: 'sticky left-0 whitespace-nowrap border-r border-t bg-white pl-2 text-xs text-gray-900 drop-shadow-md' }, "7. File PDF thu ph\u00ED"), listDebtRecordByStudent === null || listDebtRecordByStudent === void 0 ? void 0 :
                                listDebtRecordByStudent.map((itemDebt, index) => {
                                    var _a, _b;
                                    const linkDeliveredEmail = ((_a = itemDebt.profile_student) === null || _a === void 0 ? void 0 : _a.tuition_notice_delivered_emails) || [];
                                    const listEmailFilterWithSchoolTermId = (linkDeliveredEmail === null || linkDeliveredEmail === void 0 ? void 0 : linkDeliveredEmail.filter((item) => { var _a, _b; return ((_a = itemDebt.school_term) === null || _a === void 0 ? void 0 : _a.id) === ((_b = item.tuition_notice_campaign) === null || _b === void 0 ? void 0 : _b.school_term_id); })) || [];
                                    let linkPdfNewest = '';
                                    if (listEmailFilterWithSchoolTermId.length > 0) {
                                        linkPdfNewest = (_b = listEmailFilterWithSchoolTermId[0]) === null || _b === void 0 ? void 0 : _b.link_pdf_cdn;
                                    }
                                    return linkPdfNewest ? (React.createElement("td", { key: index, className: 'whitespace-nowrap border-r border-t px-2 py-2 text-xs text-gray-900' },
                                        React.createElement("a", { 
                                            // ref={linkRef}
                                            className: 'pt-3 text-xs text-blue-600 hover:cursor-pointer hover:text-blue-800 hover:underline', href: linkPdfNewest, rel: 'noreferrer', target: '_blank' }, "pdf file"))) : (React.createElement("td", { key: index, className: 'whitespace-nowrap border-r border-t px-2 py-2 text-xs text-gray-900' }, "---"));
                                }),
                                React.createElement("td", { className: 'whitespace-nowrap border-t px-2 py-2 text-xs text-gray-900' })))))))))) : (React.createElement(PHXEmptyRecord, null))));
};
//# sourceMappingURL=FormTuitionV3.js.map