// #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 api from '@/common/http/'

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

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

    var userinfo = await getUserInfo()

    if (
      url &&
      userinfo.isGZSign &&
      !['/pages/index/index', '/pages/repairConfirmation'].find(item => !!~url.indexOf(item))
    ) {
      if (
        (
          await api.post('/worker/check/manual/sign/confirm', {
            type: 'gz'
          })
        )?.data
      ) {
        uni.showModal({
          title: '温馨提示',
          content: '您未签署确认书！',
          cancelText: '取消',
          confirmText: '去签署',
          success: res => {
            if (res.confirm) {
              uni[goToType]({
                url: webHref('/pages/repairConfirmation?type=gz'),
                ...data
              })
            }
          }
        })
      } else {
        uni.showModal({
          title: '温馨提示',
          content: '签署确认书正在审核！',
          cancelText: '取消',
          confirmText: '知道了',
          success: res => {}
        })
      }
      return
    }

    if (
      url &&
      userinfo.isFSSign &&
      !['/pages/index/index', '/pages/repairConfirmation'].find(item => !!~url.indexOf(item))
    ) {
      if (
        (
          await api.post('/worker/check/manual/sign/confirm', {
            type: 'fs'
          })
        )?.data
      ) {
        uni.showModal({
          title: '温馨提示',
          content: '您未签署确认书！',
          cancelText: '取消',
          confirmText: '去签署',
          success: res => {
            if (res.confirm) {
              uni[goToType]({
                url: webHref('/pages/repairConfirmation?type=fs'),
                ...data
              })
            }
          }
        })
      } else {
        uni.showModal({
          title: '温馨提示',
          content: '签署确认书正在审核！',
          cancelText: '取消',
          confirmText: '知道了',
          success: res => {}
        })
      }
      return
    }

    if (
      url &&
      ![
        '/pages/index/index',
        '/pages/workorder/index',
        '/pages/mine/index',
        '/packageMine/pages/userinfo',
        '/packageMine/pages/phone' // 绑定手机号码
      ].find(item => !!~url.indexOf(item)) &&
      !userinfo.mobile
    ) {
      uni.showModal({
        title: '温馨提示',
        content: '你尚未绑定手机号，请尽快绑定以免影响接单！',
        cancelText: '取消',
        confirmText: '去绑定',
        success: res => {
          if (res.confirm) {
            uni[goToType]({
              url: webHref('/packageMine/pages/phone'),
              ...data
            })
          }
        }
      })
      return
    }

    if (
      url &&
      ![
        '/pages/index/index',
        '/pages/workorder/index',
        '/pages/mine/index',
        '/packageMine/pages/userinfo',
        '/packageGoods/pages/order', // 商城
        '/packageMine/pages/distributorEnter', // 分销员
        '/packageMine/pages/myWebsit', // 入驻师傅
        '/packageMine/pages/workerEnter', // 入驻师傅
        '/packageMine/pages/phone', // 绑定手机号码
        '/packageEnter/pages/insurance' // 我的保险
      ].find(item => !!~url.indexOf(item)) &&
      userinfo.type !== 'WORKER'
    ) {
      uni.showModal({
        title: '温馨提示',
        content: '你尚未入驻网点，请尽快入驻以免影响接单！',
        cancelText: '取消',
        confirmText: '去入驻',
        success: res => {
          if (res.confirm) {
            uni[goToType]({
              url: webHref('/packageMine/pages/myWebsit'),
              ...data
            })
          }
        }
      })
      return
    }

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

export function webViewHref(url, pam = {}, crossPagePam = {}) {
  console.log(store.state.user, '----0')
  var defaultPam = {
    ...pam,
    ...crossPagePam,
    appId: store.state.user.appId,
    openId: store.state.user.openId,
    userId: store.state.user.userId,
    code2: store.state.user.code2 || '',
    'x-token': store.state.user.token,
    mobile: store.state.user.mobile,
    username: store.state.user.name,
    ...(() => {
      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 = {}) {
  console.log(store.state.user, '----1')
  if (!url) {
    return undefined
  }
  var defaultPam = {
    ...pam,
    ...crossPagePam,
    appId: store.state.user.appId,
    openId: store.state.user.openId,
    userId: store.state.user.userId,
    code2: store.state.user.code2 || '',
    'x-token': store.state.user.token,
    mobile: store.state.user.mobile,
    username: store.state.user.name,
    ...(() => {
      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
})()
