// src/api/b1s.js
import axios from 'axios';

// 创建 axios 实例
const tm = axios.create({
  timeout: 100000,
  baseURL: window.dt_Config.baseURLtm,
  headers: {
    'Content-Type': 'application/json'
  }
});


export async function gettm(url, params) {
  try {

    //  const paramsGet = {
    //   func:"GET",
    //   cmd: url.replace('/', ''),
    //   content: new URLSearchParams(params).toString()//.replace('%24', '')
    // }
     const paramsGet = {
      func:"GET",
      cmd: url.replace('/', ''),
      content: JSON.stringify(params)
    }
    const res = await tm.post('',paramsGet);
    return { success: true, data: res.data };
  } catch (error) {
    console.log('GET', error)
    const msg = extractB1Error(error);
    return { success: false, message: msg };
  }
}

export async function posttm(url, data) {
  try {
    const params = {
      func:"POST",
      cmd: url.replace('/', ''),
      content: JSON.stringify(data)
    }
    const res = await tm.post('', params);
    console.log(res)
    return { success: true, data: res.data };
  } catch (error) {
    console.log('POST', error)
    const msg = extractB1Error(error);
    return { success: false, message: msg };
  }
}
export async function patchtm(url, data) {
  try {
 const params = {
      func:"PATCH",
      cmd: url.replace('/', ''),
      content: JSON.stringify(data)
    }
    const res = await tm.post('', params);
    console.log('PATCH 请求成功:', res);
    return { success: true, data: res.data };
  } catch (error) {
    console.log('PATCH', error)
    const msg = extractB1Error(error); // 複用你的錯誤提取函數
    console.error('PATCH 请求失败:', msg);
    return { success: false, message: msg };
  }
}

// src/api/b1s.js 内部定义
function extractB1Error(error) {
  if (!error) return '未知错误';

  // 优先取 SAP B1 返回的错误信息
  if (
    error.response &&
    error.response.data &&
    error.response.data.error
  ) {
    const b1Error = error.response.data.error;
    if (b1Error.message && b1Error.message.value) {
      return b1Error.message.value;
    } else if (typeof b1Error.message === 'string') {
      return b1Error.message;
    } else {
      return b1Error.code || 'SAP B1 错误';
    }
  }

  // 网络错误、超时等
  if (error.message) {
    return error.message;
  }

  return '请求失败，请检查网络或服务状态';
}
