import QRCode from "qrcode"
export const HOST = "https://huodong2.lzlj.com"
export const DIR = "zhaoma"
export const API = `${HOST}/api/${DIR}/`
export const debuglog = (text) => {
  console.log(`%c -- ${text} `, "background:green;color:#fff")
}
export const Storage = {
  set (name, data) {
    localStorage.setItem(name, JSON.stringify(data))
  },
  get (name) {
    return JSON.parse(localStorage.getItem(name))
  },
  clear () {
    localStorage.clear()
  },
  remove (name) {
    localStorage.removeItem(name)
  }
}
export const Sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
export const isLogin = () => {
  return !!(Storage.get("userinfos") && Storage.get("userinfos").phone)
  // return true
}
export const isBaseLogin = () => {
  return Storage.get("userinfos")
  // return true
}
export const generateQR = async (text, width = 160, height = 160) => {
  return await QRCode.toDataURL(`${HOST}/${DIR}/?${text}`, {
    errorCorrectionLevel: 'H',
    width: width,
    height: height,
    margin: 1,
    colorDark: "#000000",
    colorLight: "#e8e2cc",
  })
}

export const createPop = (id, classname) => {
  const wrapper = document.createElement("div")
  wrapper.id = id
  wrapper.classList.add(classname)
  document.querySelector("body").appendChild(wrapper)
  return wrapper
}
export const isIos = () => {
  return /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)
}
export const isWeixin = () => {
  return /MicroMessenger/i.test(window.navigator.userAgent)
}
export const isWeixinPlatform = () => {
  return /MicroMessenger/i.test(window.navigator.userAgent) || window.__wxjs_environment === 'miniprogram'
}
export const isWeibo = () => {
  return /Weibo/i.test(window.navigator.userAgent)
}
export const isDouyin = () => {
  return /aweme/i.test(window.navigator.userAgent)
}
export const isWebp = () => {
  return !![].map && document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0
}
export const isMiniPage = () => {
  return window.__wxjs_environment === 'miniprogram'
  // return true
}
export const webpAsPng = (url) => {
  const nowebp = document.querySelector("html").classList.value.indexOf("nowebp") > -1
  return nowebp ? url.replace(".webp", ".webp").replace("images/", "images/png/") : url
}
export const getUserBrowersName = () => {
  const ua = navigator.userAgent
  if (isWeixin()) {
    return "weixin"
  } else if (isWeibo()) {
    return "weibo"
  } else if (isDouyin()) {
    return "douyin"
  } else if (isMiniPage()) {
    return "miniprogram"
  } else {
    return "other"
  }
}
export const getMiniPageBtnHack = (url) => {
  //TODO确认小程序appid！！！
  let html = ''
  html += `<wx-open-launch-weapp id="launch-btn" appid="wxc911dd6c6bc128de" path="${url}"><template>`
  html += '<style>.open-btn {position:absolute;width:100%;height:100%;opacity:0}</style>'
  html += '<button class="open-btn">打开小程序</button>'
  html += '</template></wx-open-launch-weapp>'
  return html
}

export const miniJumpToScene = () => {
  wx.miniProgram.navigateTo({ url: '/pages/retail-act/landing-page/ordinary?id=943829622103607910&orgId=200282401019674482&programId=84796583983972352' })
}
export const miniJumpToActive = () => {
  wx.miniProgram.navigateTo({ url: '/pages/retail-act/landing-page/ordinary?id=897432916524553363&orgId=200282401019674482&programId=84796583983972352' })
}
export const miniJumpToCouopon = () => {
  wx.miniProgram.navigateTo({
    url: '/pages/unify/unify?orgId=200282401019674482&targetUrl=%2Fpages%2Fcoupon%2Fcoupons-list'
  })
}
export const miniJumpToCenter = () => {
  wx.miniProgram.navigateTo({ url: '/pages/unify/unify?currentCode=my&orgId=200282401019674482' })
}
//[ ]
// export const miniJumpToCouopon = () => {
//   wx.miniProgram.navigateTo({ url: 'pages/unify/unify?orgId=200282401019674482&targetUrl=%2Fpages%2Fcoupon%2Fcoupons-list' })
// }
export const getParam = (name) => {
  if ('URLSearchParams' in window) {
    var params = new URLSearchParams(window.location.search)
    return params.get(name) ? params.get(name) : null
  } else {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'),
      r = window.location.search.substr(1).match(reg)

    if (r != null) return unescape(r[2])
    return null
  }
}

export const Request = async (url, data, type, noloading, noerror) => {
  let headers = {
    'Content-Type': 'application/json',
    Accept: "application/json",
    "Source": "iceSip",
    'App-Channel': getUserBrowersName(),
    refer: document.referrer,
    blackbox: Storage.get("blackbox") ? Storage.get("blackbox") : false
  }

  if (url != "sms/sendCode" && url != "sms/authPhone" && url != "wechat/login" && url != "wechat/jssdk") {
    if (isLogin()) {
      headers.Authorization = `Bearer ${Storage.get("userinfos").api_token}`
    } else {
      Storage.clear()
      weui.alert("登录失效，请重新登录")
      // window.location.reload()
    }
  }

  if (isBaseLogin() && url == "sms/authPhone") {
    headers.Authorization = `Bearer ${Storage.get("userinfos").api_token}`
  }

  let loading = false
  if (!noloading) {
    loading = weui.loading()
  }

  let message = "请求失败，请重试"

  let fetchData = {
    method: type || 'POST',
    headers: new Headers(headers),
  }

  if (fetchData.method == "POST") {
    fetchData.body = JSON.stringify(data)
  }

  let requrl = `${API}${url}`

  if (type === "GET") {
    let paramArr = []
    Object.keys(data).forEach(v => {
      paramArr.push(`${v}=${data[v]}`)
    })
    requrl = paramArr.length === 0 ? `${requrl}` : `${requrl}?${paramArr.join("&")}`
  }

  try {
    const response = await fetch(`${requrl}`, fetchData)
    const result = await response.json()
    message = result.message || message
    if (getParam("debug")) {
      console.log("url:", url)
      console.log("data:", data)
      console.log(response)
      console.log(result)
    }

    loading && loading.hide()

    if (response.status == 200 || response.status == 201) {
      return { res: response, json: result }
    } else if (response.status == 401) {
      Storage.clear()
      weui.alert("登录失效，请重新登录")
      // window.location.reload()
      return
    } else {
      if (!noerror) {
        weui.alert(message)
      }
      return { res: response, json: result }
    }

  } catch (error) {
    if (!noerror) {
      // weui.alert(message)
    }
    loading && loading.hide()
  }
}


// let str = ''
// let s = ''
// for (let index = 0; index < 60; index++) {
//   str += `import denglong2${index} from "./images/frame/denglong2/denglong2_${index}.webp";`
//   s+=`denglong2${index},`
// }