import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { useExecutionApi } from '@/api/execution';
import type { TodoItem } from '@/types/todo';
import to from 'await-to-js';

export const useTodoStore = defineStore('todo', () => {
  const executionApi = useExecutionApi();

  // 列表数据
  const list = ref<TodoItem[]>([]);
  // 总数
  const total = ref(0);
  // 加载状态
  const loading = ref(false);

  /**
   * 获取列表数据 (通用方法)
   * @param type 列表类型: approval | start | history
   * @param query 查询参数
   * @param append 是否追加数据 (用于翻页)
   */
  async function fetchList(type: 'approval' | 'start' | 'history', query: Record<string, any>, append = false) {
    loading.value = true;
    
    // 如果不是追加模式（如重新搜索、切换Tab），先清空列表，防止显示旧数据
    if (!append) {
      list.value = [];
      total.value = 0;
    }
    
    let apiFn;
    if (type === 'approval') {
      apiFn = executionApi.getOwnApproveList;
    } else if (type === 'start') {
      apiFn = executionApi.getOwnStartList;
    } else {
      apiFn = executionApi.getOwnApprovedList;
    }

    const [err, res] = await to(apiFn(query)) as [any, any];
    loading.value = false;

    if (err) {
      console.error(`获取${type}列表失败:`, err);
      return { success: false };
    }

    if (res && res.data) {
      const rows = res.data.list || [];
      total.value = res.data.total || 0;
      if (append) {
        list.value = list.value.concat(rows);
      } else {
        list.value = rows;
      }
      return { success: true, data: res.data };
    }

    return { success: false };
  }

  /**
   * 快捷获取首页待办 (Top 2)
   */
  async function fetchHomeTodoList() {
    return fetchList('approval', { platformId: 100010, pageNum: 1, pageSize: 2 }, false);
  }

  return {
    list,
    total,
    loading,
    fetchList,
    fetchHomeTodoList
  };
});
