var gemhoUtil = window.gemhoUtil || {}
gemhoUtil.formatDate = function (date, type) {
  var ymd = `${date.getFullYear()}-${
    (date.getMonth() + 1 > 9 ? '' : '0') + (date.getMonth() + 1)
  }-${(date.getDate() > 9 ? '' : '0') + date.getDate()}`
  if (type === 'YYYY-MM-DD HH:MM:SS') {
    return ymd + ' 00:00:00'
  }
  return ymd
}
gemhoUtil.getTargetDateYMD = function (dayLength, type) {
  var dayLength = dayLength || 0
  var tempDate = new Date()
  tempDate.setDate(tempDate.getDate() + dayLength)
  var year = tempDate.getFullYear()
  var month =
    tempDate.getMonth() + 1 < 10
      ? '0' + (tempDate.getMonth() + 1)
      : tempDate.getMonth() + 1
  var day =
    tempDate.getDate() < 10 ? '0' + tempDate.getDate() : tempDate.getDate()
  return year + '-' + month + '-' + day
}
gemhoUtil.getTargetDateYM = function (dayLength, type) {
  var dayLength = dayLength || 0
  var tempDate = new Date()
  tempDate.setDate(tempDate.getDate() + dayLength)
  var year = tempDate.getFullYear()
  var month =
    tempDate.getMonth() + 1 < 10
      ? '0' + (tempDate.getMonth() + 1)
      : tempDate.getMonth() + 1
  return year + '-' + month
}

gemhoUtil.getTargetDateYMByPara = function (date) {
  var tempDate = date
  var year = tempDate.getFullYear()
  var month =
    tempDate.getMonth() + 1 < 10
      ? '0' + (tempDate.getMonth() + 1)
      : tempDate.getMonth() + 1
  return year + '-' + month
}

/**
 *
 * @functionName: getPageName
 * @Description: get page name from URL
 * @author: zjb
 *
 */
gemhoUtil.getPageName = function () {
  var pathname = window.location.pathname
  if (pathname) {
    pathname = pathname.split('/')
    return pathname[pathname.length - 1].split('.')[0]
  } else {
    return ''
  }
}

/**
 *
 * @functionName: getNavigator
 * @Description: get navigator
 * @author: zjb
 *
 */
gemhoUtil.getNavigator = function () {
  var ua = navigator.userAgent.toLowerCase()
  if (ua.indexOf('chrome') != -1) {
    return 'Chrome'
  } else if (ua.indexOf('firefox') != -1) {
    return 'Firefox'
  } else if (ua.indexOf('safari') != -1) {
    return 'Safari'
  } else if (ua.indexOf('opera') != -1) {
    return 'Opera'
  } else {
    return 'Unknow'
  }
}

/**
 *
 * @functionName: getParameter
 * @Description: get parameter from URL
 * @author: zjb
 *
 */
gemhoUtil.getParameter = function (name) {
  var search = location.search
  if (!search) {
    return false
  }
  search = search.split('?')
  var data = search[1].split('=')
  if (search[1].indexOf(name) == -1) {
    return ''
    return
  }
  if (search[1].indexOf('&') == -1) {
    data = search[1].split('=')
    return data[1]
  } else {
    data = search[1].split('&')
    for (var i = 0; i <= data.length - 1; i++) {
      var l_data = data[i].split('=')
      if (l_data[0] == name) {
        return l_data[1]
        break
      } else {
        continue
      }
    }
  }
}

/**
 *
 * @functionName: getParameter
 * @Description: get parameter from URL
 * @author: yl
 *
 */
gemhoUtil.getUrlParams = function () {
  const search = window.location.search
  const params = new URLSearchParams(search)
  const paramsObj = {}

  for (const [key, value] of params) {
    paramsObj[key] = decodeURIComponent(value)
  }
  return paramsObj
}

/**
 *
 * @functionName: setParameter
 * @Description: set parameter to URL
 * @author: zjb
 *
 */
gemhoUtil.setParameter = function () {
  if (arguments.length) {
    var url = arguments[0],
      paramsObj = arguments[1]
    if (paramsObj) {
      var parameter = ''
      for (var x in paramsObj) {
        parameter += x + '=' + paramsObj[x] + '&'
      }
      url += '?' + parameter.substr(0, parameter.length - 1)
    }
    return url
  }
}

/**
 * @functionName: setCookie
 * @Description: set cookies
 * @author: zjb
 */
