import axiosApi from '@/utils/axios.js'



// 根据分组ID获取Markdown文件列表
export const groupingId = (groupingId) => axiosApi.get(`/api/markdown/grouping/${encodeURIComponent(groupingId)}`)
// 获取所有分组
export const groupingAll = (data) => {
    if (data) {
        return axiosApi.get(`/api/groupings?parentId=${encodeURIComponent(data)}`);
    }
    return axiosApi.get('/api/groupings');
};
// 获取所有Markdown文件
export const markdownAll = () => axiosApi.get(`/api/markdown`);
// 预览markdown文件
export const Preview = (id) => axiosApi.get(`/api/markdown/${id}`);

// 分块加载markdown文件内容（用于大文件）
export const PreviewChunk = (id, chunkIndex = 0, chunkSize = 10000) => 
    axiosApi.get(`/api/markdown/${id}/chunk?chunkIndex=${chunkIndex}&chunkSize=${chunkSize}`);

// 创建分类分组
export const addGroupings = (group) => {
    return axiosApi.post('/api/groupings', group);
}
//更新Markdown文件
export const  updateMarkdown = (data) => {
    return axiosApi.post(`/api/markdown/updateMarkdown`, data)
}
// 批量删除图片
// 修复：后端接收 JSON 数组，不是 FormData
export const deleteImages = (list) => {
    return axiosApi.post('/api/images/batch', list)
}
// 上传图片
// 修复：移除 userId 参数，后端从 SecurityContext 获取当前用户
export const uploadImage = (file, markdownId) => {
    const formData = new FormData()
    if (file) formData.append('file', file)
    if (markdownId) formData.append('markdownId', markdownId)
    return axiosApi.post('/api/images', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
}

// 删除Markdown文件
export const deleteMarkdown = (id) => axiosApi.delete(`/api/markdown/${id}`);
// 根据分组ID获取Markdown文件列表
export const markdownList = (groupingId) => axiosApi.get(`/api/markdown/grouping/${groupingId}`);

// 登录
export const login = (data) => {
    const formData = new FormData()
    formData.append('username', data.username)
    formData.append('password', data.password)
    return axiosApi.post('/api/user/login', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
}

// 搜索
export const searchMarkdown = (keyword) => {
    const params = new URLSearchParams();
    params.append('keyword', keyword);
    return axiosApi.get(`/api/markdown/search?${params.toString()}`);
};

// 注册
export const register = (data) => {
    const formData = new FormData()
    formData.append('username', data.username)
    formData.append('password', data.password)
    formData.append('email', data.email || '')  // 修复：添加 email 参数
    formData.append('registrationCode', data.registrationCode)
    return axiosApi.post('/api/user/register', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
}

// 更新分组名称
// 修复：使用与后端 Grouping 实体类匹配的字段名
export const updateGroupingName = (id, newName) => {
    return axiosApi.put(`/api/groupings/${id}`, { grouping: newName });
}

// 删除分组
export const deleteGrouping = (id) => axiosApi.delete(`/api/groupings/${id}`);

// 更新Markdown文件标题
export const updateMarkdownTitle = (id, newName) => {
    const formData = new FormData()
    if (newName) formData.append('title', newName)
    return axiosApi.post(`/api/markdown/${id}/title`,formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });
}

// 获取最近更新的笔记
export const getRecentFiles = (limit = 16) => axiosApi.get(`/api/markdown/recent?limit=${limit}`);











// 获取回收站内容
export const getTrash = () => axiosApi.get('/api/trash');

// 恢复项目
export const restoreTrashItem = (id, type) => axiosApi.post(`/api/trash/restore/${type}/${id}`);

// 验证Token
export const validateToken = () => axiosApi.post('/api/user/validate-token');

// System APIs
export const getRegistrationStatus = () => {
    return axiosApi.get('/api/system/registration/status');
};

export const toggleRegistration = (enabled) => {
    return axiosApi.post('/api/system/registration/toggle', enabled, {
        headers: {
            'Content-Type': 'application/json'
        }
    });
};

export const generateRegistrationCode = () => {
    return axiosApi.post('/api/system/registration/generate-code');
};

// 获取验证码
export const getCaptcha = () => {
  return axiosApi.get('/api/captcha/generate');
};

// 更新密码（需要验证码）
export const updatePassword = (data, captchaId, captchaCode) => {
  return axiosApi.put('/api/user/password', data, {
    headers: {
      'X-Captcha-Id': captchaId,
      'X-Captcha-Code': captchaCode
    }
  });
};

// 删除当前用户（需要验证码）
export const deleteUser = (captchaId, captchaCode) => {
  return axiosApi.delete('/api/user/deleteUser', {
    headers: {
      'X-Captcha-Id': captchaId,
      'X-Captcha-Code': captchaCode
    }
  });
};

// 永久删除回收站项目（需要验证码）
export const permanentlyDeleteItem = (id, type, captchaId, captchaCode) => {
  return axiosApi.delete(`/api/trash/permanently/${type}/${id}`, {
    headers: {
      'X-Captcha-Id': captchaId,
      'X-Captcha-Code': captchaCode
    }
  });
};

// 清空回收站（需要验证码）
export const cleanTrash = (captchaId, captchaCode) => {
  return axiosApi.delete('/api/trash/clean', {
    headers: {
      'X-Captcha-Id': captchaId,
      'X-Captcha-Code': captchaCode
    }
  });
};
