const openData = {
  url: 'https://mp.wuhanud.com/wx/',
  appid: wx.getAccountInfoSync().miniProgram.appId,
  retryCount: 1
}
const fetchRequest = (path, method, jsonData) => {
  const url = openData.url;
  const token = wx.getStorageSync('ud_token')
  return new Promise((resolve, reject) => {
      wx.request({
      url: `${url}${path}`,
      method: method,
      header: { 'Token': token },
      data: jsonData,
      success: (res) => {
          if (res.statusCode === 200) {
              resolve(res.data);
          } else if(res.statusCode===401) {
              resolve(res.data);
          } else {
              console.error('请求失败：', res);
              reject(new Error('请求失败'));
              // wx.showToast({
              //     title: res.data.msg || '请求失败',
              //     icon: 'none',
              //     duration: 2000,
              // });
          }
      },
      fail: (err) => {
          console.error('网络错误：', err);
          reject(new Error('网络错误'));
          // wx.showToast({
          // title: '网络错误',
          // icon: 'none',
          // duration: 2000,
          // });
      },
      });
  });
};
const wxUpfile = (file,data,type) => {
  var url = openData.url;
  if(type =='avatar')
      url = url+'user/avatar'
  else
      url = url + 'parrot/upload'
  console.log('wxupfile',data)
  const token = wx.getStorageSync('ud_token')
  return new Promise((resolve, reject) => {
      const uploadTask = wx.uploadFile({
          url: url, //接口地址
          name: 'file', //上传文件名
          filePath: file,
          formData: data,
          header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Token': token
          },
          success(res) { //后台返回给前端识别后的文字
              if (res.statusCode === 200) {
                  resolve(JSON.parse(res.data));
              } else if(res.statusCode===401) {
                  resolve(JSON.parse(res.data));
              } else {
                  reject(new Error('请求失败'));
                  wx.showToast({
                      title: res.data.msg || '请求失败',
                      icon: 'none',
                      duration: 2000,
                  });
              }
          },
          fail: (err) => {
              reject(new Error('网络错误'));
              wx.showToast({
              title: '网络错误',
              icon: 'none',
              duration: 2000,
              });
          },
      })
      uploadTask.onProgressUpdate((res) => {
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
      })
  })
}

const noneToken = (callback) => {
  const token = wx.getStorageSync('ud_token');
  if (!token || token.length < 32) {
      setTimeout(() => {
          callback();
      }, 2000);
      return true
  }
  return false
}
const expireDo = (callback) => {
  getOpenid(callback)
}

const getEcho = () => {
  const echodata = wx.getStorageSync("ud_echodata")
  var version = 0
  if(noneToken(getEcho))return
  if(echodata) {
      version = echodata.version
  }
  fetchRequest('echo','GET',{ version:version })
  .then(data => {
      if(data.code==401)expireDo(getEcho)
      if(data.code==200) {
          // if(data.data.version != version){
              wx.setStorageSync('ud_echodata', data.data)
          // }
      }
  })
  .catch(error => {
      console.error('请求出错：', error);
  });
}
const getOpenid = (callback=false) => {
  if (openData.retryCount > 3) {  // 最多重试3次
      // wx.showToast({
      //     title: '网络异常，无法登录',
      //     icon: 'none',
      //     duration: 2000
      // });
      return;
  }
  openData.retryCount += 1
  const deviceinfo = wx.getDeviceInfo()
  //console.log('deviceinfo',deviceinfo)
  wx.login({
      success: res => {
          if (res.code) {
              //这里要改成POST
              fetchRequest('login', 'POST', { appId: openData.appid, code: res.code,platform:deviceinfo.platform,model:deviceinfo.model,brand: deviceinfo.brand})
              .then(data => {
                  wx.setStorageSync('ud_token', data.data.token);
                  wx.setStorageSync('ud_userinfo',data.data.user);
                  openData.retryCount = 1
                  if(callback) {
                      callback()
                  }
              })
              .catch(error => {
                  console.error('请求出错：', error);
                  //openData.retryCount += 1
                  getOpenid(); // 重试
              });
          }
      },
      fail: () => {
          getOpenid(); // 登录失败，重试
      },
  });
}

const getTotal = () =>{
  if(noneToken(getTotal))return
  fetchRequest('total', 'GET')
  .then(data => {
      if(data.code==401){
          expireDo(getTotal)
      }
  })
  .catch(error => {
      console.log('error',error)
  });
}
const carryPage = () => {
  const token = wx.getStorageSync('ud_token');
  
  if (!token || token.length < 32) {
      getOpenid();
  }
  getEcho();
  getTotal()
  const originalPage = Page;
  Page = (pageConfig) => {
      const originalOnShow = pageConfig.onShow;
      pageConfig.onShow = function () {
          if (originalOnShow) {
              originalOnShow.apply(this, arguments);
          }
          getTotal();
      };
      return originalPage(pageConfig);
  };
}
module.exports = {
  fetchRequest: fetchRequest,
  carryPage:carryPage,
  expireDo:expireDo,
  wxUpfile:wxUpfile,
  noneToken:noneToken
}
