import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useProjectApi } from '@/api/project/index';
import to from 'await-to-js';

const projectApi = useProjectApi();

export const useProjectStore = defineStore('project', () => {
  // ==================== State ====================
  // 定义三种类型的列表字典和分页结构
  const verticalList = ref<any[]>([]);
  const verticalPagination = ref({ pageNum: 1, pageSize: 25, total: 0 });
  
  const horizontalList = ref<any[]>([]);
  const horizontalPagination = ref({ pageNum: 1, pageSize: 25, total: 0 });

  const spontaneityList = ref<any[]>([]);
  const spontaneityPagination = ref({ pageNum: 1, pageSize: 25, total: 0 });

  const changeList = ref<any[]>([]);

  // 变更详情数据
  const changeDetailData = ref<any>({});
  const projectBaseData = ref<any>({});
  const projectDetailData = ref<any>({});
  const changePreData = ref<any>(null);
  const changeAfterData = ref<any>(null);

  // 中检任务数据
  const inspList = ref<any[]>([]);
  // 单条中检详情数据
  const inspDetailData = ref<any>({});

  // 科研成果数据
  const paperData = ref<any[]>([]);
  const workData = ref<any[]>([]);
  const patentData = ref<any[]>([]);
  const awardData = ref<any[]>([]);

  // 结题数据
  const conclusionList = ref<any[]>([]);

  // 经费数据
  const claimdData = ref<any[]>([]);
  const outBoundData = ref<any[]>([]);
  const rebateData = ref<any[]>([]);
  const fundsData = ref<any>({});

  const loadings = {
    fetchVerticalLoading: ref<boolean>(false),
    fetchHorizontalLoading: ref<boolean>(false),
    fetchSpontaneityLoading: ref<boolean>(false),
    fetchChangeListLoading: ref<boolean>(false),
    fetchChangeDetailLoading: ref<boolean>(false),
    fetchInspListLoading: ref<boolean>(false),
    fetchAchievementLoading: ref<boolean>(false),
    fetchConclusionLoading: ref<boolean>(false),
    fetchFundingLoading: ref<boolean>(false)
  } as const;

  /**
   * 设置加载状态
   */
  function setRequestLoading(field: keyof typeof loadings, value: boolean) {
    loadings[field].value = value;
  }

  // ==================== Actions ====================

  /**
   * 获取纵向项目列表
   * @param queryParams 外部额外传入的查询条件
   * @param reset 是否重置页码刷新
   */
  async function fetchVerticalProjects(queryParams: any = {}, reset = false) {
    if (reset) {
      verticalPagination.value.pageNum = 1;
      verticalList.value = [];
    }
    
    setRequestLoading('fetchVerticalLoading', true);
    
    const params = {
      pageNum: verticalPagination.value.pageNum,
      pageSize: verticalPagination.value.pageSize,
      ...queryParams
    };

    const [err, res] = await to(projectApi.getVerticalList(params)) as [any, any];

    setRequestLoading('fetchVerticalLoading', false);

    if (err) {
      console.error('fetchVerticalProjects error:', err);
      return { success: false, rows: [], total: 0 };
    }

    if (res && res.code === 200) {
      let rows = res.data?.list || res.data?.rows || res.rows || (Array.isArray(res.data) ? res.data : []);
      if (!Array.isArray(rows)) rows = [];
      const total = res.data?.total || res.total || 0;
      
      verticalList.value = reset ? rows : [...verticalList.value, ...rows];
      verticalPagination.value.total = total;
      
      return { success: true, rows, total };
    }
    
    return { success: false, rows: [], total: 0 };
  }
  
  /**
   * 纵向列表加载下一页
   */
  async function loadMoreVerticalProjects(queryParams: any = {}) {
    verticalPagination.value.pageNum++;
    return await fetchVerticalProjects(queryParams, false);
  }

  /**
   * 获取横向项目列表
   */
  async function fetchHorizontalProjects(queryParams: any = {}, reset = false) {
    if (reset) {
      horizontalPagination.value.pageNum = 1;
      horizontalList.value = [];
    }
    
    setRequestLoading('fetchHorizontalLoading', true);
    
    const params = {
      pageNum: horizontalPagination.value.pageNum,
      pageSize: horizontalPagination.value.pageSize,
      ...queryParams
    };

    const [err, res] = await to(projectApi.getHorizontalList(params)) as [any, any];

    setRequestLoading('fetchHorizontalLoading', false);

    if (err) {
      console.error('fetchHorizontalProjects error:', err);
      return { success: false, rows: [], total: 0 };
    }

    if (res && res.code === 200) {
      let rows = res.data?.list || res.data?.rows || res.rows || (Array.isArray(res.data) ? res.data : []);
      if (!Array.isArray(rows)) rows = [];
      const total = res.data?.total || res.total || 0;
      
      horizontalList.value = reset ? rows : [...horizontalList.value, ...rows];
      horizontalPagination.value.total = total;
      
      return { success: true, rows, total };
    }
    
    return { success: false, rows: [], total: 0 };
  }

  async function loadMoreHorizontalProjects(queryParams: any = {}) {
    horizontalPagination.value.pageNum++;
    return await fetchHorizontalProjects(queryParams, false);
  }

  /**
   * 获取校内项目列表
   */
  async function fetchSpontaneityProjects(queryParams: any = {}, reset = false) {
    if (reset) {
      spontaneityPagination.value.pageNum = 1;
      spontaneityList.value = [];
    }
    
    setRequestLoading('fetchSpontaneityLoading', true);
    
    const params = {
      pageNum: spontaneityPagination.value.pageNum,
      pageSize: spontaneityPagination.value.pageSize,
      ...queryParams
    };

    const [err, res] = await to(projectApi.getSpontaneityList(params)) as [any, any];

    setRequestLoading('fetchSpontaneityLoading', false);

    if (err) {
      console.error('fetchSpontaneityProjects error:', err);
      return { success: false, rows: [], total: 0 };
    }

    if (res && res.code === 200) {
      let rows = res.data?.list || res.data?.rows || res.rows || (Array.isArray(res.data) ? res.data : []);
      if (!Array.isArray(rows)) rows = [];
      const total = res.data?.total || res.total || 0;
      
      spontaneityList.value = reset ? rows : [...spontaneityList.value, ...rows];
      spontaneityPagination.value.total = total;
      
      return { success: true, rows, total };
    }
    
    return { success: false, rows: [], total: 0 };
  }

  async function loadMoreSpontaneityProjects(queryParams: any = {}) {
    spontaneityPagination.value.pageNum++;
    return await fetchSpontaneityProjects(queryParams, false);
  }

  /**
   * 获取项目变更列表
   */
  async function fetchProjectChanges(projectId: number, projectType: string = '10') {
    setRequestLoading('fetchChangeListLoading', true);
    
    let typeCode = projectType;
    if (projectType === 'vertical') typeCode = '10';
    if (projectType === 'horizontal') typeCode = '20';
    if (projectType === 'spontaneity') typeCode = '30';

    const params = {
      projectId: projectId,
      projectType: typeCode,
      noPage: true
    };
    
    const [err, res] = await to(projectApi.getProjectDetailsList(params)) as [any, any];
    
    setRequestLoading('fetchChangeListLoading', false);

    if (err) {
      console.error('fetchProjectChanges error:', err);
      changeList.value = [];
      return { success: false };
    }

    if (res && res.code === 200) {
      changeList.value = res.data || [];
      return { success: true };
    }

    changeList.value = [];
    return { success: false };
  }

  /**
   * 获取项目中检列表
   */
  async function fetchInspList(projectId: number, projectType: string = '10') {
    setRequestLoading('fetchInspListLoading', true);

    let typeCode = projectType;
    if (projectType === 'vertical') typeCode = '10';
    if (projectType === 'horizontal') typeCode = '20';
    if (projectType === 'spontaneity') typeCode = '30';

    const params = {
      projectId: projectId,
      projectType: typeCode,
      pageSize: 9999
    };
    
    const [err, res] = await to(projectApi.getTaskList(params)) as [any, any];
    
    setRequestLoading('fetchInspListLoading', false);

    if (err) {
      console.error('fetchInspList error:', err);
      inspList.value = [];
      return { success: false };
    }

    if (res && res.code === 200) {
      inspList.value = res.data?.list || [];
      return { success: true };
    }

    inspList.value = [];
    return { success: false };
  }

  /**
   * 获取项目中检详情
   */
  async function fetchInspDetail(taskId: number, operatorType?: string, projectType?: string) {
    setRequestLoading('fetchInspListLoading', true);
    inspDetailData.value = {};
    
    let apiCall = projectApi.getTaskDetail({ id: taskId, type: operatorType == '10' ? '10' : '' });
    if (projectType === 'horizontal' || projectType === '20') {
      apiCall = projectApi.getHorizontalInspTaskDetail({ id: taskId, type: operatorType == '10' ? '10' : '' });
    }
    
    const [err, res] = await to(apiCall) as [any, any];
    
    setRequestLoading('fetchInspListLoading', false);
    if (!err && res?.code === 200) {
      inspDetailData.value = res.data || {};
      return { success: true };
    }
    return { success: false };
  }

  /**
   * 获取项目变更的具体详情
   * 这个方法统筹了获取变更信息以及对应的主项目信息
   */
  async function fetchProjectChangeDetail(changeId: number, projectType: string, projectId: number) {
    setRequestLoading('fetchChangeDetailLoading', true);
    
    // 1. 获取变更单详细信息
    const [errChange, resChange] = await to(projectApi.getProjectChangeDetail({ id: changeId })) as [any, any];
    
    // 2. 获取对应的原项目详细信息
    let baseApiCall = null;
    if (projectType === '10' || projectType === 'vertical') {
      baseApiCall = projectApi.getVerticalEntityById({ id: projectId });
    } else if (projectType === '20' || projectType === 'horizontal') {
      baseApiCall = projectApi.getHoriEntityById({ id: projectId });
    } else if (projectType === '30' || projectType === 'spontaneity') {
      baseApiCall = projectApi.getSpontaneityEntityById({ id: projectId });
    }
    
    if (baseApiCall) {
      const [errBase, resBase] = await to(baseApiCall) as [any, any];
      if (!errBase && resBase?.code === 200) {
        projectBaseData.value = resBase.data || {};
      } else {
        projectBaseData.value = {};
      }
    }

    // 3. 业务数据填充和反序列化解析（无需在页面写JSON.parse）
    if (!errChange && resChange?.code === 200) {
      const data = resChange.data || {};
      changeDetailData.value = data;
      
      try {
        changePreData.value = data.changeDataPre ? JSON.parse(data.changeDataPre) : null;
      } catch {
        changePreData.value = null;
      }
      
      try {
        changeAfterData.value = data.changeDataAfter ? JSON.parse(data.changeDataAfter) : null;
      } catch {
        changeAfterData.value = null;
      }
    } else {
      changeDetailData.value = {};
      changePreData.value = null;
      changeAfterData.value = null;
    }
    
    setRequestLoading('fetchChangeDetailLoading', false);
  }

  /**
   * 获取项目及相关详细信息 (主数据详情)
   * 针对纵向、横向、校园项目类型，分发到不同的 API 接口
   */
  async function fetchProjectDetailData(id: number, type: string) {
    projectDetailData.value = {};
    let apiCall = null;
    
    if (type === 'vertical' || type === '10') {
      apiCall = projectApi.getVerticalEntityById({ id });
    } else if (type === 'horizontal' || type === '20') {
      apiCall = projectApi.getHoriEntityById({ id });
    } else if (type === 'spontaneity' || type === '30') {
      apiCall = projectApi.getSpontaneityEntityById({ id });
    }
    
    if (!apiCall) return { success: false, msg: '未知项目类型' };
    
    const [err, res] = await to(apiCall) as [any, any];
    if (!err && res?.code === 200) {
      projectDetailData.value = res.data || {};
      return { success: true };
    }
    return { success: false };
  }

  /**
   * 获取项目科研成果数据
   */
  async function fetchAchievements(projectCode: string, projectType: string = '10') {
    setRequestLoading('fetchAchievementLoading', true);
    
    let typeCode = projectType;
    if (projectType === 'vertical') typeCode = '10';
    if (projectType === 'horizontal') typeCode = '20';
    if (projectType === 'spontaneity') typeCode = '30';

    const query = { projectCode, projectType: typeCode };

    Promise.all([
      projectApi.getPaperByProject(query),
      projectApi.getWorkByProject(query),
      projectApi.getPatentByProject(query),
      projectApi.getAwardsByProject(query)
    ]).then(([paper, work, patent, awards]: any) => {
      paperData.value = paper?.data || [];
      workData.value = work?.data || [];
      patentData.value = patent?.data || [];
      awardData.value = awards?.data || [];
    }).catch(err => {
      console.error('fetchAchievements error:', err);
    }).finally(() => {
      setRequestLoading('fetchAchievementLoading', false);
    });
  }
  /**
   * 获取结题信息
   */
  async function fetchConclusion(projectId: number, projectType: string = '10') {
    setRequestLoading('fetchConclusionLoading', true);
    let typeCode = projectType;
    if (projectType === 'vertical') typeCode = '10';
    if (projectType === 'horizontal') typeCode = '20';
    if (projectType === 'spontaneity') typeCode = '30';
    
    const [err, res] = await to(projectApi.getConclusionTaskList({ projectId, projectType: typeCode, pageSize: 9999 })) as [any, any];
    setRequestLoading('fetchConclusionLoading', false);
    if (!err && res?.code === 200) {
      conclusionList.value = res.data?.list || [];
    } else {
      conclusionList.value = [];
    }
  }

  /**
   * 获取经费信息
   */
  async function fetchFunding(projectId: number, projectType: string = '10') {
    setRequestLoading('fetchFundingLoading', true);
    let typeCode = projectType;
    if (projectType === 'vertical') typeCode = '10';
    if (projectType === 'horizontal') typeCode = '20';
    if (projectType === 'spontaneity') typeCode = '30';

    const params = { projectId, projectType: typeCode, pageSize: 9999 };

    Promise.all([
      projectApi.getRecordList(params),
      projectApi.getOutBoundList(params),
      projectApi.getExpenseList(params),
      projectApi.getFundsStatistics({ projectId, projectType: typeCode })
    ]).then(([claimd, outbound, rebate, statistics]: any) => {
      claimdData.value = claimd?.data?.list || [];
      outBoundData.value = outbound?.data?.list || [];
      rebateData.value = rebate?.data?.list || [];
      fundsData.value = statistics?.data || {};
    }).catch(err => {
      console.error('fetchFunding error:', err);
    }).finally(() => {
      setRequestLoading('fetchFundingLoading', false);
    });
  }

  return {
    ...loadings,
    verticalList,
    verticalPagination,
    horizontalList,
    horizontalPagination,
    spontaneityList,
    spontaneityPagination,
    fetchVerticalProjects,
    loadMoreVerticalProjects,
    fetchHorizontalProjects,
    loadMoreHorizontalProjects,
    fetchSpontaneityProjects,
    loadMoreSpontaneityProjects,
    changeList,
    changeDetailData,
    projectDetailData,
    projectBaseData,
    changePreData,
    changeAfterData,
    inspList,
    inspDetailData,
    paperData,
    workData,
    patentData,
    awardData,
    conclusionList,
    claimdData,
    outBoundData,
    rebateData,
    fundsData,
    fetchProjectChanges,
    fetchProjectChangeDetail,
    fetchProjectDetailData,
    fetchInspList,
    fetchInspDetail,
    fetchAchievements,
    fetchConclusion,
    fetchFunding
  };
});
