常用js方法库

import {
  showModal,
  navigateTo,
  paymeng,
  getCode,
  hideLoading,
  downloadFile,
  saveImageToPhotosAlbum,
  getLocation,
  showToast
} from "./public.js";
import {
  config
} from "config.js";
const app = getApp();
//获取当前页面url
export const getUrl = ({
  page
}) => {
  var pages = getCurrentPages() //获取加载的页面
  let currentPage = pages[pages.length - (1 + page)] //获取当前页面的对象
  let url = currentPage.route //当前页面url
  let options = currentPage.options //如果要获取url中所带的参数可以查看options

  //拼接url的参数
  var urlWithArgs = url + '?'
  for (let key in options) {
    let value = options[key]
    urlWithArgs += key + '=' + value + '&'
  }
  urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)

  return urlWithArgs
}
//格式化时间戳:(state 1:年-月-日  时:分:秒  2:年-月-日 3:月-日)
export const formatTimeStamp = (timeStamp, state = 1) => {
  var date = new Date(timeStamp * 1000);
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hour = date.getHours();
  let minute = date.getMinutes();
  let second = date.getSeconds();

  month = month < 10 ? `0${month}` : month;
  day = day < 10 ? `0${day}` : day;
  hour = hour < 10 ? `0${hour}` : hour;
  minute = minute < 10 ? `0${minute}` : minute;
  second = second < 10 ? `0${second}` : second;
  return state == '1' ? `${year}-${month}-${day} ${hour}:${minute}:${second}` : (state == '2' ? `${year}-${month}-${day}` : `${month}-${day}`)
}
//当前时间星期数
export const getWeek = (time) => {
  let day = new Date(time)
  let days = day.getDay()
  switch (days) {
    case 1:
      days = '一';
      break;
    case 2:
      days = '二';
      break;
    case 3:
      days = '三';
      break;
    case 4:
      days = '四';
      break;
    case 5:
      days = '五';
      break;
    case 6:
      days = '六';
      break;
    case 0:
      days = '日';
      break;
  }
  return days
}
//倒计时:
export const countDownPub = (times) => {
  let today = new Date(), //当前时间
    h = today.getHours(),
    m = today.getMinutes(),
    s = today.getSeconds();
  let stopTime = new Date(times),
    stopH = stopTime.getHours(),
    stopM = stopTime.getMinutes(),
    stopS = stopTime.getSeconds();

  let shenyu = stopTime.getTime() - today.getTime();
  let shengyuD = parseInt(shenyu / (60 * 60 * 24 * 1000)),
    D = parseInt(shenyu) - parseInt(shengyuD * 60 * 60 * 24 * 1000),
    shengyuH = parseInt(D / (60 * 60 * 1000)),

  //   var mydata = '2017-01-01 11:00:00';
  // mydata = data.replace(/-/g, '/');

  H = D - shengyuH * 60 * 60 * 1000,
    shengyuM = parseInt(H / (60 * 1000)),
    M = H - shengyuM * 60 * 1000;
  let S = parseInt((shenyu - shengyuD * 60 * 60 * 24 * 1000 - shengyuH * 60 * 60 * 1000 - shengyuM * 60 * 1000) / 1000);
  if (shengyuD > 0) {
    return [shengyuD < 10 ? '0' + shengyuD : shengyuD, shengyuH < 10 ? '0' + shengyuH : shengyuH, shengyuM < 10 ? '0' + shengyuM : shengyuM, S < 10 ? '0' + S : S, shenyu];
  } else {
    return [shengyuH < 10 ? '0' + shengyuH : shengyuH, shengyuM < 10 ? '0' + shengyuM : shengyuM, S < 10 ? '0' + S : S, shenyu];
  }
}
//计算开始时间距离结束时间的天数
//传参为字符串
export const getDays = (startTime, endTime) => {
  let startDate = new Date(startTime)
  let endDate = new Date(endTime)
  let days = (endDate.getTime() - startDate.getTime()) / 1000 / 60 / 60 / 24
  return days
}
//未登录,去登录:
export const goLogin = () => {
  return new Promise((resolve, reject) => {
    let token = wx.getStorageSync("token");
    if (!!token) {
      resolve();
    } else {
      showModal({
        content: '暂未登录,是否去登录?'
      }).then(res => {
        navigateTo({
          url: "/pages/login/login"
        });
      }).catch(res => {
        reject();
      });
    }
  });

}

