import axios from 'axios'
import {showDialog, showToast} from 'vant'
import store from '../store/index'

const baseURL = import.meta.env.VITE_BASE_URL
const service = axios.create({
  baseURL: baseURL,
  withCredentials: true,
  timeout: 0,
})

service.interceptors.request.use(
  (config) => {
    config.headers['token'] = localStorage.getItem('token')
    store.commit('SET_LOADING', true);
    return config
  },
  (error) => {
    store.commit('SET_LOADING', false)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    store.commit('SET_LOADING', false)
    if (response.data.code === 200) {
      return response.data.data
    }
    if (response.data.code === 0) {
      return response.data
    }
    if (response.data.code > 1000 && response.data.code < 2000) {
      showToast({
        message: response.data.message,
        position: 'top',
      });
    } else if (response.data.code > 2000 && response.data.code < 3000) {
      showDialog({
        title: '提示',
        message: response.data.message,
      }).then(() => {
      })
    } else if (response.data.code > 3000 && response.data.code < 4000) {
      showDialog({
        title: '提示',
        message: response.data.message,
      }).then(() => {
        WeixinJSBridge.call('closeWindow')
      })
    }
    return Promise.reject(new Error(response.data.message || '服务器内部错误'));
  },
  (error) => {
    store.commit('SET_LOADING', false)
    showToast({
      message: error.toString(),
      position: 'top',
    });
    return Promise.reject(error)
  }
)

export default service

export function fetchInspectionReportImage(data) {
  store.commit('SET_LOADING', true);
  return new Promise((resolve, reject) => {
    axios({
      url: baseURL + '/inspections/fetchReportImage',
      method: 'post',
      data: data,
      headers: {'token': localStorage.getItem('token')},
      contentType: 'image/JPEG',
      responseType: 'blob',
    }).then(response => {
      const blob = new Blob(
        [response.data],
        {type: response.headers['content-type']}
      );
      resolve(URL.createObjectURL(blob))
    }).catch(() => {
      reject("请求失败，请稍后再试。");
    }).finally(() => {
      store.commit('SET_LOADING', false);
    })
  })
}