import axios from 'axios'
import { get_session_api_headers } from '../api/auth'

/**
 * 检查 pagetype 是否为单页模式
 * @param entity pagetype 名称
 * @returns Promise<boolean> 是否为单页模式
 */
export async function isSinglePageType(entity: string): Promise<boolean> {
  try {
    const url = `/api/data/PageType/${encodeURIComponent(entity)}`
    const res = await axios.get(url, { 
      headers: get_session_api_headers(), 
      withCredentials: true 
    })
    
    const data = res.data?.data
    // 检查 issingle 字段，如果为 1 或 true 则认为是单页模式
    return Boolean(data?.issingle === 1 || data?.issingle === true)
  } catch (error) {
    console.error('Failed to check single page type:', error)
    return false
  }
}

/**
 * 根据 pagetype 是否为单页模式返回对应的路由名称
 * @param entity pagetype 名称
 * @returns Promise<string> 路由名称
 */
export async function getPageTypeRouteName(entity: string): Promise<string> {
  const isSingle = await isSinglePageType(entity)
  return isSingle ? 'SinglePageDetail' : 'PageTypeList'
}

/**
 * 获取单页 pagetype 数据
 * @param pagetype pagetype 名称
 * @returns Promise<{ success: boolean; data?: any; message?: string }> 返回结果
 */
export async function getSinglePageData(pagetype: string): Promise<{ success: boolean; data?: any; message?: string }> {
  try {
    const url = `/api/action/jingrow.client.get_single`
    const res = await axios.get(url, { 
      params: { 
        pagetype: pagetype
      },
      headers: get_session_api_headers(), 
      withCredentials: true 
    })
    
    if (res.data?.message) {
      return {
        success: true,
        data: res.data.message
      }
    } else {
      return {
        success: true,
        data: {}
      }
    }
  } catch (error: any) {
    console.error('Failed to get single page data:', error)
    return {
      success: false,
      message: error.response?.data?.message || error.message || '获取单页数据失败'
    }
  }
}

/**
 * 保存单页 pagetype 数据
 * @param pagetype pagetype 名称
 * @param data 要保存的数据
 * @returns Promise<{ success: boolean; message?: string }> 返回结果
 */
export async function saveSinglePageData(pagetype: string, data: any): Promise<{ success: boolean; message?: string }> {
  try {
    const url = `/api/action/jingrow.client.save_single`
    await axios.post(url, {
      pagetype: pagetype,
      data: data
    }, { 
      headers: get_session_api_headers(), 
      withCredentials: true 
    })
    
    return {
      success: true
    }
  } catch (error: any) {
    console.error('Failed to save single page data:', error)
    return {
      success: false,
      message: error.response?.data?.message || error.message || '保存单页数据失败'
    }
  }
}
