import {defineStore} from "pinia";
import {reactive, ref} from "vue";
import Api from "../../api/index.js";

export const useSystemStore = defineStore('SystemStore', () => {
    const accountManagementPo = reactive({
        pid: null,
    });
    const message = ref([]);
    const messageCount = ref({
        one: 0,
        two: 0,
    });

    const getMessageCount = async () => {
        const {data: {list}} = await Api.system.getMessageCenter({type: 1});
        list.forEach(data => {
            const now = message.value.find(v => v.id === data.id);
            if (!now) message.value.push({...data, is_read: false});
        })
        const {data: {count}} = await Api.system.getChildrenCount();

        messageCount.value.one = count;
        messageCount.value.two = message.value.filter(v => !v.is_read).length;

        document.querySelectorAll('.uni-tabbar__item__dot').forEach(v => v.remove());
        // 生成角标
        if (messageCount.value.one + messageCount.value.two > 0) {
            const tabbar = document.querySelectorAll('.uni-tabbar__item')[2].querySelector('.uni-tabbar__bd');
            tabbar.style.position = 'relative';
            const div = document.createElement('div');
            div.className = 'uni-tabbar__item__dot';
            div.style.position = 'absolute';
            div.style.backgroundColor = 'red';
            div.style.color = 'white';
            div.style.width = '16px';
            div.style.height = '16px';
            div.style.borderRadius = '50%';
            div.style.display = 'flex';
            div.style.justifyContent = 'center';
            div.style.alignItems = 'center';
            div.style.fontSize = '12px';
            div.style.right = '-12px';
            div.style.top = '0';
            div.innerText = messageCount.value.one + messageCount.value.two;
            tabbar.appendChild(div);
        }
    }

    return {
        accountManagementPo,
        message,
        messageCount,
        getMessageCount,
    }
}, {
    persist: {
        key: 'SystemStore',
        pick: ['message'],
        storage: {
            getItem(key) {
                return uni.getStorageSync(key);
            },
            setItem(key, value) {
                uni.setStorageSync(key, value);
            }
        },
    }
});
