상용 js 방법 라 이브 러 리

90881 단어 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();
    }
  });
}

좋은 웹페이지 즐겨찾기