import { normalizeResponseData, requestJson } from "./request"

const JSY_API_BASE = import.meta.env.VITE_JSY_API_BASE || "/jsyApi"

function joinBase(base, path) {
  if (/^https?:\/\//.test(path)) return path
  return `${base}${path.startsWith("/") ? path : `/${path}`}`
}

function unwrapResponse(response) {
  const failed =
    response?.success === false ||
    (response?.code !== undefined && ![0, 200, "0", "200"].includes(response.code))

  if (failed) {
    const error = new Error(response?.msg || response?.message || "接口请求失败")
    error.code = response?.code
    throw error
  }

  return normalizeResponseData(response)
}

function get(path, params, options = {}) {
  return requestJson(joinBase(JSY_API_BASE, path), {
    params,
    timeout: options.timeout || 12000,
  }).then(unwrapResponse)
}

function post(path, params, options = {}) {
  return requestJson(joinBase(JSY_API_BASE, path), {
    method: "POST",
    params,
    timeout: options.timeout || 12000,
  }).then(unwrapResponse)
}

export function getPastureCoreItems() {
  return post("/api/dataItem?group=pastures").then(normalizeRows)
}

export function getPastureDistribution() {
  return post("/api/muhu/distribution").then(normalizeRows)
}

export function getPastureAge() {
  return post("/api/muhu/age").then(normalizeRows)
}

export function getPastureOnline() {
  return post("/api/muhu/upline_rate").then(normalizeRows)
}

function normalizeRows(data) {
  if (Array.isArray(data)) return data
  if (Array.isArray(data?.rows)) return data.rows
  if (Array.isArray(data?.list)) return data.list
  if (Array.isArray(data?.data)) return data.data
  if (data?.data) return normalizeRows(data.data)
  if (data?.result) return normalizeRows(data.result)
  return []
}

export function getMuhuList(query = "", page = 1, pageSize = 80) {
  return get("/api/home/muhu_list", { query, page, pageSize }).then(normalizeRows)
}

export function getPastureGrasslandsById(id) {
  return get("/api/home/grasslandByPastureId", { id }).then(normalizeRows)
}

export function getGrasslandClickInfo(params = {}) {
  return get("/api/home/grasslandClickInfo", params, { timeout: 20000 }).then((data) => data?.data || data || null)
}

export function getPastureDetailsById(id) {
  return get("/api/pastureDetailsById", { id }).then((data) => data?.data || data || {})
}

export function getPasturesDetailsById(id) {
  return get("/api/pasturesDetails", { id }).then((data) => data?.data || data || {})
}

export function getPastureList() {
  return get("/api/pasturesList").then(normalizeRows)
}

export async function getPastureProfile() {
  const [core, distribution, age, online, pastureList, muhuList] = await Promise.allSettled([
    getPastureCoreItems(),
    getPastureDistribution(),
    getPastureAge(),
    getPastureOnline(),
    getPastureList(),
    getMuhuList("", 1, 10000),
  ])
  const pastureRows = pastureList.status === "fulfilled" ? pastureList.value : []
  const muhuRows = muhuList.status === "fulfilled" ? muhuList.value : []
  const primaryList = hasPastureAreaRows(muhuRows) ? muhuRows : hasPastureAreaRows(pastureRows) ? pastureRows : (muhuRows.length ? muhuRows : pastureRows)
  const list = mergePastureRows(primaryList, pastureRows, muhuRows)

  return {
    core: core.status === "fulfilled" ? core.value : [],
    distribution: distribution.status === "fulfilled" ? distribution.value : [],
    age: age.status === "fulfilled" ? age.value : [],
    online: online.status === "fulfilled" ? online.value : [],
    list,
  }
}

function mergePastureRows(primaryRows = [], ...sourceGroups) {
  const sourceMap = new Map()
  sourceGroups.flat().forEach((row) => {
    getPastureRowKeys(row).forEach((key) => {
      const current = sourceMap.get(key) || {}
      sourceMap.set(key, fillMissingPastureFields(current, row))
    })
  })
  return (Array.isArray(primaryRows) ? primaryRows : []).map((row) => {
    const supplement = getPastureRowKeys(row)
      .map((key) => sourceMap.get(key))
      .find(Boolean)
    return supplement ? fillMissingPastureFields(row, supplement) : row
  })
}

function fillMissingPastureFields(target = {}, source = {}) {
  const merged = { ...target }
  Object.entries(source || {}).forEach(([key, value]) => {
    if (merged[key] === undefined || merged[key] === null || merged[key] === "") {
      merged[key] = value
    }
  })
  return merged
}

function getPastureRowKeys(row = {}) {
  return [
    row.id,
    row.pastureId,
    row.pasturesId,
    row.pastures_id,
    row.muhuId,
    row.muhu_id,
    row.name,
    row.pasturesName,
    row.pastures_name,
    row.muhuName,
    row.muhu_name,
    row.pastureName,
    row.pasture_name,
  ]
    .map((value) => String(value || "").trim())
    .filter(Boolean)
}

function hasPastureAreaRows(rows = []) {
  return (Array.isArray(rows) ? rows : []).some((row) => {
    const value = row?.grasslandArea ?? row?.grassland_area ?? row?.acreage ?? row?.area ?? row?.areaRange ?? row?.area_range
    if (typeof value === "number") return value > 0
    const number = Number(String(value ?? "").replace(/,/g, "").match(/-?\d+(?:\.\d+)?/)?.[0])
    return Number.isFinite(number) && number > 0
  })
}
