import utils from './util'
//testURL
// const BASE_URL = 'http://127.0.0.1:8080/wx';
//devURL
// const BASE_URL = 'https://lmqhznn.goho.co/wx';
//prodURL
const BASE_URL = 'https://www.qnforever.top/wx';
function buildURL(url, needToken) {
  let userId = wx.getStorageSync('userId');
  if (!userId && url != '/user/login') {
    wx.redirectTo({
      url: '../myself/index'
    })
    wx.showToast({
      title: '请先登录',
      mask: true,
      duration: 2000
    })
    return;
  }
  if (url != '/user/login'){
    url = url + (url.indexOf('?') >= 0 ? '&' : '?') + "userId=" + userId
  }
  if (needToken) {
    let token = utils.getToken()
    return token ? url + (url.indexOf('?') >= 0 ? '&' : '?') + "access_token=" + token : url
  }
  return url + (url.indexOf('?') >= 0 ? '&' : '?');
}

export function fetchPost(url, params, needToken, multiple) {
  url = buildURL(url, needToken);
  // 如果url不存在，返回错误
  if (!url) {
    return new Promise((resolve, reject) => {
      reject();
    })
  }
  console.log("网络请求", BASE_URL + url, params);
  // 如果上传图片
  if (multiple) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: BASE_URL + url,
        filePath: params.filePath,
        name: 'image',
        formData: {},
        success: function(response) {
          console.log(response.data);
          let res = JSON.parse(response.data);
          console.log(res);
          if (response.statusCode == 200) {
            if (res.err_code == 0) {
              // wx.hideLoading();
              resolve(res);
            } else {
              if (res.err_code == 10003 || res.err_code == 10006 || res.err_code == 20006) {
                // wx.removeStorageSync('accessToken');
                // wx.redirectTo({
                //   url: '/pages/login/index',
                // })
                isUnLogin();
                reject(res);
                return;
              } else if (res.err_code == 20005) {
                wx.removeStorageSync('accessToken');
                wx.removeStorageSync('history');
                wx.hideLoading();
                wx.showToast({
                  title: res.err_msg,
                  icon: 'none',
                  duration: 2000
                })
                reject(res);
              } else {
                wx.hideLoading();
                wx.showToast({
                  title: res.err_msg,
                  icon: 'none',
                  duration: 2000
                })
                reject(res);
              }
            }
          } else {
            wx.hideLoading();
            wx.showToast({
              title: '网络错误',
              icon: 'none',
            })
            reject(response);
          }
        },
        fail: function(err) {
          console.log(err);
          wx.hideLoading();
          wx.showToast({
            title: '网络错误',
            icon: 'none',
          })
          reject(response);
        },
      })
    })
  }

  // 获取POST数据
  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + url,
      data: params,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function(res) {
        console.log("POST返回数据", url,res);
        if (res.data.err_code == 0) {
          wx.hideLoading();
          resolve(res.data);
        } else {
          if (res.data.err_code == 10003 || res.data.err_code == 10006 || res.data.err_code == 20006) {
            // wx.removeStorageSync('accessToken');
            // wx.redirectTo({
            //   url: '/pages/login/index',
            // })
            reject(res);
            return;
          } else if (res.data.err_code == 30022) {
            reject(res);
          } else if (res.data.err_code == 20005) {
            wx.removeStorageSync('accessToken');
            wx.removeStorageSync('history');
            wx.hideLoading();
            wx.showToast({
              title: res.data.err_msg,
              icon: 'none',
              duration: 2000
            })
            reject(res);
          } else {
            wx.hideLoading();
            wx.showToast({
              title: res.data.err_msg,
              icon: 'none',
              duration: 2000
            })
            reject(res);
          }

        }
      },
      fail: function(res) {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none',
          duration: 2000
        })
        reject(res);

      },
    })
  })
}

// get请求
export function fetchGet(url, params, needToken) {
  url = buildURL(url, needToken);
  // 如果url不存在，返回错误
  if (!url) {
    return new Promise((resolve, reject) => {
      reject();
    })
  }

  console.log("网络请求", BASE_URL + url, params);
  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + url,
      data: params,
      method: 'GET',
      success: function(res) {
        console.log("GET返回数据", url, res);
        if (res.statusCode == 200) {
          if (res.data.err_code == 0) {
            wx.hideLoading();
            resolve(res.data);
          } else {
            if (res.data.err_code == 10003 || res.data.err_code == 10006 || res.data.err_code == 20006) {
              // isUnLogin();
              reject(res);
              return;
            } else if (res.data.err_code == 20005) {
              wx.removeStorageSync('accessToken');
              wx.removeStorageSync('history');
              wx.hideLoading();
              wx.showToast({
                title: res.data.err_msg,
                icon: 'none',
                duration: 2000
              })
              reject(res);
            } else {
              wx.hideLoading();
              wx.showToast({
                title: res.data.err_msg,
                icon: 'none',
                duration: 2000
              })
              reject(res);
            }
          }
        } else {
          wx.hideLoading();
          reject(res)
          wx.showToast({
            title: '网络错误',
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: function(res) {
        wx.hideLoading();
        reject(res)
        wx.showToast({
          title: '网络错误',
          icon: 'none',
          duration: 2000
        })
      },
    })
  })
}

// 暴露接口
export default {

  /**
   * 用户设置
   * @param params
   * @returns {Promise<unknown>}
   */
  loginAccount(params) {
    return fetchPost('/user/login',params,true,false);
  },
  getSetting(params) {
    return fetchPost('/user/setting/' + params,null,true,false);
  },
  editSetting(params) {
    return fetchPost('/user/settings/edit',params,true,false);
  },
  deleteSetting(params) {
    return fetchPost('/user/settings/del/' + params,null,true,false);
  },
  getSettings() {
    // let result;
    // if (type == 'INCOME_SETTING'){
    //   result = wx.getStorageSync('INCOME_SETTING');
    // }
    // if (type == 'EXPEND_SETTING'){
    //   result = wx.getStorageSync('INCOME_SETTING');
    // }
    // if (type == 'ACCOUNT_SETTING'){
    //   result = wx.getStorageSync('INCOME_SETTING');
    // }
    // if (result){
    //   return result;
    // }
    return fetchPost('/user/settings', null, true, false);
  },

  getSettingsExpend(){
    return fetchPost('/user/settings/expend',null,true,false);
  },
  getSettingsIncome(){
    return fetchPost('/user/settings/income',null,true,false);
  },
  editAccount(params){
    return fetchPost('/user/settings/edit/bill',params,true,false);
  },
  /**
   * 账单处理
   */
  listBillsToday() {
    return fetchPost('/user/bills/today', null,true,false);
  },
  listBillByAccount(params){
    return fetchPost('/user/bills/account' ,params,true,false);
  },
  editBill(params) {
    return fetchPost('/user/bill/edit',params,true,false);
  },
  getBill(params) {
    return fetchPost('/user/bill/' + params,null,true,false);
  },
  deleteBill(params) {
    return fetchPost('/user/bill/del/' + params,null,true,false);
  },
}
