import axios from 'axios'

const Axios = axios.create({
  timeout: 60000,
  responseType: 'json',
  withCredentials: true,
  queryData: {},
  urlData: {},
  headers: {
    'Content-Type': 'multipart/form-data'
  }
})
export default function request(config) {
  return new Promise((resolve, reject) => {
    const { query, data, ...conf } = config;
    const params = query;
    const formHead = { 'content-type': "multipart/form-data;charset=UTF-8" }
    const fmtData = new FormData()

    if (data) {
      Object.keys(data).forEach((k) => {
        const val = data[k]

        if (Array.isArray(val)) {
          val.forEach((v) => {
            fmtData.append(k, v)
          })
        } else {
          fmtData.append(k, val)
        }
      })
    }
    Axios({
      params,
      data: !data ? undefined : fmtData,
      headers: {
        ...formHead
      },
      ...conf,
      withCredentials: true,
    }).then((response) => {
      const data = response.data;
      if (data.code === 200) {
        resolve(data.result);
      } else {
        reject('请求数据失败');
      }
    }).catch((error) => {
      reject(error.message);
    });
  });
}