import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useDocumentApi } from '@/api/document';
import to from 'await-to-js';

export const useDocumentInfoStore = defineStore('documentInfo', () => {
  const documentApi = useDocumentApi();
  const documentDetail = ref<any>(null);
  const loading = ref(false);

  /**
   * 根据业务编码和流程编码获取单据详情
   * @param defCode 流程定义编码
   * @param businessCode 业务代码 (可能是业务流水号，也可能是ID)
   */
  async function fetchDocumentDetail(defCode: string, businessCode: string) {
    if (!businessCode) return null;
    loading.value = true;
    documentDetail.value = null;

    let apiFn: any = null;
    let paramValue: any = businessCode;

    // 纵向项目/预申报
    if (['sci_project_vertical', 'pre_sci_project_vertical', 'sci_project_spontaneity_declaration_project'].includes(defCode)) {
      apiFn = documentApi.getVerticalByCode;
    }
    // 横向项目
    else if (defCode === 'sci_project_horizontal') {
      apiFn = documentApi.getHorizontalByCode;
    }
    // 校内项目
    else if (defCode === 'sci_project_spontaneity') {
      apiFn = documentApi.getSpontaneityByCode;
    }
    // 学术会议 (ID-based)
    else if (defCode === 'sci_academic_conferences') {
      apiFn = documentApi.getConferenceById;
    }
    // 学术讲座 (ID-based)
    else if (defCode === 'sci_academic_lectures') {
      apiFn = documentApi.getLectureById;
    }
    // 社会任职 (ID-based)
    else if (defCode === 'sci_academic_committee_positions') {
      apiFn = documentApi.getDutiesById;
    }
    // 人员派驻 (ID-based)
    else if (defCode === 'sci_scientific_researchers_dispatch') {
      apiFn = documentApi.getDispatchById;
    }
    // 学术成果
    else if (defCode === 'sci_academic_achievement') {
      const code = businessCode.includes('-') ? businessCode.split('-')[1] : businessCode;
      paramValue = code;
      if (businessCode.includes('学术论文')) {
        apiFn = documentApi.getPaperByCode;
      } else if (businessCode.includes('奖项荣誉')) {
        apiFn = documentApi.getAwardsByCode;
      } else if (businessCode.includes('学术专利') || businessCode.includes('专利转化')) {
        apiFn = documentApi.getPatentByCode;
      } else if (businessCode.includes('学术著作')) {
        apiFn = documentApi.getWorkByCode;
      }
    }
    // 学术委员会成果 (Code-based with split)
    else if (defCode === 'sci_academic_committee') {
      paramValue = businessCode.includes('-') ? businessCode.split('-')[1] : businessCode;
      apiFn = documentApi.getCommitteeByCode;
    }
    // 经费相关 (ID-based)
    else if (defCode === 'sci_fund_allot_apply') {
      apiFn = documentApi.getFundClaimById;
    }
    else if (defCode === 'sci_fund_expense') {
      apiFn = documentApi.getFundExpenseById;
    }
    else if (defCode === 'sci_fund_reward') {
      apiFn = documentApi.getFundRewardById;
    }
    else if (defCode === 'sci_fund_carryover') {
      apiFn = documentApi.getFundCarryoverById;
    }
    // 考核批次 (ID-based)
    else if (defCode === 'sci_assessment_batch') {
      apiFn = documentApi.getAssessmentBatchById;
    }
    // 项目中期/结项 (ID-based)
    else if (['sci_project_inspection', 'sci_project_conclusion'].includes(defCode)) {
      apiFn = documentApi.getProjectAuditById;
    }
    // 学科分类 (Code-based)
    else if (defCode === 'sci_project_discipline') {
      apiFn = documentApi.getDisciplineByCode;
    }

    if (!apiFn) {
      loading.value = false;
      console.warn('Unhandled defCode for API mapping:', defCode);
      return null;
    }

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

    if (err) {
      console.error('Fetch document detail error:', err);
      return null;
    }

    const data = res?.Data || res?.data;
    if (data) {
      documentDetail.value = data;
      return data;
    }

    return null;
  }

  return {
    documentDetail,
    loading,
    fetchDocumentDetail
  };
});