gemhoUtil.setCookie = function (name, value, days) {
  var len = arguments.length
  if (len == 2) {
    var exp = new Date()
    exp.setTime(exp.getTime() + 30 * 24 * 60 * 60 * 1000)
    document.cookie =
      name + '=' + escape(value) + ';expires=' + exp.toGMTString() + ';path=/'
  } else if (len == 3) {
    var exp = new Date()
    exp.setDate(exp.getDate() + parseInt(days))
    exp.setHours(1, 0, 0, 0)
    document.cookie =
      name + '=' + escape(value) + ';expires=' + exp.toGMTString() + ';path=/'
  }
}

/**
 *
 * @functionName: getCookie
 * @Description: get cookies
 * @author: zjb
 *
 */
gemhoUtil.getCookie = function (name) {
  var arr,
    reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
  if ((arr = document.cookie.match(reg))) return unescape(arr[2])
  else return null
}

/**
 *
 * @functionName: delCookie
 * @Description: delete cookies
 * @author: zjb
 *
 */
gemhoUtil.delCookie = function (name) {
  var exp = new Date()
  exp.setTime(exp.getTime() - 1)
  var cval = getCookie(name)
  if (cval != null)
    document.cookie =
      name + '=' + cval + ';expires=' + exp.toGMTString() + ';path=/'
}

/**
 *
 * @functionName:
 * @Description: 获取url页面名称方法
 * @param: date
 */
gemhoUtil.getPageName = function () {
  var pageN = window.location.pathname
  pageN = pageN.substring(pageN.lastIndexOf('/') + 1, pageN.indexOf('.'))
  if (pageN) return pageN
}

/**
 * 跳转页面 更新版本号
 * @param path
 * @returns
 * @demo  navigatePage('/warehouse/company/companyDetail.html?companyId=1002');
 */
gemhoUtil.navigatePage = function (path, title) {
  vant.Toast.loading({
    message: title || '页面跳转中...',
    forbidClick: true,
    loadingType: 'spinner',
  })

  if (!path) {
    return
  }
  var url = ''
  if (path.indexOf('?') > -1) {
    // 带有参数
    url += path + '&rev=' + +new Date()
  } else {
    url += path + '?rev=' + +new Date()
  }

  // 保存当前的滚动位置
  var scrollPosition = window.scrollY

  // 利用 pushState 在浏览器历史记录中添加新状态
  // history.pushState({ scrollPosition: scrollPosition }, '');
  console.log('跳转页面', scrollPosition)
  gemhoUtil.setCookie('scrollPosition', scrollPosition)

  location.href = url
}

/**
 * 跳转页面 更新版本号
 * @param path
 * @returns
 * @demo  nav2asd('src/_shanghu_home.html?id=1002');
 */
gemhoUtil.nav2asd = function (opt) {
  const baseUrl =
    'https://web1.isdapp.shandong.gov.cn/jmopen_files/unzip/d14b94db457149eab6260efd27deba47/gqyjglptxiefn/'
  lightAppJssdk.navigation.show({
    url: baseUrl + (opt.url || 'index.html'),
    title: title || '高区安全“码”上查监管平台',
    isgoback: '0',
    success: function (data) {
      // 成功回调
    },
    fail: function (data) {
      // 错误返回
    },
  })
}

/**
 * 爱山东下载方法
 * @param {Object} url  下载文件全路径
 * https://h5.tfryb.com/hos-server/pub/jmas/jmasbucket//jmopen_files/webapp/jssdk/be0c4a53adf04f9db4e39a303af78689.docx
 */
gemhoUtil.downloadFile = function (url) {
  lightAppJssdk.download.downloadFiles({
    filePath:
      'https://h5.tfryb.com/hos-server/pub/jmas/jmasbucket//jmopen_files/webapp/jssdk/be0c4a53adf04f9db4e39a303af78689.docx',
    success: function (data) {
      alert(JSON.stringify(data))
    },
    fail: function (err) {
      alert(JSON.stringify(err))
    },
  })
}

// aes解密
function aes_Decrypt(word, key) {
  var key = CryptoJS.enc.Utf8.parse(key) //转为128bit
  var srcs = CryptoJS.enc.Hex.parse(word) //转为16进制
  var str = CryptoJS.enc.Base64.stringify(srcs) //变为Base64编码的字符串
  var decrypt = CryptoJS.AES.decrypt(str, key, {
    mode: CryptoJS.mode.ECB,
    spadding: CryptoJS.pad.Pkcs7,
  })
  return decrypt.toString(CryptoJS.enc.Utf8)
}

// sm2解密,需要创建加密应用时的私钥
function sm2_Decrypt(word, key) {
  return SM.decrypt(word, key)
}
