// 智库概览信息
import request, { getToken } from "@/api/request.js";

// 智库列表
export function getThinkTankList() {
  return request({
    method: 'GET',
    url: `/api/thinkTankOverview/thinkTanks`,

  })
}

export function getAllThinkTankList(params) {
  return request({
    method: 'GET',
    url: '/api/thinkTankOverview/thinkTanks/page',
    params: params  
  })
}
//智库概览:获取智库发布
export function getNewReport() {
  return request({
    method: 'GET',
    url: `/api/thinkTankOverview/newReport`,

  })
}

// 风险信号
export function getThinkTankRiskSignal() {
  return request({
    method: 'GET',
    url: `/api/thinkTankOverview/riskSignal`,

  })
}

/**
 * 政策建议趋势分布（数量变化趋势）
 * @param {{ startDate: string, endDate: string }} params - 如 2024-01-01 ~ 2024-12-31
 */
export function getThinkTankPolicyIndustryChange(params) {
  return request({
    method: "GET",
    url: `/api/thinkTankOverview/policyIndustryChange`,
    params: {
      startDate: params.startDate,
      endDate: params.endDate
    },
    // 无数据年份（如 2026）后端可能返回 HTTP 400/500，避免走全局错误提示
    validateStatus: (status) =>
      (status >= 200 && status < 300) || status === 400 || status === 500
  });
}

// 政策建议领域分布
export function getThinkTankPolicyIndustry(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankOverview/policyIndustry/${params.year}`,
    params
  })
}

// 资金流向
export function getThinkTankDonation() {
  return request({
    method: 'GET',
    url: `/api/thinkTankOverview/donation`,

  })
}

//智库概览:获取智库研究热点
export function getThinkTankHot(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankOverview/research/hot/${params}`,

  })
}


// 行业领域字典列表
export function getHylyList() {
  return request({
    method: 'GET',
    url: `/api/billImpactAnalysis/industry/hylyList`,
  })
}


/**
 * 智库概览/智库动态-智库报告
 * GET /api/thinkTankOverview/report
 * 常用 query：pageNum, pageSize, sortFun, domainIds, startDate, endDate, category（调查项目）, thinkTankId（详情页）, keyword（动态搜索）
 */
export function getThinkTankReport(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankOverview/report`,
    params: params
  })
}

//智库概览调查项目
export function getThinkTankProjects(params) {
  return request({
    method: 'GET',
    url: `/api/think-tank/projects`,
    params
  })
}
//智库概览页国会听证会
export function getThinkTankTestimonies(params) {
  return request({
    method: 'GET',
    url: `/api/think-tank/testimonies`,
    params
  })
}
//智库调查项目详情主页
export function getThinkTankProjectsInfo(params) {
  return request({
    method: 'GET',
    url: `/api/think-tank/projects/${params.id}`,

  })
}
//智库国会听证会详情主页
export function getThinkTankHearingInfo(params) {
  return request({
    method: 'GET',
    url: `/api/think-tank/testimonies/${params.id}`,

  })
}
// 智库详情-调查项目（按智库 id）
export function getThinkTankProjectsByThinkTankId(params) {
  return request({
    method: 'GET',
    url: `/api/think-tank/${params.thinkTankId}/projects`,
    params: {
      pageNum: params.pageNum,
      pageSize: params.pageSize,
      sortFun: params.sortFun,
      sortField: params.sortField,
      sortOrder: params.sortOrder,
      domainIds: params.domainIds,
      startDate: params.startDate,
      endDate: params.endDate,
      projectName: params.projectName,
    }
  })
}

// 智库动态-国会听证会（按智库 id）
export function getThinkTankTestimoniesByThinkTankId(params) {
  return request({
    method: 'GET',
    url: `/api/think-tank/${params.thinkTankId}/testimonies`,
    params: {
      pageNum: params.pageNum,
      pageSize: params.pageSize,
      
      domainIds: params.domainIds,
      startDate: params.startDate,
      endDate: params.endDate,
      title: params.title,
    }
  })
}
//智库调查项目详情作者
export function getThinkTankProjectsAuthors(params) {
  return request({
    method: 'GET',
    url: `/api/think-tank/projects/${params.id}/team`,

  })
}
// 智库概览：政策建议（资源库-政策建议）
export function getThinkTankOverviewPolicy(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankOverview/policy`,
    params
  })
}