//定位方法:
export const getBelongsCity = () => {
  return new Promise((resolve, reject) => {
    getLocation().then(res => {
      console.log(res)
      let location = `${res.latitude},${res.longitude}`;
      wx.request({
        url: `${config.api_map}?location=${location}&key=${config.map_keys}`,
        success(res) {
          let city = res.data.result.address_component.city;
          // city = '无锡';
          wx.setStorageSync('city', city);

          resolve(city)
        }
      })
    }).catch(res => {
      reject(res);
    });
  });
}
//去支付:
export const goPayNow = (orderDetail) => {
  return new Promise((resolve, reject) => {
    let weChatPay = orderDetail.weChatPay;
    let params = {
      timeStamp: weChatPay.timeStamp,
      nonceStr: weChatPay.nonceStr,
      package: weChatPay.package,
      signType: weChatPay.signType,
      paySign: weChatPay.paySign,
    }
    paymeng({
      data: params
    }).then(res => {
      showToast('支付成功', true);
      resolve(res);
    }).catch(res => {
      showToast('支付失败');
      reject(res);
    })
  });
}
//生成分享二维码图片:
export const getCodeFun = (codedata = null) => {
  //得到分享的二维码:
  if (!(!!codedata)) { //未定义时,跳转到首页,固定的二维码:
    codedata = {
      page: "pages/home/home",
      scene: '?invite_code=' + wx.getStorageSync("userInfo")['invite_code']
    }
  }
  return new Promise((resolve, reject) => {
    getCode(codedata).then(res => {
      resolve(res);
    });
  });
}
//画图:
export const canvasImgsFun = ({
  ctx,
  imgData,
  txtData = []
}) => {
  console.log("执行了canvasImgsFun")
  // showLoading('生成中~');
  //如果未传文本内容,使用默认的空值:
  if (txtData.length == 0) {
    txtData = [{
      'txt': '',
      'X': 82,
      'Y': 410,
      'fontsize': 17,
      color: '#444444'
    }, ]
  }
  return new Promise((resolve, reject) => {
    console.log(imgData)
    console.log(txtData)
    //对涉及到的图片、文字,进行画图:
    for (const i in imgData) {
      drawImg(imgData[i], ctx).then(res => {
        console.log("iii:", i);
        // if (i == (imgData.length - 1)) {
          //对涉及到的文字画图:
          for (const j in txtData) {
            console.log("jjj:",j)
            drawTxt(txtData[j], ctx).then(res => {
              // if (j == (txtData.length - 1)) {
                // ctx.draw(false, (() => {
                ctx.draw(true, (() => {
                  setTimeout(function(){
                    console.log("开始canvasToTempFilePath")
                  wx.canvasToTempFilePath({
                    canvasId: 'canvas',
                    success: (res => {
                      console.log("执行结束")
                      console.log(res)
                      hideLoading();
                      resolve(res.tempFilePath);
                    })
                  })
                  },1000)
                  
                }))
              // }
            });
          }
        // }
      });
    }
  });
}
// 画图片 down
export const drawImg = (imgData, ctx) => { //state,判断画的图是本地图片还是远程图片
  console.log("执行了drawImg")
  return new Promise((resolve, reject) => {
    downloadFileFun(imgData['imgurl'], imgData['state']).then(res => {

      wx.getImageInfo({
        src: res,
        success: (res) => {
          console.log("res:", res.path);
          ctx.drawImage(imgData['state'] ? imgData['imgurl'] : res.path, cpx(imgData['X']), cpx(imgData['Y']), cpx(imgData['W']), cpx(imgData['H']))
          resolve()
        },
        fail(res) {}
      })
    });
  }).catch(res => {});
}
//画文本:
export const drawTxt = (txtData, ctx) => {
  console.log("执行了drawTxt")
  return new Promise((resolve, reject) => {
    ctx.font = 'normal bold 17px sans-serif';
    var text = txtData['txt']; //这是要绘制的文本';
    if (text.length > 10) {
      var chr = text.split(""); //这个方法是将一个字符串分割成字符串数组    
      var temp = "";
      var row = [];
      ctx.setFontSize(txtData['fontsize'])
      ctx.setFillStyle(txtData['color'])
      for (var a = 0; a < chr.length; a++) {
        if (ctx.measureText(temp).width < 265) {
          temp += chr[a];
        } else {
          a--; //这里添加了a-- 是为了防止字符丢失,效果图中有对比
          row.push(temp);
          temp = "";
        }
      }
      row.push(temp); //如果数组长度大于2 则截取前两个
      if (row.length > 2) {
        var rowCut = row.slice(0, 2);
        var rowPart = rowCut[1];
        var test = "";
        var empty = [];
        for (var a = 0; a < rowPart.length; a++) {
          if (ctx.measureText(test).width < 250) {
            test += rowPart[a];
          } else {
            break;
          }
        }
        empty.push(test);
        console.log(empty[0])
        var group = empty[0] + "..."
        // 这里只显示两行,超出的用...表示
        rowCut.splice(1, 1, group);
        row = rowCut;
      }
      for (var b = 0; b < row.length; b++) {
        ctx.fillText(row[b], cpx(b != 0 ? txtData['X'] : txtData['X']), cpx(txtData['Y'] + b * 20, b != 0 ? 150 : 0));
      }
    } else {
      ctx.setFontSize(txtData['fontsize'])
      ctx.setFillStyle(txtData['color'])
      ctx.fillText(txtData['txt'], cpx(txtData['X']), cpx(txtData['Y']));
    }

    resolve()
  });
}
// 图片下载
export const downloadFileFun = (imgUrl, state) => {
  console.log("执行了downloadFileFun")
  return new Promise((resolve, reject) => {
    if (!state) {
      downloadFile(imgUrl).then(res => {
        resolve(res);
      });
    } else {
      resolve(imgUrl);
    }

  });
}

