import { getSystemInfoAsync } from '@/utils/system';
import store from '@/store';

const BASE_URL = 'https://test.api.chelvc.com';
const TIME_OUT = 60000;
const errStatus = {
  200: '成功',
  400: '请求参数异常',
  401: '用户认证失败，需要用户重新认证',
  403: '用户无访问权限',
  404: '访问的目标资源不存在',
  405: '请求方式不支持',
  406: '接口参数传递方式不支持',
  410: '用户令牌已被重置，需要用户重新登录',
  412: '参数校验异常，具体格式请查看响应参数格式',
  415: '接口媒体类型不支持',
  500: '服务端异常',
};

export function request(options) {
  uni.showLoading({
    title: options.loadingText || '加载中...',
  });
  return new Promise(async (resolve, reject) => {
    const { deviceId, osName, osVersion } = await getSystemInfoAsync();
    const access_token = store.getters.access_token;
    return uni.request({
      timeout: TIME_OUT,
      url: BASE_URL + options.url,
      method: options.method.toUpperCase() || 'GET',
      data: options.data,
      header: Object.assign(
        {},
        {
          Authorization: `Bearer ${access_token}`,
          'Content-Type': 'application/json; charset=utf-8',
          client_id: 'chelvc_client',
          client_secret: 'qWBe6jD%GCuPPTkP',
          grant_type: 'wechat',
          Device: deviceId,
          Platform: osName.toUpperCase(),
          Version: osVersion,
          Terminal: 'APPLET',
          Business: 'CUSTOMER',
          Initial: false,
        },
        options.header,
      ),
      success: res => {
        if (res.statusCode !== 200) {
          uni.showToast({
            icon: 'none',
            title: res.data.message || errStatus[res.statusCode],
            duration: 2000,
          });
          reject(res);
        } else {
          resolve(res.data);
        }
      },
      fail: err => {
        console.log('fail:err', err);
        if (err.errMsg.includes('timeout')) {
          uni.showToast({
            icon: 'none',
            title: '网络连接超时,请检查您的网络',
            duration: 2000,
          });
        }
        reject(err);
      },
      complete: () => {
        uni.hideLoading();
      },
    });
  });
}

/**
 * 文件上传
 * @param {string} filePath 文件路径
 * @returns
 */
export async function uploadFile(filePath) {
  const { deviceId, osName, osVersion } = await getSystemInfoAsync();
  const access_token = store.getters.access_token;
  uni.showLoading({
    title: '正在上传...'
  })
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: BASE_URL + '/maintain/file',
      filePath: filePath,
      name: 'file',
      header: {
        Authorization: `Bearer ${access_token}`,
        'Content-Type': 'application/json; charset=utf-8',
        client_id: 'chelvc_client',
        client_secret: 'qWBe6jD%GCuPPTkP',
        grant_type: 'wechat',
        Device: deviceId,
        Platform: osName.toUpperCase(),
        Version: osVersion,
        Terminal: 'APPLET',
        Business: 'CUSTOMER',
      },
      success: res => {
        resolve(res.data);
      },
      fail: err => {
        reject(err);
      },
      complete:()=>{
        uni.hideLoading()
      }
    });
  });
}
