import uni from './uniHooks';
import md5 from 'js-md5';
import CacheTool from '@/utils/cache-tool.js';
import log from './log.js';

function getSign(params) {
  let signStr = '';
  let timeStamp = '10000';
  let password = '123456';
  let key_arr = [];
  for (var key in params) {
    key_arr.push(key);
  }
  let sarr = key_arr.sort();
  sarr.forEach(function (item) {
    if (params[item] === 0 || params[item]) {
      signStr = signStr + params[item] + '&';
    }
  });
  signStr = signStr + password + '&' + timeStamp;
  console.info('===> MD5签名参数: ' + signStr);
  let sign = md5(signStr);
  return {
    'Content-Type': 'application/json; charset=utf-8',
    // #ifdef MP-WEIXIN
    // 'user': 'sys_miniprogram',
    // #endif
    // #ifdef H5
    user: 'sys_gzh',
    // #endif
    timeStamp: timeStamp,
    sign: sign,
  };
}

const CONTENT_TYPE_ARRAY = {
  json: 'application/json',
  form: 'application/x-www-form-urlencoded',
};

function getHeaders(config = {}) {
  const { contentType = 'json' } = config;
  const ct = CONTENT_TYPE_ARRAY[contentType];
  let header = {
    'Content-Type': ct,
  };

  return header;
}

function getUrl(url) {
  if (url.indexOf('http') > -1 || url.indexOf(`/${window.profileApi}`) > -1) {
    return url;
  } else {
    const baseUrl = CacheTool.getCurEnvConst('BASE_URL');
    return baseUrl + url;
  }
}

function handleCrmResponse(resp) {
  if (resp && resp.data) {
    const { status, msg } = resp;
    console.log(`crm request resp => ${msg} ${status}`);
    const result = resp.data;
    if (result) {
      const { code, msg } = result || {};
      console.log(`crm api resul => msg: ${msg} code: ${code}`);
      if (`${code}` !== '0') {
        console.error(`===>接口返回错误: ${JSON.stringify(result)}`);
        if (`${code}` === '3000') {
          uni.navigateTo({
            url: '/pages/automatic/automaticMy.vue',
          });
          return
        }
      }
    }
  }
  return resp.data;
}

export default {
  base(method, path, param = {}, config) {
    return new Promise((resolve, reject) => {
      const url = getUrl(path);
      const baseHeader = getHeaders(config);
      const sign = getSign(param);
      const header = { ...baseHeader, ...sign };
      log.info(`===>request-crm url: ${url}`);
      log.info(`===>request-crm header: ${JSON.stringify(header)}`);
      uni
        .request({
          header: header,
          method: method,
          url: url,
          data: param,
        })
        .then((res) => {
          console.log(9595, res);
          log.info(`===>request-crm response: ${JSON.stringify(res.data)}`);
          resolve(handleCrmResponse(res));
          if (res.status === 581) {
            uni.navigateTo({
              url: '/pages/errorPage/errorLimit?msg=当前访问太火爆了，稍后试试吧~',
            });
          }
        })
        .catch((response) => {
          log.error(`===>request-crm error: ${JSON.stringify(response)}`);
          reject(response);
        });
    });
  },
  get(path, param = {}, config) {
    return this.base('GET', path, param, config);
  },
  post(path, param = {}, config) {
    return this.base('POST', path, param, config);
  },
  put(path, param = {}, config) {
    return this.base('PUT', path, param, config);
  },
  delete(path, param = {}, config) {
    return this.base('DELETE', path, param, config);
  },
  uploadFile(path, param = {}) {
    return new Promise((resolve, reject) => {
      const url = getUrl(path);
      const { fileType, file, formData } = param;
      const header = {
        ...getHeaders(),
        'Content-Type': 'multipart/form-data',
      };
      uni
        .uploadFile({
          header: header,
          method: 'POST',
          url: url,
          name: 'file',
          fileType: fileType,
          filePath: file.path,
          file: file,
          formData: formData,
        })
        .then((res) => {
          resolve(handleCrmResponse(res[1]));
        })
        .catch((response) => {
          reject(response);
        });
    });
  },
};