/*********  智库信息 */
//智库百科:获取全局信息
export function getThinkTankSummary(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankInfo/summary/${params.id}`,

  })
}


//智库报告:获取智库报告类型
export function getThinkDynamicsReportType() {
  return request({
    method: 'GET',
    url: `/api/thinkTankInfo/reportType`,
  })
}

//智库动态:获取智库报告
export function getThinkDynamicsReport(params) {
  const safe = params || {}
  // 兼容两种调用方式：
  // 1) { id, startDate, authorName, currentPage, pageSize, researchTypeIds, searchText, sortFun, years }
  // 2) { id, startDate, parmas: { authorName, currentPage, pageSize, researchTypeIds, searchText, sortFun, years } }
  const inner = safe.parmas && typeof safe.parmas === 'object' ? safe.parmas : {}
  const id = safe.id
  const startDate = safe.startDate

  const authorName = inner.authorName ?? safe.authorName ?? ''
  const currentPage = inner.currentPage ?? safe.currentPage ?? 1
  const pageSize = inner.pageSize ?? safe.pageSize ?? 10
  const researchTypeIds = inner.researchTypeIds ?? safe.researchTypeIds ?? ''
  const searchText = inner.searchText ?? safe.searchText ?? ''
  const sortFun = inner.sortFun ?? safe.sortFun ?? false
  const years = inner.years ?? safe.years ?? null

  const query = { currentPage, pageSize, sortFun }
  // 仅在有值时才传，避免后端按空值筛选
  if (authorName) query.authorName = authorName
  if (researchTypeIds) query.researchTypeIds = researchTypeIds
  if (searchText) query.searchText = searchText
  if (years !== null && years !== undefined && years !== '') query.years = years

  return request({
    method: 'GET',
    url: `/api/thinkTankInfo/report/${id}/${startDate}`,
    params: query
  })
}

// 智库领域观点分析（流式）
// [POST] 8.140.26.4:10029/report-domain-view-analysis
// 每次请求体：{ domain, report_view_list }（一个 domain）；多领域由前端按领域循环多次调用
export function postReportDomainViewAnalysis(data) {
  return request({
    method: 'POST',
    // 开发环境走 Vite 同源代理，避免浏览器跨域（见 vite.config.js：/intelligent-api -> 8.140.26.4:10029）
    url: '/intelligent-api/report-domain-view-analysis',
    data
  })
}

/**
 * 智库领域观点分析（真正流式，逐 chunk 回调）
 * @param {object} data
 * @param {{ onReasoningChunk?: (chunk: string) => void, onMessage?: (msg: any) => void }} handlers
 */
export async function postReportDomainViewAnalysisStream(data, handlers = {}) {
  const { onReasoningChunk, onMessage } = handlers
  const token = getToken()
  const response = await fetch('/intelligent-api/report-domain-view-analysis', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      ...(token ? { token } : {})
    },
    body: JSON.stringify(data)
  })

  if (!response.ok) {
    throw new Error(`流式分析请求失败: ${response.status}`)
  }

  // 兜底：非流式返回时仍可读取文本继续后续解析
  if (!response.body) {
    return await response.text()
  }

  const reader = response.body.getReader()
  const decoder = new TextDecoder('utf-8')
  let done = false
  let pending = ''
  let fullText = ''

  while (!done) {
    const result = await reader.read()
    done = result.done
    if (result.value) {
      const chunkText = decoder.decode(result.value, { stream: !done })
      fullText += chunkText
      pending += chunkText
      const lines = pending.split(/\r?\n/)
      pending = lines.pop() ?? ''
      for (const rawLine of lines) {
        const line = String(rawLine || '').trim()
        if (!line || !line.startsWith('data:')) continue
        const jsonText = line.slice(5).trim()
        if (!jsonText || jsonText === '[DONE]') continue
        try {
          const msg = JSON.parse(jsonText)
          if (typeof onMessage === 'function') onMessage(msg)
          if (msg?.type === 'reasoning' && msg?.chunk != null && typeof onReasoningChunk === 'function') {
            const c = String(msg.chunk)
            if (c) onReasoningChunk(c)
          }
        } catch (e) {
          // 忽略非 JSON 数据行
        }
      }
    }
  }

  // 处理最后一行残留
  const last = String(pending || '').trim()
  if (last.startsWith('data:')) {
    const jsonText = last.slice(5).trim()
    if (jsonText && jsonText !== '[DONE]') {
      try {
        const msg = JSON.parse(jsonText)
        if (typeof onMessage === 'function') onMessage(msg)
        if (msg?.type === 'reasoning' && msg?.chunk != null && typeof onReasoningChunk === 'function') {
          const c = String(msg.chunk)
          if (c) onReasoningChunk(c)
        }
      } catch (e) {
        // ignore
      }
    }
  }
  return fullText
}


//提出建议领域分布
export function getThinkPolicyIndustry(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankInfo/policyIndustry/${params.id}/${params.year}`,
  })
}
//提出政策建议涉及部门分布
export function getPolicyAdviceDeptDistribution(params){
   return request({
    method: 'GET',
    url: `/api/thinkTankInfo/policyDepartment/${params.id}/${params.year}`,
  })
}

//获取相关政策领域分布
export function getThinkPolicyIndustryTotal(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankInfo/policyIndustryTotal/${params.id}/${params.year}`,
  })
}

//获取热门研究方向变化趋势
export function getThinkPolicyIndustryChange(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankInfo/policyIndustryChange/${params.id}/${params.year}`,
  })
}

/**
 * 获取智库政策（政策追踪列表）

 */
export function getThinkPolicy(params) {
  return request({
    method: 'GET',
    url: '/api/thinkTankInfo/policy',
    params
  })
}

