import Taro from '@tarojs/taro';
import { getToken, setToken } from './token';
import logger from './log';

const getQueryStrByParams = params => {
  if (!params) return undefined;

  return Object.keys(params).map(key => {
    const value = params[key];
    return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
  }).join('&')
}

export default function request(api, options = {}) {
  return new Promise((resolve, reject) => {
    const { method = 'GET', params, data = {}, header = {}, silent = false, noSuccesTip, ...cfgs } = options;
    const queryStr = params ? getQueryStrByParams(params) : undefined;
    // eslint-disable-next-line no-undef
    const url = queryStr ? `${HOST}${api}?${queryStr}` : `${HOST}${api}`;
    const personId = Taro.getStorageSync('personId');
    const duty = Taro.getStorageSync('duty');
    
    const onError = (err) => {
      console.error(err);
      logger.error(`接口 [${method}]: ${url}`);
      logger.error('参数: ', data);
      logger.error(err);

      if (!silent && 'GET' !== method.toUpperCase()) {
        Taro.showModal({
          title: err.message || err,
          showCancel: false,
        })
      }

      reject(err);
    };

    Taro.request({
      url,
      data,
      method,
      header: {
        'x-client': 'miniapp',
        'x-personId': personId,
        'x-duty': duty,
        'content-type': 'application/json',
        'authorization': getToken(),
        ...header,
      },
      ...cfgs,
    }).then(({ statusCode, header, data = result }) => {
      if (statusCode >= 300) {
        logger.error(header);
        return onError(`网络错误 ${statusCode}`);
      }

      if (data.code === 1000) {
        if (data.data?.token) {
          setToken(data.data.token);
        }

        if (!silent && 'GET' !== method.toUpperCase()) {
          if (!noSuccesTip) {
            Taro.showToast({
              title: '操作成功',
              icon: 'none',
            })
          }
        }

        resolve(data.data);
      } else {
        onError(data);
      }
    }).catch(onError);

  });
}


export const uploadFiles = async (files, url) => {
  const uploads = []
  const token = getToken();
  for (var i = 0; i < files.length; i++) {
    uploads[i] = new Promise((resolve, reject) => {
      Taro.uploadFile({
        // eslint-disable-next-line no-undef
        url: url || `${HOST}/api/ma/file`,
        filePath: files[i].tempFilePath,
        header: {
          'authorization': token,
        },
        name: 'file',
        formData: {
          fileType: files[i].fileType,
        },
        success: function (res) {
          // debugger
          const _data = JSON.parse(res.data)
          // if (_data.code !== CODE_SUCCESS) {
          //   reject(new Error(_data.message))
          // }

          resolve(_data.data)
        },
        fail(err) {
          reject(err)
        }
      })
    })
  }

  return Promise.all(uploads)
}