import { defineStore } from 'pinia';

import { getMyMessagesCount, getMyWaits } from '@/api/my-workbenches';
import { MESSAGE_TYPE } from '@/config/constants';

const useWorkStore = defineStore('work', {
  state: () => ({
    counts: {
      message: 0,
      work: 0,
      notice: 0,
    },
  }),
  actions: {
    async updateWorkCounts() {
      const task = [
        {
          type: 'message',
          func: () => getMyMessagesCount(Object.keys(MESSAGE_TYPE).join()),
        },
        {
          type: 'work',
          func: async () => {
            const data = await getMyWaits({
              flowTaskTypeEnum: 'ALL',
              pageNumber: 1,
              pageSize: 1,
            });

            return data ? data.total : 0;
          },
        },
        {
          type: 'notice',
          func: () => getMyMessagesCount('SYSTEM'),
        },
      ];
      let countAll = task.map((item) => item.func());
      const data = await Promise.all(countAll).catch(() => {});
      if (!data) return;

      let counts = {};
      data.forEach((count, index) => {
        counts[task[index].type] = count;
      });
      this.counts = counts;
    },
  },
});

export default useWorkStore;
