/**
 * @brief 提示框
 * @param  zconfirm('是否清除数据', (result: boolean) => {if (result) { 确认 } else { 取消 } })
 * @return
 */
export const zconfirm = (msg: string, callBackFun?: any) => {
  uni.showModal({
    content: msg,
    success(res) {
      if (res.confirm) {
        callBackFun(true)
      } else if (res.cancel) {
        callBackFun(false)
      }
    },
  })
}

export const zalert = (msg: string, callBackFun?: any) => {
  uni.showModal({
    title: "提示",
    content: msg,
    showCancel: false,
    success() {
      if (callBackFun) {
        callBackFun()
      }
    },
  })
}

export const toast = (msg: string) => {
  uni.showToast({
    title: msg,
    duration: 2000,
    mask: false,
    icon: "none",
  })
}

export const sLoading = (msg: string = "加载中...") => {
  uni.showLoading({
    title: msg,
    mask: true,
  })
}

export const hLoading = () => {
  uni.hideLoading()
}

// 防抖
interface DebounceFunc<T extends (...args: any[]) => any> {
  (this: ThisParameterType<T>, ...args: Parameters<T>): ReturnType<T>
}

export function debounce<T extends (...args: any[]) => any>(
  fn: T,
  delay = 300
): DebounceFunc<T> {
  let timer: number | null
  return function (this: ThisParameterType<T>, ...args: Parameters<T>) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.call(this, ...args)
    }, delay)
  } as DebounceFunc<T>
}

export const jsonp = function (url: any, data: any) {
  console.log(url, data)

  return new Promise((resolve, reject) => {
    // 1.初始化url
    let dataString = url.indexOf("?") === -1 ? "?" : "&"
    let callbackName: any = `jsonpCB_${Date.now()}`
    url += `${dataString}callback=${callbackName}`
    if (data) {
      // 2.有请求参数，依次添加到url
      for (let k in data) {
        url += `&${k}=${data[k]}`
      }
    }

    console.log(url, "url")

    let scriptNode = document.createElement("script")
    scriptNode.src = url
    const windows: any = window
    // 3. callback
    windows[callbackName] = (result: any) => {
      result ? resolve(result) : reject("没有返回数据")
      delete window[callbackName]
      document.body.removeChild(scriptNode)
    }

    // 4. 异常情况
    scriptNode.addEventListener(
      "error",
      () => {
        reject("接口返回数据失败")
        delete window[callbackName]
        document.body.removeChild(scriptNode)
      },
      false
    )

    // 5. 开始请求
    document.body.appendChild(scriptNode)
  })
}
