util.js 9.14 KB
import bigdatautilApi from '~/api/bigdatautil'
import api from '~/utils/request/request'
import {
  Storage
} from '~/utils/cache/storage'
import sopApi from '~/api/sopApi'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
const $Storage = new Storage()
/**
 * 日期格式化
 * let time = new Date().format('yyyy-MM-dd hh:mm:ss') //log   2020-07-31 10:00:00
 */
Date.prototype.format = function (fmt) {
  let o = {
    'M+': this.getMonth() + 1, //月份
    'd+': this.getDate(), //日
    'h+': this.getHours(), //小时
    'm+': this.getMinutes(), //分
    's+': this.getSeconds(), //秒
    //季度
    'q+': Math.floor((this.getMonth() + 3) / 3),
    S: this.getMilliseconds() //毫秒
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
  }
  return fmt
}
const isEmptyObj = (obj) => {
  return JSON.stringify(obj) === "{}";
};

const setNavigationBarTitle = (title) => {
  getSystemInfo({
    success: (res) => {
      // console.log('++++++++++++++', res);
      // console.log('title length',title.length)
      let width = res.safeArea.width / res.fontSizeSetting;
      // console.log('width: ', width);
      let space = '';
      // for (let i = 0; i <= width+4; i++) {
      //   space = space + ' ';
      // }

      width = width - (title.length) / 2

      for (let i = 0; i < width; i++) {
        space = space + ' ';
      }

      if (res.system.includes('iOS') === false) {
        wx.setNavigationBarTitle({
          title: space + title
        });
      } else {
        wx.setNavigationBarTitle({
          title: title
        });
      }
    }
  });
}
/**节流 */
const throttle = (fn, gapTime) => {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500
  }
  let _lastTime = null
  // 返回新的函数
  return function () {
    let _nowTime = +new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments) //将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}
const debounce = (fn, delay = 500) => {
  // timer 是在闭包中的
  let timer = null
  return function () {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, arguments)
    }, delay)
  }
}
const promise = callBack => {
  return new Promise((resolve, reject) => {
    callBack(resolve, reject)
  })
}

/** */
const getSessionId = () => {
  return $Storage.get('scrm_shopmall_sessionId')
}
const setSessionId = sessionId => {
  $Storage.set('scrm_shopmall_sessionId', sessionId)
}

// const setStorageSync = (key, data) => {
//   wx.setStorageSync(key, JSON.stringify(data))
// }
// const getStorageSync = key => {
//   let data = wx.getStorageSync(key) || null
//   return JSON.parse(data)
// }

const getUserInfo = () => {
  return $Storage.get('srcm_shopmall_user_info') || null
  // return JSON.parse(user)
}
const setUserInfo = userInfo => {
  $Storage.set('srcm_shopmall_user_info', userInfo)
}

/** 小程序扫码进来的sceneId */
const getSceneId = path => {
  let [_route_, _options_] = path.split('?')
  let [target] = _route_.split('/')
  let name = _route_.split('/').pop()
  let scene = _options_ ? _options_.split('=')[1] : ''
  return {
    name,
    scene,
    target
  }
}

const clearObjNull = options => {
  let obj = {}
  Object.keys(options).map(e => {
    if (options[e] != null && options[e] != undefined) {
      if (typeof options[e] == 'object') {
        Object.keys(options[e]).map(key => {
          if (options[e][key] == null || options[e][key] == undefined) delete options[e][key]
        })
      }
      obj[e] = options[e]
    }
  })
  return obj
}

/**SOP埋点 */
let _behaviorType = '',
  _taskId = '',
  _eventId = ''
const customerbehavior = (behaviorType = 1) => {
  if (wx.$authStatus) return
  let {
    taskId,
    eventId
  } = wx.getEnterOptionsSync().query
  let {
    openId,
    phone
  } = getUserInfo()

  if (_behaviorType == behaviorType && (_taskId == taskId || _eventId == eventId)) return
  let params = {
    customerPhone: phone,
    behaviorType,
    openId,
  }
  if (taskId || eventId) {
    if (taskId) {
      params.taskId = taskId
      _taskId = taskId
    }
    if (eventId) {
      params.eventId = eventId
      _eventId = eventId
    }
    sopApi.customerbehaviorByEventId(params)
  }


  _behaviorType = behaviorType

}
/**埋点上报 */
const reportData = (params, check, receive, isRecommended) => {
  let data = {
    add_way: '104'
  }
  const user = getUserInfo() || {}
  if (params.activity_id) {
    data.activity_id = params.activity_id
  }
  if (params.merchantId) {
    data.merchant_id = params.merchantId
  }
  if (params.phone || user.phone) {
    data.customer_phone = params.phone || user.phone
  }
  if (check) {
    data.check_time = new Date().format('yyyy-MM-dd hh:mm:ss')
    data.check_status = 1
  }
  if (receive) {
    data.receive_status = 1
    data.receive_time = new Date().format('yyyy-MM-dd hh:mm:ss')
  }
  if (user.unionId) {
    data.union_id = user.unionId
  }
  if (user.openId) {
    data.open_id = user.openId
  }
  if (isRecommended) {
    data.item_type = params.item_type
    data.action_type = params.action_type
    data.business_type = 1
    data.create_time = new Date().format('yyyy-MM-dd hh:mm:ss')
    data.staff_uuid = params.shareStaffUuid
    data.item_id = params.item_id
    if (params.order_id) {
      data.order_id = params.order_id
    }
  }
  // let json = encodeURIComponent(JSON.stringify(data))
  let json = JSON.stringify(data)
  bigdatautilApi.reportCustomer({
    json
  })
}

