// #ifdef H5
import wx from 'weixin-js-sdk'
// #endif
import store from '@/store/index.js'
import { isWeixin, getQueryVariable } from './common.js'
import { delayPerform } from 'js-perform-lock'
import md5 from 'md5'
import { getUserInfo } from './util.js'

import { goLoginPage } from '@/mixins/index.js'

import { setStorage, getStorage, removeStorage } from '@/common/utils/storage.js'

export const navToPage = (function () {
  var gopageid = null

  // 需要拦截的地址
  var blacklist = ['/packageGoods/pages/order', '/packageMine/pages/myWebsit', '/packageMine/pages/distributorEnter']

  return async function (p, goToType = 'navigateTo') {
    var { url, ...data } = p

    if (url && blacklist.find(item => !!~url.indexOf(item))) {
      try {
        var userinfo = await getUserInfo()
        // 补充手机号判断

        if (!userinfo.mobile) {
          uni[goToType]({
            url: webHref('/packageMine/pages/phone'),
            ...data
          })
          return
        }
      } catch (error) {
        console.log(error)
      }
    }

    // 纯h5版本
    uni[goToType]({
      url: webHref(url),
      ...data
    })
    return

    // #ifdef H5
    if (isWeixin()) {
      wx.miniProgram.getEnv(res => {
        if (res.miniprogram) {
          var i = 0
          ;(function goTo() {
            if (gopageid) {
              clearTimeout(gopageid)
            }
            i++
            if (uniWebview && uniWebview[goToType]) {
              // h5跳转小程序
              if (getStorage('miniProgram') == 'jsm_env') {
                // 家盛茂小程序环境
                uniWebview[goToType]({
                  ...(() => {
                    if (url) {
                      return {
                        url: url
                      }
                    }
                    return {}
                  })(),
                  ...data
                })
              } else {
                // 原生小程序页面
                var miniProgramPages = []
                if (!!~miniProgramPages.indexOf(url.split('?')[0])) {
                  // 第三方小程序跳转我们的h5页面处理
                  uniWebview[goToType]({
                    ...(() => {
                      if (url) {
                        return {
                          url: `/pagesJsm/pages/middle?webUrl=${encodeURIComponent(webViewHref(url))}`
                        }
                      }
                      return {}
                    })(),
                    ...data
                  })
                } else {
                  // 第三方小程序跳转我们的h5页面处理
                  uniWebview[goToType]({
                    ...(() => {
                      if (url) {
                        return {
                          url: `/pagesJsm/pages/webview?webUrl=${encodeURIComponent(webViewHref(url))}`
                        }
                      }
                      return {}
                    })(),
                    ...data
                  })
                }
              }
            } else if (i < 10) {
              gopageid = setTimeout(function () {
                gopageid = null
                goTo()
              }, 200)
            }
          })()
        } else {
          // 当前环境跳转
          uni[goToType]({
            url: webHref(url),
            ...data
          })
        }
      })
    } else {
      // 当前环境跳转
      uni[goToType]({
        url: webHref(url),
        ...data
      })
    }
    // #endif

    // #ifndef H5
    // 当前环境跳转
    uni[goToType]({
      url: webHref(url),
      ...data
    })
    // #endif
  }
})()

export function webViewHref(url, pam = {}, crossPagePam = {}) {
  var defaultPam = {
    ...pam,
    ...crossPagePam,
    'x-token': store.state.user.token,
    openId: store.state.user.openId,
    userId: store.state.user.userId,
    mobile: store.state.user.mobile,
    username: store.state.user.name,
    useravatar: store.state.user.avatar,
    appId: store.state.user.appId,
    ...(() => {
      if (store.state.user.miniOpenId) {
        return {
          miniOpenId: store.state.user.miniOpenId
        }
      }
      return {}
    })(),
    ...(() => {
      if (store.state.user.sharerOpenId) {
        return {
          sharerOpenId: store.state.user.sharerOpenId
        }
      }
      return {}
    })(),
    // #ifndef H5
    miniProgram: 'jsm_env'
    // #endif
  }

  var pamstr = Object.entries(defaultPam)
    .map(item => item.join('='))
    .join('&')

  if (!!~url.indexOf('?')) {
    return process.env.VUE_APP_HREF + url + `${pamstr ? '&' + pamstr : ''}`
  } else {
    return process.env.VUE_APP_HREF + url + `${pamstr ? '?' + pamstr : ''}`
  }
}

// #ifdef H5

window.navToPage = navToPage

// #endif