/**
 * 政府机构字典（政策追踪-涉及部门筛选项）
 * GET /api/commonDict/gov/agency
 * @returns {Promise<{ code: number, data: Array<{ id: string, name: string }> }>}
 */
export function getGovAgencyDict() {
  return request({
    method: 'GET',
    url: '/api/commonDict/gov/agency'
  })
}

//智库百科基本信息
export function getThinkTankInfoBasic(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankInfo/basic/${params}`,
  })
}

//获取全球分支机构
export function getThinkTankInfoBranch(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankInfo/branch/${params}`,
  })
}


//获取经费来源
export function getThinkTankFundsSource(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankInfo/fundsStatistics/${params}`,
  })
}

//获取研究领域演变
export function getThinkTankResearchAreae(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankInfo/researchArea/${params}`,
  })
}

//获取核心研究人员
export function getThinkTankPerson(params) {
  const { thinkTankId, currentPage, pageSize } = params
  return request({
    method: 'GET',
    url: `/api/thinkTankInfo/person/page`,
    params: {
      currentPage,
      pageNum: currentPage,
      page: currentPage,
      pageSize,
      thinkTankId
    }
  })
}

//智库报告:获取报告全局信息
export const getThinkTankReportSummary = (params) => {
  return request(
    {
      method: 'GET',
      url: `/api/thinkTankReport/summary/${params}`,
    }
  );
}
//智库报告：获取相关报告
export const getThinkTankReportRelated = (params) => {
  return request(
    {
      method: 'GET',
      url: `/api/thinkTankReport/related/${params}`,
    }
  );
}
//调查项目：获取项目报告
export const getThinkTankProjectRelated = (params) => {
  return request(
    {
      method: 'GET',
      url: `/api/think-tank/projects/${params}/reports`,
    }
  );
}

//获取报告原文
export const getThinkTankReportcontentUrl = (params) => {
  return request(
    {
      method: 'GET',
      url: `/api/thinkTankReport/contentUrl/${params}`,
    }
  );
}

//获取报告内容摘要
export function getThinkTankReportAbstract(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankReport/abstract/${params}`,
  })
}

//获取报告主要观点
export function getThinkTankReportContent(params) {
  const { id, currentPage, pageSize } = params
  return request({
    method: 'GET',
    url: `/api/thinkTankReport/content/${id}`,
    params: {
      currentPage,
      pageSize,
    }
  })
}

// 获取报告核心论点（支持关键字搜索）
export function getThinkTankReportViewpoint(params) {
  const { reportId, currentPage, pageSize, keyword = '', orgIds = '' } = params
  return request({
    method: 'GET',
    url: `/api/thinkTankReport/viewpoint/${reportId}`,
    params: {
      currentPage,
      pageSize,
      keyword,
      orgIds,
    }
  })
}
// 获取报告核心论点（支持关键字搜索）
export function getThinkTankHearingViewpoint(params) {
  const { testimonyId,  pageSize, keyword = '',pageNum } = params
  return request({
    method: 'GET',
    url: `/api/think-tank/testimonies/qa`,
    params: {
  
      pageSize,
      keyword,
      pageNum,
   testimonyId
    }
  })
}
//获取涉及科技领域
export function getThinkTankReportIndustry(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankReport/industry/${'Rand_RRA3572-1'}`,
  })
}

//获取科技领域词云
export function getThinkTankReportIndustryCloud(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankReport/keyword/${params.id}`,
  })
}
//获取调查项目词云
export function getThinkTankProjectCloud(params) {
  return request({
    method: 'GET',
    url: `/api/think-tank/projects/${params.id}/word-cloud`,
  })
}
//获取国会听证会词云
export function getThinkTankHearingCloud(params) {
  return request({
    method: 'GET',
    url: `/api/think-tank/testimonies/${params.id}/wordcloud`,
  })
}

//获取政策建议落实情况
export function getThinkTankReportPolicy(params) {
  return request({
    method: 'GET',
    url: `/api/thinkTankReport/policy/${params}`,
  })
}

//获取相关政策动态
export function getThinkTankReportPolicyAction(params) {
  const {
    reportId,
    currentPage,
    pageSize,
    keyword = "",
    orgIds = "",
    // 新增：按科技领域 / 标签过滤
    industryName = ""
  } = params;
  return request({
    method: 'GET',
    url: `/api/thinkTankReport/policyDetail/${reportId}`,
    params: {
      currentPage,
      pageSize,
      keyword,
      // 后端按标签过滤使用的字段
      industryName,
      orgIds,
    }
  })
}

//通用接口:获取新闻资讯智库模块
export function getThinkTankReportNews() {
  return request({
    method: 'GET',
    url: `/api/commonFeature/news/0102`,
  })
}

//获取人物动态 通用接口:获取社交媒体-智库模块
export function getThinkTankReportRemarks() {
  return request({
    method: 'GET',
    url: `/api/commonFeature/remarks/0102`,
  })
}