//画图单位转换:
export const cpx = (a) => {
  let system = wx.getSystemInfoSync();
  let pix = system.screenWidth / wx.getStorageSync('windowWidth');
  return a * pix
}

//上拉刷新:
export const reachBottomFun = (count, page, page_size = 10) => {
  return new Promise((resolve, reject) => {
    if (page * page_size >= count || count < 9) {
      return false
    } else {
      resolve(++page);
    }
  });
}
//列表数据拼接处理:
export const dealListData = (listData, res, page) => {
  console.log("listData:", listData);
  if (!!listData['items'] && res['items'].length > 0 && page != 1 && listData['total'] > listData['items'].length) {
    res['items'] = listData['items'].concat(res['items']);
  }
  if (!(!!listData['items'])) {
    listData = {
      total: 0,
      items: []
    }
  }
  return res['items'].length > 0 ? res : listData;
}
//一次进行多张远程网络图片保存:
export const saveMultiImg = (imgListData) => {
  //刷新用户基本信息: saveImageToPhotosAlbum
  return new Promise((resolve, reject) => {
    imgListData.forEach((imgUrl, index) => {
      Promise.resolve().then(() => {
        downloadFile(imgUrl).then(res => {
          console.log(123, res)
          saveImageToPhotosAlbum(res).then(res => {
            resolve(res);
          }).catch(res => {
            reject(res)
          });
        }).catch(res => {
          reject(res);
        });
      })
    })
  })
}

//获取用户的登录状态的值:
export const getLoginState = () => {
  let loginState = wx.getStorageSync("loginState");

  return !!loginState ? true : false;
}
//判断是否已经登录,如果没有登录,去登录页面进行登录:
export const loginJudgment = () => {
  return new Promise((resolve, reject) => {
    let token = wx.getStorageSync("token");
    //判断是否已经登录了:
    if (!!token) {
      resolve();
    } else {
      showToast('请先登录');
      navigateTo({
        url: "/pages/login/login"
      });
      reject();
    }
  });
}

你可能感兴趣的:(js)