"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PHXFormTarget = void 0;
const tslib_1 = require("tslib");
const react_1 = require("react");
const react_hook_form_1 = require("react-hook-form");
const divider_1 = require("../Divider/divider");
const radio_group_select_1 = require("./components/radio-group-select");
const config_1 = require("./config");
const constant_1 = require("./constant");
const query_1 = require("./graphql/query");
const tranform_target_user_1 = require("./ultis/tranform-target-user");
const getSchoolYearV3_1 = tslib_1.__importDefault(require("../Func/SchoolYearV3/getSchoolYearV3"));
const getLoginInfo_1 = tslib_1.__importDefault(require("../Func/getLoginInfo"));
const PHXGrpcClientV3_1 = require("../Func/GRPC/PHXGrpcClientV3");
const react_2 = tslib_1.__importDefault(require("react"));
const BannerWithCard_1 = require("../BannerWithCard/BannerWithCard");
const Skeleton_1 = require("../Skeleton");
const Checkbox_1 = require("../Checkbox");
const Text_1 = require("../Text/Text");
const Toggle_1 = tslib_1.__importDefault(require("../PHXToggle/Toggle"));
const hooks_1 = require("./hooks");
const Box_1 = require("../Box");
const PHXFormTarget = ({ targetId, onLoading, onChange }) => {
    var _a, _b, _c;
    const { clearErrors, control, formState: { errors }, register, setValue, watch, } = (0, react_hook_form_1.useFormContext)();
    const [getDefaultLoading, setGetDefaultLoading] = (0, react_1.useState)(false);
    const schoolYear = (0, getSchoolYearV3_1.default)();
    const schoolYearId = (_b = (_a = schoolYear === null || schoolYear === void 0 ? void 0 : schoolYear.current_school_year) === null || _a === void 0 ? void 0 : _a.schoolYear) === null || _b === void 0 ? void 0 : _b.id;
    const userInfo = (0, getLoginInfo_1.default)();
    const { loading: getSelectLoading, selectOptions } = (0, hooks_1.useGetDataSelectTarget)({
        schoolYearId,
    });
    const { isSubmitted } = (0, react_hook_form_1.useFormState)({ control });
    const listTargetSelected = watch('target');
    const handleSetTarget = (newTargets) => {
        setValue('target', newTargets, {
            shouldValidate: false,
            shouldDirty: true,
        });
        onChange === null || onChange === void 0 ? void 0 : onChange(newTargets);
    };
    (0, react_1.useEffect)(() => {
        register('target', {
            validate: (value) => (value === null || value === void 0 ? void 0 : value.length) > 0 || 'Vui lòng chọn loại đối tượng',
        });
    }, []);
    const handleChangeTarget = (target) => {
        const exists = listTargetSelected.some((item) => item.target === target);
        const nextValues = exists
            ? listTargetSelected.filter((item) => item.target !== target)
            : [
                ...listTargetSelected,
                {
                    target,
                    filter: [],
                    notifyWith: constant_1.DEFAULT_NOTIFY_WITH_BY_TARGET[target],
                },
            ];
        handleSetTarget(nextValues);
    };
    const handleChangeNotifyWith = (target, notifyWith) => {
        const itemIndex = listTargetSelected.findIndex((item) => item.target === target && item.notifyWith === notifyWith);
        let nextValues = [...listTargetSelected];
        if (itemIndex !== -1) {
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            const { notifyWith: _, ...rest } = nextValues[itemIndex];
            nextValues[itemIndex] = rest;
        }
        else {
            nextValues = listTargetSelected.map((item) => (item.target === target ? { ...item, notifyWith } : item));
        }
        handleSetTarget(nextValues);
    };
    const handleChangeFilter = (target, checked, filterItem) => {
        clearErrors('target');
        // lất vị trí item hiện tại trong danh sách
        const selectedIndex = listTargetSelected.findIndex((i) => i.target === target);
        if (selectedIndex === -1)
            return;
        // lấy ra item hiện tại
        const item = listTargetSelected[selectedIndex];
        // kiểm tra xem filter đã tồn tại chưa
        const exists = item.filter.some((f) => f.filterBy === filterItem.filterBy);
        const isCheckAll = filterItem.filterBy === constant_1.FILTER_BY.ALL;
        let nextFilter;
        // xử lý logic thay đổi filter
        if (!checked) {
            nextFilter = item.filter.filter((f) => f.filterBy !== filterItem.filterBy);
        }
        else if (exists) {
            nextFilter = item.filter.map((f) => (f.filterBy === filterItem.filterBy ? filterItem : f));
        }
        else {
            if (isCheckAll) {
                // nếu chọn "Tất cả", thì bỏ tất cả các filter khác
                nextFilter = [filterItem];
            }
            else {
                nextFilter = [...item.filter, filterItem];
            }
        }
        const nextValues = [...listTargetSelected];
        nextValues[selectedIndex] = {
            ...item,
            filter: nextFilter,
        };
        handleSetTarget(nextValues);
    };
    const getDefaultData = async () => {
        if (!targetId)
            return;
        onLoading === null || onLoading === void 0 ? void 0 : onLoading(true);
        setGetDefaultLoading(true);
        try {
            const { data: { user_segment_target_by_pk: { school_year_id, target_by_roles }, }, } = await (0, PHXGrpcClientV3_1.PHXClientQueryV3)({
                query: query_1.GET_TARGET_BY_ROLE_QUERY,
                variables: {
                    id: targetId,
                },
            });
            const userIds = target_by_roles.flatMap((r) => r.target_users).map((u) => u.user.id);
            const { data } = await (0, PHXGrpcClientV3_1.PHXClientQueryV3)({
                query: query_1.GET_CLASSROOM_BY_USER_IDS,
                variables: {
                    schoolYearId: school_year_id || schoolYearId,
                    userIds,
                },
            });
            const classroomMap = data.classroom_student.reduce((acc, item) => {
                var _a;
                acc[_a = item.user.id] || (acc[_a] = []);
                acc[item.user.id].push(item.classroom);
                return acc;
            }, {});
            const result = target_by_roles.map((item) => {
                var _a, _b;
                return ({
                    ...item,
                    role: {
                        ...item.role,
                        role_code: ((_a = item.role) === null || _a === void 0 ? void 0 : _a.role_code) === constant_1.ERoleCode.PARENT ? constant_1.ERoleCode.STUDENT : (_b = item.role) === null || _b === void 0 ? void 0 : _b.role_code,
                    },
                    target_users: item.target_users.map((tu) => ({
                        ...tu,
                        user: {
                            ...tu.user,
                            classroom_students: (classroomMap[tu.user.id] || []).map((classroom) => ({ classroom })),
                        },
                    })),
                });
            });
            const formatted = result
                .map((item) => {
                var _a, _b, _c, _d, _e, _f, _g;
                const filters = [];
                if (item.is_all) {
                    filters.push({ filterBy: constant_1.FILTER_BY.ALL, filterValues: [] });
                }
                if ((_a = item.target_educational_levels) === null || _a === void 0 ? void 0 : _a.length) {
                    filters.push({
                        filterBy: constant_1.FILTER_BY.EDUCATIONAL_LEVEL,
                        filterValues: item.target_educational_levels.map((x) => x.educational_level),
                    });
                }
                if ((_b = item.target_grades) === null || _b === void 0 ? void 0 : _b.length) {
                    filters.push({
                        filterBy: constant_1.FILTER_BY.GRADE,
                        filterValues: item.target_grades.map((x) => x.grade),
                    });
                }
                if ((_c = item.target_classrooms) === null || _c === void 0 ? void 0 : _c.length) {
                    filters.push({
                        filterBy: constant_1.FILTER_BY.CLASSROOM,
                        filterValues: item.target_classrooms.map((x) => x.classroom),
                    });
                }
                if ((_d = item.target_departments) === null || _d === void 0 ? void 0 : _d.length) {
                    filters.push({
                        filterBy: constant_1.FILTER_BY.DEPARTMENT,
                        filterValues: item.target_departments.map((x) => x.department),
                    });
                }
                if ((_e = item.target_users) === null || _e === void 0 ? void 0 : _e.length) {
                    filters.push({
                        filterBy: constant_1.FILTER_BY.CUSTOM_LIST,
                        filterValues: item.target_users.map((u) => {
                            var _a, _b, _c;
                            const formatUser = (0, tranform_target_user_1.transformTargetUser)([
                                {
                                    ...u.user,
                                    full_name: u.user.name,
                                    phone_number: (_a = u.user) === null || _a === void 0 ? void 0 : _a.phone,
                                },
                            ], (_c = (_b = item.role) === null || _b === void 0 ? void 0 : _b.role_code) !== null && _c !== void 0 ? _c : constant_1.ERoleCode.DEPARTMENT);
                            return formatUser[0];
                        }),
                    });
                }
                if (filters.length === 0)
                    return null;
                return {
                    target: (_g = (_f = item.role) === null || _f === void 0 ? void 0 : _f.role_code) !== null && _g !== void 0 ? _g : constant_1.ERoleCode.DEPARTMENT,
                    filter: filters,
                    notifyWith: item.notify_with,
                };
            })
                .filter((item) => item !== null);
            handleSetTarget(formatted);
        }
        catch (e) {
            console.error(e);
        }
        finally {
            setGetDefaultLoading(false);
            onLoading === null || onLoading === void 0 ? void 0 : onLoading(false);
        }
    };
    (0, react_1.useEffect)(() => {
        if (targetId && schoolYearId && (userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id)) {
            getDefaultData();
        }
    }, [targetId, schoolYearId, userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id]);
    return (react_2.default.createElement(react_2.default.Fragment, null, (getSelectLoading || getDefaultLoading) && targetId ? (react_2.default.createElement(Skeleton_1.PHXSkeleton, { type: 'table' })) : (react_2.default.createElement("div", null,
        ((_c = errors.target) === null || _c === void 0 ? void 0 : _c.message) && (react_2.default.createElement(BannerWithCard_1.PHXBannerWithCard, { className: 'mb-3', description: errors.target.message, hideCloseButton: true, show: true, type: 'danger' })),
        react_2.default.createElement("div", { className: 'space-y-2' }, config_1.TARGET_CONFIGS.map((config, targetIndex) => {
            var _a, _b, _c, _d, _e;
            const { listRadio, notifyWith, title, value: targetConfig } = config;
            const isChecked = listTargetSelected.some((i) => i.target === targetConfig);
            const item = listTargetSelected.find((i) => i.target === targetConfig);
            const notifyActive = (item === null || item === void 0 ? void 0 : item.notifyWith) === (notifyWith === null || notifyWith === void 0 ? void 0 : notifyWith.value);
            const targetError = (_c = (_b = (_a = errors === null || errors === void 0 ? void 0 : errors.target) === null || _a === void 0 ? void 0 : _a[targetIndex]) === null || _b === void 0 ? void 0 : _b.filter) === null || _c === void 0 ? void 0 : _c.message;
            return (react_2.default.createElement("div", { key: targetConfig, className: 'space-y-2' },
                react_2.default.createElement("div", null,
                    react_2.default.createElement(Checkbox_1.PHXCheckbox, { checked: isChecked, error: !!targetError && isSubmitted, errorType: 'required-field', id: targetConfig, onChange: () => handleChangeTarget(targetConfig), title: title }),
                    react_2.default.createElement("div", { className: 'ml-7' },
                        react_2.default.createElement(Text_1.PHXText, { tone: 'subdued' }, config.description))),
                notifyWith && isChecked && (react_2.default.createElement("div", { className: 'ml-7 flex flex-col gap-2' },
                    react_2.default.createElement(Box_1.PHXBox, { mb: 'atomic' },
                        react_2.default.createElement(divider_1.PHXDivider, null)),
                    react_2.default.createElement("div", { className: 'flex items-center justify-between ' },
                        react_2.default.createElement(Text_1.PHXText, null, notifyWith.title),
                        react_2.default.createElement(Toggle_1.default, { active: !!notifyActive, onChange: () => handleChangeNotifyWith(targetConfig, notifyWith.value) })),
                    react_2.default.createElement(Text_1.PHXText, { tone: 'subdued' }, notifyWith.description),
                    react_2.default.createElement(divider_1.PHXDivider, null))),
                isChecked && (react_2.default.createElement("div", null,
                    react_2.default.createElement(radio_group_select_1.CheckboxGroup, { errors: (_e = (_d = errors === null || errors === void 0 ? void 0 : errors.target) === null || _d === void 0 ? void 0 : _d[targetIndex]) === null || _e === void 0 ? void 0 : _e.filter, handleChangeFilter: handleChangeFilter, listRadio: listRadio, listTargetSelected: listTargetSelected, schoolYearId: schoolYearId, selectOptions: selectOptions, target: targetConfig })))));
        }))))));
};
exports.PHXFormTarget = PHXFormTarget;
//# sourceMappingURL=PHXFormTarget.js.map