import request from '@/utils/request'
import { handleTree, tansParams } from '@/utils/ruoyi'

const QUERY_FORM_PATTERNS = [/\/list$/i, /\/allocatedList$/i, /\/unallocatedList$/i]

function shouldSkipRepeatSubmit(url = '') {
  const normalizedUrl = String(url).split('?')[0]
  return QUERY_FORM_PATTERNS.some((pattern) => pattern.test(normalizedUrl))
}

export function postForm(url, data = {}, config = {}) {
  const customHeaders = config.headers || {}
  const headers = {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    ...(shouldSkipRepeatSubmit(url) && !Object.prototype.hasOwnProperty.call(customHeaders, 'repeatSubmit')
      ? { repeatSubmit: false }
      : {}),
    ...customHeaders
  }

  return request({
    ...config,
    url,
    method: 'post',
    data,
    headers,
    transformRequest: config.transformRequest || [(params) => tansParams(params)]
  })
}

export function buildZtree(list = []) {
  const flatNodes = list.map(item => ({
    ...item,
    id: item.id,
    parentId: item.pId,
    label: item.name,
    disabled: Boolean(item.nocheck)
  }))
  return handleTree(flatNodes, 'id', 'parentId')
}

export function extractCheckedKeys(list = []) {
  return list.filter(item => item.checked).map(item => item.id)
}
