import { httpRequest } from '/@/api/sys/api';
import { getToken } from '/@/utils/auth';

export default function () {
  async function changeApiOptions(val) {
    if (val.path) {
      try {
        const headers = { Authorization: `Bearer ${getToken()}` };
        if (val.requestHeaderConfigs.length > 0) {
          val.requestHeaderConfigs.forEach((element) => {
            if (element.name) headers[element.name] = element.value;
          });
        }
        let path = val.path;
        if (val.requestParamsConfigs.length > 0) {
          path += '?';
          val.requestParamsConfigs.forEach((element) => {
            if (element.name) path += `${element.name}=${element.value}&`;
          });
        }
        const apiData = {};
        if (val.requestBodyConfigs.length > 0) {
          val.requestBodyConfigs.forEach((element) => {
            if (element.name) apiData[element.name] = element.value;
          });
        }
        const res = await httpRequest(
          {
            requestUrl: path,
            requestType: val.method,
          },
          {
            headers,
            data: apiData,
          },
        );

        return res;
      } catch (error) {}
    }
  }
  return {
    changeApiOptions,
  };
}
