import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { getParentBindChildList, type ParentBindChildItem } from '@/api/parent';
import { getCache, removeCache, setCache } from '@/utils/cache';

export interface ParentChildItem {
    bindId: string;
    id: string;
    name: string;
    account: string;
    className: string;
    school: string;
    examNo: string;
    parentId: string;
    adminFlag: number;
    isSelfBind: boolean;
}

const CACHE_ACTIVE_CHILD_ID = 'parentActiveChildId';

const emptyChild = (): ParentChildItem => ({
    bindId: '',
    id: '',
    name: '--',
    account: '',
    className: '--',
    school: '--',
    examNo: '--',
    parentId: '',
    adminFlag: 0,
    isSelfBind: false,
});

const mapBindRow = (row: ParentBindChildItem, selfParentId: string): ParentChildItem => {
    const account = row.child?.account || '';
    const parentId = String(row.parent?.id ?? '');
    return {
        bindId: String(row.id ?? row.child?.id ?? ''),
        id: String(row.child?.id ?? row.id ?? ''),
        name: row.child?.name || row.child?.nickname || '未命名',
        account,
        className: row.child?.gradeName || '',
        school: '',
        examNo: account,
        parentId,
        adminFlag: Number(row.adminFlag || 0),
        isSelfBind: parentId !== '' && parentId === selfParentId,
    };
};

/**
 * 家长端 - 绑定孩子列表与当前选中孩子
 */
export const useParentStore = defineStore('parent', () => {
    const childrenList = ref<ParentChildItem[]>([]);
    const activeChildId = ref<string>(getCache(CACHE_ACTIVE_CHILD_ID) || '');
    const loading = ref(false);

    const activeChild = computed(() => {
        if (!childrenList.value.length) {
            return emptyChild();
        }
        const matched = childrenList.value.find((item) => item.id === activeChildId.value);
        return matched || childrenList.value[0];
    });

    const activeChildIndex = computed(() => {
        const index = childrenList.value.findIndex((item) => item.id === activeChildId.value);
        return index >= 0 ? index : 0;
    });

    const hasActiveChild = computed(() => !!activeChild.value.id);

    const ensureActiveChild = () => {
        if (!childrenList.value.length) {
            activeChildId.value = '';
            removeCache(CACHE_ACTIVE_CHILD_ID);
            return;
        }
        const exists = childrenList.value.some((item) => item.id === activeChildId.value);
        if (!activeChildId.value || !exists) {
            activeChildId.value = childrenList.value[0].id;
            setCache(CACHE_ACTIVE_CHILD_ID, activeChildId.value);
        }
    };

    const selectChildByIndex = (index: number) => {
        const child = childrenList.value[index];
        if (!child) return;
        activeChildId.value = child.id;
        setCache(CACHE_ACTIVE_CHILD_ID, child.id);
    };

    const fetchBindChildren = async (parentId?: string | number) => {
        const pid = parentId ?? '';
        if (pid === '' || pid == null) {
            childrenList.value = [];
            ensureActiveChild();
            return [];
        }

        loading.value = true;
        try {
            const res = await getParentBindChildList({ parentId: pid });
            const rows = res.data?.rows || [];
            const selfParentId = String(pid);
            childrenList.value = rows.map((row) => mapBindRow(row, selfParentId));
            ensureActiveChild();
            return childrenList.value;
        } catch (err) {
            console.error('[parent] fetchBindChildren error', err);
            childrenList.value = [];
            ensureActiveChild();
            throw err;
        } finally {
            loading.value = false;
        }
    };

    const clear = () => {
        childrenList.value = [];
        activeChildId.value = '';
        removeCache(CACHE_ACTIVE_CHILD_ID);
    };

    return {
        childrenList,
        activeChildId,
        activeChild,
        activeChildIndex,
        hasActiveChild,
        loading,
        fetchBindChildren,
        selectChildByIndex,
        ensureActiveChild,
        clear,
    };
});
