// 验签
var log = require('@/utils/log.js')
import uni from './uniHooks'
import md5 from 'js-md5';

export function md(params, callback = false) {
  let signStr = '';
  let timeStamp = '10000';
  let password = '123456'
  var key_arr = [];
  for (var key in params) {
    key_arr.push(key)
  }
  var sarr = key_arr.sort();
  sarr.forEach(function (item) {
    if (params[item] === 0 || params[item]) {
      signStr = signStr + params[item] + "&"
    }
  })
  signStr = signStr + password + "&" + timeStamp;
  log.info('MD5签名参数:' + signStr)
  let sign = callback ? md5(signStr) : this.$md5(signStr);
  const headers = {
    'Content-Type': 'application/json; charset=utf-8',
    // #ifdef MP-WEIXIN
    // 'user': 'sys_miniprogram',
    // #endif
    // #ifdef H5
    'user': 'sys_gzh',
    // #endif
    'timeStamp': timeStamp,
    'sign': sign
  }
  uni.setStorageSync('handleUser', JSON.stringify(headers))
  if(callback) {
    return headers
  }
}

// 手机号码隐藏中间4位
export function geTel(tel) {
  var reg = /^(\d{3})\d{4}(\d{4})$/;
  return tel.replace(reg, "$1****$2");
}

// 富文本图片溢出问题
export function formatRichText(html) {
  let newContent = html.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;"').replace(
    /\<div style=\"/gi, '<div style="width:100%;word-break:break-all;word-wrap:normal;').replace(/\s{2,}/g, "")
  return newContent
}

// 防止处理多次点击
export function noMultipleClicks(methods, info) {
  // methods是需要点击后需要执行的函数， info是点击需要传的参数
  let that = this;
  console.log(that.noClick)
  if (that.noClick) {
    if (info && info !== '') {
      // info是执行函数需要传的参数
      methods(info);
    } else {
      methods();
    }
  } else {
    console.log('这里是重复点击的判断')
    return
    // 这里是重复点击的判断
  }
}

// 场景二维码记录
export function saveSceneQrcodeDetail(type, pageIndex, pageName, eventId, eventName, consumptionAmount, consumption_integral) {
  // const app = getApp()
  // const app = {}
  let vipcode = ''
  // console.log(727272, uni.getStorageSync('member'))
  // #ifdef H5
  if (uni.getStorageSync('member') && uni.getStorageSync('member') !== '{}') {
    app.globalData.member = JSON.parse(uni.getStorageSync('member'))
  }
  // #endif
  // 未知会员
  if (!app.globalData.member) {
    vipcode = 2
  } else if (JSON.stringify(app.globalData.member) !== '{}') { // 有会员
    vipcode = 1
  } else {
    vipcode = 0
  }
  const params = {
    groupId: app.globalData.groupId, // 集团编号
    openid: app.globalData.openId,
    mallid: app.globalData.mallid, // 商场号
    isMember: vipcode, // 是否是会员0否1是
    type, // 类型：事件event，page:点击页面
    pageIndex, // 页面标识
    pageName // 页面名称
  }
  // 场景二维码唯一标识
  const paramsScene = app.globalData.paramsScene;
  if (paramsScene) {
    console.log(`===> 场景二维码唯一标识`, JSON.stringify(paramsScene))
    if (JSON.stringify(paramsScene) !== '{}') {
      params.paramsCode = paramsScene.paramsCode
    }
  }

  // 是否是会员
  if (vipcode == 1) {
    params.vipcode = app.globalData.member.vipcode
  }
  // 事件id
  if (eventId) {
    params.eventId = eventId
  }
  // 事件名称
  if (eventName) {
    params.eventName = eventName
  }
  // 消费金额
  if (consumptionAmount) {
    params.consumptionAmount = consumptionAmount
  }
  //消耗积分
  if (consumption_integral) {
    params.consumption_integral = consumption_integral
  }
  this.$md(params);
  uni.request({
    url: this.$baseURL + 'api/1.0/sceneqrcode/saveSceneQrcodeDetail',
    data: params,
    method: 'POST',
    header: JSON.parse(uni.getStorageSync('handleUser')),
    success: (res) => {
    }
  })
}

// 拉新会员
export function savePullVipcode(pullVipcode, pullNewShop, pullNewActivity) {
  // const app = getApp()
  const app = {}
  const params = {
    groupId: app.globalData.groupId,
    pullNewVipcode: app.globalData.member.vipcode,
    mallid: app.globalData.mallid
  }
  // 拉新人的会员号
  if (app.globalData.pullVipcode) {
    params.pullVipcode = app.globalData.pullVipcode
  }
  // 拉新的店铺
  if (pullNewShop) {
    params.pullNewShop = pullNewShop
  }
  // 拉新的活动，例如  爱蜂乐:id   aifengle:000000000000001
  if (pullNewActivity) {
    params.pullNewActivity = pullNewActivity
  }
  // 拉新场景，对应的场景值唯一
  if (JSON.stringify(app.globalData.paramsScene) !== '{}') {
    params.pullNewChannel = app.globalData.paramsScene.paramsCode
  }
  console.log('--------拉新会员---------', params)
  this.$md(params);
  uni.request({
    url: this.$baseURL + 'api/1.0/login/pullNewMember',
    data: params,
    method: 'POST',
    header: JSON.parse(uni.getStorageSync('handleUser')),
    success: (res) => {
    }
  })
}

// H5复制
import h5Copy from '@/utils/js_sdk/junyi-h5-copy.js'

export function copyH5(content) {
  console.log('复制', content)
  // 复制内容，必须字符串，数字需要转换为字符串
  const result = h5Copy(content)
  if (result === false) {
    uni.showToast({
      title: '不支持',
    })
  } else {
    uni.showToast({
      title: '复制成功',
      icon: 'none'
    })
  }
}

//清空缓存
export function delStorageSync(key, sync = true) {
  try {
    if (sync) {
      return uni.removeStorageSync(key);
    } else {
      uni.removeStorage({
        key: key
      });
    }
  } catch (e) {
    return false;
  }
}

// 获取url中的字段的值
// export function getLocationValue(str ,name){
//     var newStr = str.split("?")[1]
//     var result = ''
//     if (str.split("?"))
//     newStr.split("&").forEach(item => {
//         var arr = item.split("=")
//         if (name == arr[0]) {
//             result = arr[1]
//         }
//     })
//     return result
// }
export function getLocationValue(str, variable) {
  // var query = window.location.hash.substring(1);
  var query = str;
  let a = query.split("?").length
  if (query.split("?").length > 1) {
    var vararr = query.split("?")
    for (var j = 1; j < vararr.length; j++) {
      var vars = vararr[j].split("&");
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
          return pair[1];
        }
      }
    }

  }
  return (false);
}

export const isMini = () => {
  // by: https://blog.csdn.net/txz_gray/article/details/103975818
  //3.通过判断navigator.userAgent中包含miniProgram字样
  var userAgent = navigator.userAgent;
  // var isMini = /miniProgram/i.test(userAgent);
  return /miniProgram/i.test(userAgent);
}
