var t = require("util.js");
var md5 = require("md5.min.js");
var setting = require("../setting.js");
var ut=t;

module.exports = {
  uniqueId: "",
  // i: url
  // e: method
  // s: data
  // a: header
  request: function (e, i, o, delay = 1000) {

    var arr_in_url=t.getParams(i);
    this.check_timeout(i, delay, () => {
      var n = this, a = o.header ? o.header : {
        "content-type": "application/x-www-form-urlencoded"
        //"content-type": "application/texts"         
      };

      //-- 获取一下token --
      this.ck_api_token((api_tk)=>{

        console.log("--- api_tk ---");
        var dd= t.deep_cp(o.data);
        var new_data={...arr_in_url,...dd};

        var now=t.gettimestamp();
        var tk=this.set_req_sign(new_data,i,now,api_tk);
        if(tk){
           a.reqtime=now;
           a.token=tk;
           a.ukey=api_tk.userkey
        }

        var s = "GET" != (e = e.toUpperCase()) && o.data ? t.json2Form(o.data) : o.data;
        i = this.modifyUrl(i, o),
        o.isShowLoading && this.showLoading();

        var req = wx.request(Object.assign({}, o, {
          url: i,
          method: e,
          data: s,
          header: a,
          success: function (t) {
            o.isShowLoading && n.hideLoading(), n.doSuccess(o, t);
          },
          fail(err) {
            o.isShowLoading && n.hideLoading();
            if (err && err.errMsg && err.errMsg.indexOf('timeout') != -1) {
              getApp().globalData.fail_url.set(t.gettimestamp(), i);
              console.log('请求超时url---', getApp().globalData.fail_url);
              n.doTimeOut(o, t);
            } else {
              n.doFail(o, t);
            }
          }
        }));
        return req;
      })


    })
  },

  get: function (t, e) {
    console.log(t, e);
    return this.request("GET", t, e);
  },
  post: function (t, e) {
    this.request("POST", t, e);
  },
  delete: function (t, e) {
    this.request("DELETE", t, e);
  },
  put: function (t, e) {
    this.request("PUT", t, e);
  },


  uploadFile: function (t, e) {
    var i = this;
    t = this.modifyUrl(t, e),
      // console.log("app.request", t, e), 
      e.isShowLoading = void 0 === e.isShowLoading || e.isShowLoading,
      e.isShowLoading && this.showLoading(), wx.uploadFile(Object.assign({}, e, {
        url: t,
        filePath: e.filePath,
        name: e.name,
        success: function (t) {
          i.hideLoading();
          if (t.statusCode == 200)
            t.data = JSON.parse(i.filterJsonData(t.data));
          else { t = { code: -1, msg: '调用接口失败' }; }
          i.doSuccess(e, t);
        },
        fail: function (t) {
          i.hideLoading(), i.doFail(e, t);
        }
      }));
  },

  doSuccess: function (t, e) {
    if (console.log("app.request", e), 1 != t.successReload) {
      if (200 != e.statusCode) return this.showError("请求出错[" + e.statusCode + "]", t),
        !1;

      if (e.data.status != undefined) {
        if (1 != e.data.status) {
          if ("function" == typeof t.failStatus && 0 == t.failStatus(e)) return !1;
          if (-100 == e.data.status || -101 == e.data.status || -102 == e.data.status) {
            var i = getApp();
            return i.auth.clearAuth(), i.showWarning("正在重新登录", function () {
              var t = getCurrentPages();
              "pages/user/index/index" != t[t.length - 1].route ? wx.navigateTo({
                url: "/pages/user/index/index"
              }) : wx.navigateTo({
                url: "/pages/index/index/index"
              });
            }, null, !0), !1;
          }
          var o = "string" == typeof e.data.msg ? e.data.msg : "数据格式错误";
          return this.showError(o, t), !1;
        }
      }
      "function" == typeof t.success && t.success(e);
    } else "function" == typeof t.success && t.success(e);
  },
  doTimeOut(t, e) {
    if (console.log("app.request", e), "function" == typeof t.fail && 0 == t.fail(e)) return !1;
    this.showError("请求超时", t);
  },
  doFail: function (t, e) {
    if (console.log("app.request", e), "function" == typeof t.fail && 0 == t.fail(e)) return !1;
    this.showError("请求失败", t);
  },
  filterJsonData: function (t) {
    for (var e = t, i = 0; i < t.length && (e = t.substr(i), "{" != t.charAt(i)); i++);
    return e;
  },
  modifyUrl: function (t, e) {
    if (void 0 === e && (e = {}), 0 != t.indexOf("http") && ("string" == typeof e.baseUrl ? t = e.baseUrl + t : void 0 === e.baseUrl && (t = getApp().globalData.setting.url + t)),
      "boolean" == typeof e.notAuthParam && 1 == e.notAuthParam) return t;
    //var i = "is_json=1&unique_id=" + this.getUniqueId() + "&token=" + this.getToken();
    return t += (t.indexOf("?") > 0 ? "&" : "?");// + i;
  },

  modifyUrl2: function (t, e) {
    if (void 0 === e && (e = {}), 0 != t.indexOf("http") && ("string" == typeof e.baseUrl ? t = e.baseUrl + t : void 0 === e.baseUrl && (t = getApp().globalData.setting.hurl + t)),
      "boolean" == typeof e.notAuthParam && 1 == e.notAuthParam) return t;
    //var i = "is_json=1&unique_id=" + this.getUniqueId() + "&token=" + this.getToken();
    return t += (t.indexOf("?") > 0 ? "&" : "?");// + i;
  },


  getToken: function () {
    var t = getApp();
    return null == t.globalData.userInfo ? "" : t.globalData.userInfo.token;
  },
  getUniqueId: function () {
    return this.uniqueId ? this.uniqueId : (this.uniqueId = "miniapp" + t.randomString(17),
      this.uniqueId);
  },
  showLoading: function () {
    wx.showLoading({
      title: "加载中",
      mask: true,
    });
  },
  hideLoading: function () {
    wx.hideLoading();
  },
  showError: function (t, e) {
    wx.showModal({
      title: t,
      showCancel: !1,
      complete: function () {
        1 == e.failRollback && wx.navigateBack();
      }
    });
  },

  
  request2: function (e, i, o) {

    var n = this, a = o.header ? o.header : {
      "content-type": "application/x-www-form-urlencoded"
    }, s = "GET" != (e = e.toUpperCase()) && o.data ? t.json2Form(o.data) : o.data;

    //-- 获取一下token --
    this.ck_api_token((api_tk)=> {

        var dd= t.deep_cp(o.data);
        var now=t.gettimestamp();
        var tk=this.set_req_sign(dd,i,now,api_tk);
        if(tk){
          a.reqtime=now;
          a.token=tk;
          a.ukey=api_tk.userkey
        }

        i = this.modifyUrl2(i, o), o.isShowLoading = void 0 === o.isShowLoading || o.isShowLoading,
        o.isShowLoading && this.showLoading(), console.log("app.request", i, o), wx.request(Object.assign({}, o, {
          url: i,
          method: e,
          data: s,
          header: a,
          success: function (t) {
            o.isShowLoading && n.hideLoading(), n.doSuccess2(o, t);
          },
          fail: function (t) {
            o.isShowLoading && n.hideLoading(), n.doFail(o, t);
          }
        }));
    })
  },

  get2: function (t, e) {
    this.request2("GET", t, e);
  },
  doSuccess2: function (t, e) {
    if (console.log("app.request", e), 1 != t.successReload) {
      if (200 != e.statusCode) return this.showError("请求出错[" + e.statusCode + "]", t),
        !1;
      if (0 != e.data.code) {
        if ("function" == typeof t.failStatus && 0 == t.failStatus(e)) return !1;
        var o = "string" == typeof e.data.msg ? e.data.msg : "数据格式错误";
        return this.showError(o, t), !1;
      }
      "function" == typeof t.success && t.success(e);
    } else "function" == typeof t.success && t.success(e);
  },

  check_timeout(url, delay, func) {
    let now = t.gettimestamp();
    let fail_url = getApp().globalData.fail_url;
    if (fail_url.size > 0) {
      try {
        fail_url.forEach((value, key) => {
          if (value.indexOf(url) > 0 || value === url) {
            if (now - key <= delay) {
              throw new Error('请求超时');
            } else {
              fail_url.delete(key);
            }
          }
        })
      } catch (error) {
        if (error) {
          return false;
        }
      }
    }
    typeof func === "function" && func()
  },

  
  //---promise的使用get----
  promiseGet: function (url, data, delay = 10000) {

    var th = this;

    return new Promise((resolve, reject) => {
      this.check_timeout(url, delay, () => {
        //-- 获取一下token --
        this.ck_api_token((api_tk)=> {

          if (url.indexOf("http") == -1) url = getApp().globalData.setting.url + url;
          data.isShowLoading && th.showLoading();

          var url1=url;
          var arr_in_url=t.getParams(url1);

          var header={"content-type": "application/x-www-form-urlencoded"};
          var now = t.gettimestamp();

          var new_data={...arr_in_url,...data.data};
          var tk = this.set_req_sign(new_data, url1, now, api_tk);

          if (tk) {
            header.reqtime = now;
            header.token = tk;
            header.ukey = api_tk.userkey
          }

          wx.request({
            url,
            method: 'GET',
            header: header,
            data: data.data,
            success(res) {
              data.isShowLoading && th.hideLoading();
              resolve(res);
            },
            fail(err) {
              data.isShowLoading && th.hideLoading();
              if (err && err.errMsg && err.errMsg.indexOf('timeout') != -1) {
                getApp().globalData.fail_url.set(t.gettimestamp(), url);
                console.log('请求超时url---', getApp().globalData.fail_url);
                th.doTimeOut()
              } else {
                reject(err);
              }
            }
          })

        })
      })
    })
  },
  //---promise的使用get----
  promiseGetNodef: function (url, data, delay = 10000) {
    var url1=url;
    var arr_in_url=t.getParams(url1);
    return new Promise((resolve, reject) => {
      this.check_timeout(url, delay, () => {

        //-- 获取一下token --
        this.ck_api_token((api_tk)=> {

          var th = this;
          if (url.indexOf("http") == -1) url = getApp().globalData.setting.url + url;
          data.isShowLoading && th.showLoading();

          var header = {"content-type": "application/x-www-form-urlencoded"};
          var now = t.gettimestamp();

          var new_data={...arr_in_url,...data.data};
          var tk = this.set_req_sign(new_data, url1, now, api_tk);

          if (tk) {
            header.reqtime = now;
            header.token = tk;
            header.ukey = api_tk.userkey
          }

          wx.request({
            url,
            method: 'GET',
            header: header,
            data: data.data,
            success(res) {
              data.isShowLoading && th.hideLoading();
              resolve(res);
            },
            fail(err) {
              data.isShowLoading && th.hideLoading();
              if (err && err.errMsg && err.errMsg.indexOf('timeout') != -1) {
                getApp().globalData.fail_url.set(t.gettimestamp(), url);
                console.log('请求超时url---', getApp().globalData.fail_url);
                th.doTimeOut()
              } else {
                reject(err);
              }
            }
          })

        })
      })
    })
  },

  //---promise的使用post----
  promisePost: function (url, data) {
    var th = this;
    var url1=url;

    var arr_in_url=t.getParams(url1);

    if (url.indexOf("http") == -1) url = getApp().globalData.setting.url + url;
    var post_data = data.data;

    return new Promise((resolve, reject) => {

        //-- 获取一下token --
        this.ck_api_token((api_tk)=> {

            var header = { "content-type": "application/x-www-form-urlencoded" };
            var now = t.gettimestamp();

            var new_data=null;
            if(!Array.isArray(post_data)) {
              //-- 拼接连接中带有的参数 --
              new_data = {...arr_in_url, ...post_data};
            }else{
              new_data=post_data
            }

            var tk = this.set_req_sign(new_data, url1, now, api_tk);

            if (data.is_json) {
                header = { 'content-type': 'application/json' };
                tk = this.set_req_sign(new_data, url1, now, api_tk,1);
                post_data = JSON.stringify(post_data);
            };

            if (tk) {
              header.reqtime = now;
              header.token = tk;
              header.ukey = api_tk.userkey
            }

            data.isShowLoading && th.showLoading();
            wx.request({
              url,
              method: 'POST',
              header: header,
              data: post_data,
              success(res) {
                data.isShowLoading && th.hideLoading();
                resolve(res);
              },
              fail(err) { data.isShowLoading && th.hideLoading(); reject(err); }
            })
        })

    })
  },
  //---promise的使用post----
  promisePostNodef: function (url, data) {
    var th = this;
    var url1=url;
    var arr_in_url=t.getParams(url1);

    if (url.indexOf("http") == -1) url = getApp().globalData.setting.url + url;

    return new Promise((resolve, reject) => {

        //-- 获取一下token --
        this.ck_api_token((api_tk)=> {
          var post_data = data.data;
          var header = { "content-type": "application/x-www-form-urlencoded" };

          var now = t.gettimestamp();

          //-- 拼接连接中带有的参数 --
          var new_data={...arr_in_url,...post_data};

          var tk = this.set_req_sign(new_data, url1, now, api_tk);

          if (data.is_json) {
            header = { 'content-type': 'application/json' };
            tk = this.set_req_sign(new_data, url1, now, api_tk,1);
            post_data = JSON.stringify(post_data);
          };

          if (tk) {
            header.reqtime = now;
            header.token = tk;
            header.ukey = api_tk.userkey
          }

          data.isShowLoading && th.showLoading();
          wx.request({
            url,
            method: 'POST',
            header: header,
            data: post_data,
            success(res) {
              data.isShowLoading && th.hideLoading();
              resolve(res);
            },
            fail(err) { data.isShowLoading && th.hideLoading(); reject(err); }
          })
        })

    })
  },

  //---promise的使用delete----
  promiseDelete: function (url, data) {
    var th = this;
    var url1=url;
    var arr_in_url=t.getParams(url1);


    if (url.indexOf("http") == -1) url = getApp().globalData.setting.url + url;
    return new Promise((resolve, reject) => {
      data.isShowLoading && th.showLoading();

        //-- 获取一下token --
        this.ck_api_token((api_tk)=> {

          var header={"content-type": "application/x-www-form-urlencoded"};
          var now = t.gettimestamp();

          //-- 拼接连接中带有的参数 --
          var new_data={...arr_in_url,...data.data};

          var tk = this.set_req_sign(new_data, url1, now, api_tk);
          if (tk) {
            header.reqtime = now;
            header.token = tk;
            header.ukey = api_tk.userkey
          }

          wx.request({
            url,
            method: 'DELETE',
            header: header,
            data: data.data,
            success(res) {
              data.isShowLoading && th.hideLoading();
              resolve(res);
            },
            fail(err) {
              data.isShowLoading && th.hideLoading();
              reject(err);
            }
          })

        })
    })
  },


  //---promise的使用put----
  promisePut: function (url, data) {
    var th = this;
    var url1=url;

    var arr_in_url=t.getParams(url1);

    if (url.indexOf("http") == -1) url = getApp().globalData.setting.url + url;
    var post_data = data.data;


        var y_post_data=t.deep_cp(post_data);
        if(!Array.isArray(post_data)) {
          y_post_data = {...arr_in_url, ...y_post_data};
        }

        return new Promise((resolve, reject) => {

              //-- 获取一下token --
              this.ck_api_token((api_tk)=> {

                var header = {"content-type": "application/x-www-form-urlencoded"};
                var now = t.gettimestamp();
                var tk = this.set_req_sign(y_post_data, url1, now, api_tk);

                if (data.is_json) {
                  header = {'content-type': 'application/json'};
                  tk = this.set_req_sign(y_post_data, url1, now, api_tk, 1);
                  post_data = JSON.stringify(post_data);
                }

                if (tk) {
                  header.reqtime = now;
                  header.token = tk;
                  header.ukey = api_tk.userkey
                }

                data.isShowLoading && th.showLoading();
                wx.request({
                  url,
                  method: 'PUT',
                  header: header,
                  data: post_data,
                  success(res) {
                    data.isShowLoading && th.hideLoading();
                    resolve(res);
                  },
                  fail(err) {
                    data.isShowLoading && th.hideLoading();
                    reject(err);
                  }
                })
              })
        })

  },

  //--------具有时间限制的读取接口----------
  time_limit_get(time, url, data) {
    var req = this.get(url, data);
    setTimeout(function () {
      if (req) req.abort();
    }, time * 1000)
  },

  /**
   * @param {Object} url    //url地址
   * @param {Object} data   //data入参
   * @param {Object} succ   //成功的回调
   * @param {Object} fail   //失败的回调
   */
  json_post: function (url, data, succ, fail, mathod) {
    var th = this;
    var Mathod = "POST";

    var url1=url;
    var arr_in_url=t.getParams(url1);

    if (mathod) Mathod = mathod;
    this.showLoading();
    if (url.indexOf("http") == -1) url = getApp().globalData.setting.url + url;

    //-- 获取一下token --
    this.ck_api_token((api_tk)=> {

      var header={
        'content-type': 'application/json'
      };

      var dd= t.deep_cp(data);
      if(!Array.isArray(data)) {
        dd = {...arr_in_url, ...dd};
      }

      var now=t.gettimestamp();
      var tk=this.set_req_sign(dd,url1,now,api_tk,1);
      if(tk){
        header.reqtime=now;
        header.token=tk;
        header.ukey=api_tk.userkey
      }

      var str = JSON.stringify(data);
      wx.request({
        url: url,
        data: str,
        method: Mathod,
        header: header,// 设置请求的 header
        success: function (res) {
          succ(res);
          th.hideLoading();
        },
        fail: function (res) {
          fail(res);
        }
      })
    })
  },
  


  promise_downimg(url) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: url,
        success: function (res) {
          //res.path是网络图片的本地地址
          resolve(res.path);
        },
        fail: function (err) {
          reject(err);
        }
      });
    })
  },

  //判断有没有获取到api_token
  ck_api_token(func){
    var api_token = wx.getStorageSync('api_token');
    var api_token_time = wx.getStorageSync('api_token_time');
    //token有存在本地的时候
    if(api_token){
      //判断有没有超出token的时间，超出的话就要重头拿token
      var now=t.formar_day();
      if(now!=api_token_time){
          //调用接口获取token
          getApp().get_api_token(func);
          return false;
      }
      func(api_token);
      return  false;
    }
    getApp().get_api_token(func);
  },

  //接口加密过程
  set_req_sign(data,url,now,api_tk,is_json){
    if(!url) return '';
    var name2=url.split('?')[0];
    if(!name2) return '';

    //确保不要有前缀
    name2=name2.replace(setting.url,'')

    if(!now) now=t.gettimestamp();
    if(!api_tk){
      api_tk=wx.getStorageSync('api_token');
    }
    var userkey = api_tk;
    var token2="";

    if(data && Object.keys(data).length>0) {

      for(var i in data){
        var item=data[i];
        if (typeof item === 'string') {
          try {
            data[i]=decodeURIComponent(item); //urldecode
          }catch (err) {

          }
        }
      }

      var req4 ='';
      if(is_json){
        req4 = JSON.stringify(data);
      }else {
        // 自定义序列化函数
        function stringifyReplacer(key, value) {
          if (typeof value === 'number') {
            return String(value);
          }
          return value;
        }
        req4 = JSON.stringify(data, stringifyReplacer);
      }
      //console.log(req4+':---token0');
      token2 = md5(req4).toUpperCase();
      //console.log(name2+':---token1:'+token2);
    }
    var str=name2.toUpperCase()+token2+now+userkey.token+setting.environment_key;
    //console.log('---tk_str:'+str);
    var tk = md5(str).toUpperCase();
    return tk;
  }


};