import { useEffect, useState } from 'react';
import { ERoleCode, FILTER_BY } from '../constant';
import { INSERT_TARGET_MUTATION, UPDATE_TARGET_BY_PK_MUTATION, UPDATE_TARGET_BY_ROLE_MUTATION, } from '../graphql/mutation';
import { GET_LIST_ROLE_QUERY } from '../graphql/query';
import { getObjectType } from '../ultis/get-object-type';
import PHXFuncGetLoggedInfo from '../../Func/getLoginInfo';
import PHXGetCurrentYearWithTermV3 from '../../Func/SchoolYearV3/getSchoolYearV3';
import { PHXClientMutationV3, PHXClientQueryV3 } from '../../Func/GRPC/PHXGrpcClientV3';
export const useTargetSelect = () => {
    var _a, _b;
    const userInfo = PHXFuncGetLoggedInfo();
    const schoolYear = PHXGetCurrentYearWithTermV3();
    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 [roles, setRoles] = useState([]);
    const getDataTargetSubmit = (data, targetId) => {
        const result = [];
        data.forEach((item) => {
            var _a;
            const { filter, notifyWith, target } = item;
            const roleId = (_a = roles.find((role) => role.role_code === target)) === null || _a === void 0 ? void 0 : _a.id;
            if (!roleId && target !== ERoleCode.DEPARTMENT)
                return;
            const isDepartmentOrStaff = target === ERoleCode.DEPARTMENT || target === ERoleCode.STAFF;
            const isAll = filter.some((f) => f.filterBy === FILTER_BY.ALL && isDepartmentOrStaff);
            if (isAll) {
                result.push({
                    role_id: roleId,
                    is_all: true,
                    notify_with: notifyWith,
                    object_type: getObjectType(target),
                    ...(targetId ? { target_id: targetId } : {}),
                });
                return;
            }
            const submitItem = {
                role_id: roleId,
                is_all: false,
                notify_with: notifyWith,
                object_type: getObjectType(target),
                target_educational_levels: { data: [] },
                target_grades: { data: [] },
                target_classrooms: { data: [] },
                target_users: { data: [] },
                target_departments: { data: [] },
                ...(targetId ? { target_id: targetId } : {}),
            };
            filter.forEach((f) => {
                const { filterBy, filterValues } = f;
                if (filterBy === FILTER_BY.EDUCATIONAL_LEVEL) {
                    submitItem.target_educational_levels.data = filterValues.map((v) => ({
                        educational_level_id: v.id,
                    }));
                }
                if (filterBy === FILTER_BY.GRADE) {
                    submitItem.target_grades.data = filterValues.map((v) => ({
                        grade_id: v.id,
                    }));
                }
                if (filterBy === FILTER_BY.CLASSROOM) {
                    submitItem.target_classrooms.data = filterValues.map((v) => ({
                        classroom_id: v.id,
                    }));
                }
                if (filterBy === FILTER_BY.DEPARTMENT) {
                    submitItem.target_departments.data = filterValues.map((v) => ({
                        department_id: v.id,
                    }));
                }
                if (filterBy === FILTER_BY.CUSTOM_LIST) {
                    submitItem.target_users.data = filterValues.map((v) => ({
                        user_id: v.id,
                    }));
                }
            });
            result.push(submitItem);
        });
        return result;
    };
    const handleInsertTarget = async ({ data }) => {
        var _a;
        const typeCode = data === null || data === void 0 ? void 0 : data.type_code;
        const dataSubmit = {
            school_id: userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id,
            creator_id: userInfo === null || userInfo === void 0 ? void 0 : userInfo.id,
            name: data.name,
            school_year_id: schoolYearId,
            target_by_roles: {
                data: getDataTargetSubmit(data.target),
            },
            ...(typeCode ? { type_code: typeCode } : {}),
        };
        const { data: { insert_user_segment_target: { returning }, }, } = await PHXClientMutationV3({
            query: INSERT_TARGET_MUTATION,
            variables: {
                data: dataSubmit,
            },
            isDelay: false,
        });
        return { id: (_a = returning[0]) === null || _a === void 0 ? void 0 : _a.id };
    };
    const handleUpdateTarget = async (id, data) => {
        if (!id)
            return;
        try {
            await PHXClientMutationV3({
                query: UPDATE_TARGET_BY_PK_MUTATION,
                variables: {
                    id,
                    data: {
                        ...data,
                        updated_at: 'now',
                    },
                },
                isDelay: false,
            });
        }
        catch (e) {
            console.error(e);
        }
    };
    const handleUpdateTargetByRole = async ({ data, id }) => {
        try {
            const { target, ...rest } = data;
            await PHXClientMutationV3({
                query: UPDATE_TARGET_BY_ROLE_MUTATION,
                variables: {
                    targetId: id,
                    targetByRoles: getDataTargetSubmit(target, id),
                },
                isDelay: false,
            });
            const typeCode = data === null || data === void 0 ? void 0 : data.type_code;
            const payloadUpdateTarget = {
                name: rest.name,
                school_year_id: rest.school_year_id || schoolYearId,
                ...(typeCode ? { type_code: typeCode } : {}),
            };
            await handleUpdateTarget(id, payloadUpdateTarget);
        }
        catch (e) {
            console.error(e);
        }
    };
    const initData = async () => {
        try {
            const { data: { role }, } = await PHXClientQueryV3({
                query: GET_LIST_ROLE_QUERY,
                variables: {
                    schoolId: userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id,
                },
                isDelay: false,
            });
            setRoles(role);
        }
        catch (e) {
            console.error(e);
        }
    };
    useEffect(() => {
        initData();
    }, []);
    return { handleInsertTarget, handleUpdateTargetByRole, handleUpdateTarget };
};
//# sourceMappingURL=use-target-select.js.map