const deepClone = (target) => {
  const map = new WeakMap()

  function isObject(target) {
    return (typeof target === 'object' && target) || typeof target === 'function'
  }

  function clone(data) {
    if (!isObject(data)) {
      return data
    }
    if ([Date, RegExp].includes(data.constructor)) {
      return new data.constructor(data)
    }
    if (typeof data === 'function') {
      return new Function('return ' + data.toString())()
    }
    const exist = map.get(data)
    if (exist) {
      return exist
    }
    if (data instanceof Map) {
      const result = new Map()
      map.set(data, result)
      data.forEach((val, key) => {
        if (isObject(val)) {
          result.set(key, clone(val))
        } else {
          result.set(key, val)
        }
      })
      return result
    }
    if (data instanceof Set) {
      const result = new Set()
      map.set(data, result)
      data.forEach(val => {
        if (isObject(val)) {
          result.add(clone(val))
        } else {
          result.add(val)
        }
      })
      return result
    }
    const keys = Reflect.ownKeys(data)
    const allDesc = Object.getOwnPropertyDescriptors(data)
    const result = Object.create(Object.getPrototypeOf(data), allDesc)
    map.set(data, result)
    keys.forEach(key => {
      const val = data[key]
      if (isObject(val)) {
        result[key] = clone(val)
      } else {
        result[key] = val
      }
    })
    return result
  }

  return clone(target)
}

/**获取mock数据 */
let mockRequestCount = null,
  mockTimer = {},
  mockCache = null
const getMockData = async () => {
  const MOCKDATA = $Storage.get('mock_data')
  try {
    if (MOCKDATA && Date.now() - MOCKDATA.createTime < 5 * 60e3) {
      return Promise.resolve(MOCKDATA)
    } else {
      if (!mockRequestCount) {
        mockCache = null
        mockRequestCount = Date.now()
        const data = await api.getMock()
        data.createTime = Date.now()
        mockCache = data
        $Storage.set('mock_data', data)
        return Promise.resolve(data)
      } else {
        const key = Date.now()
        return new Promise((resolve) => {
          mockTimer[key] = setInterval(() => {
            if (mockCache) {
              clearInterval(mockTimer[key])
              mockRequestCount = null
              resolve(mockCache)
            }
          }, 1e3)
        })
      }
    }
  } catch (error) {
    if (mockTimer[key]) clearInterval(mockTimer[key])
    mockRequestCount = null
    return Promise.reject(error)
  }
}

/**判断是不是续保商城商户*/
const judgeMerchantForXubao = () => {
  const XUBAO_MERCHANTID = wx.$storage.get('srcm_shopmall_merchant_id')
  let tabIndex = 0
  if (XUBAO_MERCHANTID == 44209499 || XUBAO_MERCHANTID == 44211651 || XUBAO_MERCHANTID == 44211562) {
    tabIndex = 1
  }
  return tabIndex
}
/**百度经纬度转腾讯经纬度
 * lng
 * lat
 */
const bMapTransQQMap = (lng, lat) => {
  let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
  let x = lng - 0.0065;
  let y = lat - 0.006;
  let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
  let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
  let lngs = z * Math.cos(theta);
  let lats = z * Math.sin(theta);
  return {
    lng: lngs,
    lat: lats
  };
}

const Util = {
  customerbehavior,
  getSessionId,
  setSessionId,
  clearObjNull,
  getUserInfo,
  setUserInfo,
  getSceneId,
  deepClone,
  throttle,
  promise,
  reportData,
  getMockData,
  debounce,
  isEmptyObj,
  setNavigationBarTitle,
  judgeMerchantForXubao,
  bMapTransQQMap
}
export default Util