export function webHref(url, pam = {}, crossPagePam = {}) {
  if (!url) {
    return undefined
  }
  var defaultPam = {
    ...pam,
    ...crossPagePam,
    'x-token': store.state.user.token,
    openId: store.state.user.openId,
    userId: store.state.user.userId,
    mobile: store.state.user.mobile,
    username: store.state.user.name,
    useravatar: store.state.user.avatar,
    appId: store.state.user.appId,
    ...(() => {
      if (store.state.user.miniOpenId) {
        return {
          miniOpenId: store.state.user.miniOpenId
        }
      }
      return {}
    })(),
    ...(() => {
      if (store.state.user.sharerOpenId) {
        return {
          sharerOpenId: store.state.user.sharerOpenId
        }
      }
      return {}
    })(),
    // #ifndef H5
    miniProgram: 'jsm_env'
    // #endif
  }

  var pamstr = Object.entries(defaultPam)
    .map(item => item.join('='))
    .join('&')

  if (!!~url.indexOf('?')) {
    return url + `${pamstr ? '&' + pamstr : ''}`
  } else {
    return url + `${pamstr ? '?' + pamstr : ''}`
  }
}

export const crossPage = (function () {
  var funs = {}
  var tiemIdIs = {}
  var datacd = []

  // #ifndef H5
  var delaydeparture = new delayPerform(250).refactor(function () {
    var data = {}
    datacd.map(function ([name, val]) {
      data[name] = val
    })
    setStorage('crossPageTs', encodeURIComponent(JSON.stringify(data)))
    store.commit('user/setcrossPagePam', new Date().getTime())
    setTimeout(function () {
      removeStorage('crossPageTs')
    }, 350)
    datacd = []
  })
  // #endif

  // #ifdef H5
  var delaydepartFun = new delayPerform(250).refactor(function () {
    var data = getQueryVariable('crossPageTs')
    if (data) {
      data = JSON.parse(decodeURIComponent(data))
      Object.keys(data).map(name => {
        Object.keys(funs[name]).map(key => {
          funs[name][key](data[name])
        })
      })
    }
  })
  // #endif

  // #ifdef H5
  var idss = {}
  wx.miniProgram.getEnv(res => {
    if (res.miniprogram) {
      ;(function tiemID() {
        try {
          Object.keys(idss).map(name => {
            if (idss[name] && idss[name] < new Date().getTime()) {
              if (getStorage(name)) {
                removeStorage(name)
              }
              delete idss[name]
            }
          })
        } catch (e) {
          //TODO handle the exception
        }
        try {
          Object.keys(funs).map(name => {
            var data = getStorage(name)
            if (data && !idss[name]) {
              Object.keys(funs[name]).map(key => {
                funs[name][key](data)
              })
              idss[name] = new Date().getTime() + 500
            }
          })
        } catch (e) {
          //TODO handle the exception
        }
        setTimeout(tiemID, 200)
      })()
    }
  })
  // #endif

  var funco = {
    $emit(name, data) {
      // 同个环境下可以触发
      if (funs[name]) {
        // #ifdef H5
        /**
         * idss用于h5页面跨窗口数据监听时防止重复监听，初始设值防止防止同窗口下重复执行
         */
        idss[name] = new Date().getTime() + 500
        // #endif
        Object.keys(funs[name]).map(key => {
          funs[name][key](data === undefined ? true : data)
        })
      }

      // #ifndef H5
      // 用于小程序触发更新H5页面
      datacd.push([name, data === undefined ? true : data])
      delaydeparture()
      // #endif

      // #ifdef H5
      // h5在小程序环境下通过定时器传送
      wx.miniProgram.getEnv(res => {
        if (res.miniprogram) {
          var postMessage = (window.uniWebview && window.uniWebview.postMessage) || window.postMessage
          if (postMessage) {
            postMessage({
              data: {
                type: 'crossPageTs',
                name,
                data
              }
            })
          }
          if (tiemIdIs[name]) {
            clearTimeout(tiemIdIs[name])
          }
          setStorage(name, data === undefined ? true : data)
          tiemIdIs[name] = setTimeout(function () {
            removeStorage(name)
          }, 350)
        }
      })
      // #endif
    },

    $on(name, fun) {
      if (!funs[name]) {
        funs[name] = {}
      }
      funs[name][md5(fun.toString())] = fun

      // #ifdef H5
      delaydepartFun()
      // #endif
    },

    $off(name, fun) {
      if (fun) {
        var skey = md5(fun.toString())
        if (funs[name] && funs[name][skey]) {
          delete funs[name][skey]
        }
      } else {
        delete funs[name]
      }
    },

    // #ifndef H5
    $listener(e) {
      e.detail.data.map(({ type, name, data }) => {
        if (funs[name]) {
          Object.keys(funs[name]).map(key => {
            funs[name][key](data)
          })
        }
      })
    }
    // #endif
  }

  return funco
})()
