<template>
  <div style="width:100%; height: 100%; position: relative;">
    <vc-keep-alive :ignorePaths="['/help_detail']" :ignoreParams="[]"><router-view :style="'width:100%; height: 100%;'"></router-view></vc-keep-alive>
  </div>
</template>

<script>
import '@/utils/fastclick' // 解决点击存在的300Ms延迟问题
import Vue from 'vue'
import VcKeepAlive from 'vc-keep-alive'
import VcKeepAliveUpdateMixin from '@/utils/keep-alive-update'

Vue.use(VcKeepAlive)
Vue.mixin(VcKeepAliveUpdateMixin)
export default {
  name: 'App',
  data () {
    return {
      empty_webview_loaded: false,
      transitionName: '',
      view_height: window.innerHeight + 'px',
      focus_style: {},
      keep_alive_update_data: {},
      user_info: null,
      flags: false,
      position: { x: 0, y: 0 },
      nx: '',
      ny: '',
      dx: '',
      dy: '',
      xPum: '',
      yPum: ''
    }
  },
  methods: {
    open_app (url) {
      if (!window.plus) {
        return false
      }
      let webview = plus.webview.create(url, url)
      let StatusBarStyle = plus.navigator.getStatusBarStyle()
      plus.nativeUI.showWaiting('加载中....')
      webview.show(
        'pop-in',
        300,
        function () {
          // 窗口显示动画完成
        },
        { acceleration: 'capture' }
      )
      webview.onloaded = function () {
        plus.nativeUI.closeWaiting()
      }
      webview.onclose = function () {
        plus.navigator.setStatusBarStyle(StatusBarStyle)
      }
    },
    download_app (app_url, url) {
      let self = this
      if (!window.plus) {
        return false
      }
      plus.nativeUI.showWaiting('加载中....')
      plus.downloader
        .createDownload(app_url, { filename: '_doc/update/' }, function (d, status) {
          if (status == 200) {
            plus.zip.decompress(
              d.filename,
              '_doc/dir/',
              function () {
                plus.nativeUI.closeWaiting()
                plus.storage.setItem(url.split('#')[0], app_url)
                self.open_app(url)
              },
              function (error) {
                console.log(error)
              }
            )
          } else {
            plus.nativeUI.alert('下载失败！')
          }
          plus.nativeUI.closeWaiting()
        })
        .start()
    },
    get_app_and_open (app_url, _url) {
      let self = this
      let app_path = '_doc/dir/'
      let url = app_path + _url
      if (window.plus) {
        plus.io.getFileInfo({
          success: function (ret) {
            if (plus.storage.getItem(url.split('#')[0]) == app_url) {
              self.open_app(url)
            } else {
              self.download_app(app_url, url)
            }
          },
          filePath: url.split('#')[0],
          fail: function (ret) {
            // 打开失败，如果是文件不存在，则需要从服务器上下载压缩包
            self.download_app(app_url, url)
          }
        })
      }
    },
    parse_com (com) {
      if (com) {
        for (let i in com) {
          if (com[i].$options.keep_alive_update) {
            for (let k in com[i].$options.keep_alive_update) {
              if (this.keep_alive_update_data[k] && com[i].$options.keep_alive_update[k]) {
                com[i].$options.keep_alive_update[k](com[i], this.keep_alive_update_data[k])
              }
            }
          }
          this.parse_com(com[i].$children)
        }
      }
    },
    randomString (len) {
      len = len || 32
      var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      var maxPos = $chars.length
      var pwd = ''
      for (var i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    getParentNodes (element, classname, addclassname) {
      if (element.id == 'app' || element.id == 'div_mark') {
        return
      }
      if (element.classList && element.classList.contains(classname)) {
      } else {
        if (element.parentNode) {
        }
      }
    },

    create_web_view (new_view) {
      let self = this
      if (new_view && window.plus) {
        plus.storage.setItem(process.env.APPID, self.randomString())
      }
      if (window.plus) {
        let view_id = plus.storage.getItem(process.env.APPID)
        if (!view_id) {
          plus.storage.setItem(process.env.APPID, self.randomString())
          view_id = plus.storage.getItem(process.env.APPID)
        }
        let webview = plus.webview.getWebviewById(view_id)
        if (!webview) {
          var plusUrl = plus.webview.currentWebview().getURL()
          plusUrl = plusUrl.split('#')[0] + '#/empty'
          webview = plus.webview.create(plusUrl, view_id)
          webview.setStyle({
            softinputMode: 'adjustResize',
            height: localStorage.getItem('window_height')
          })
        }

        webview.addEventListener(
          'loaded',
          function () {
            self.empty_webview_loaded = true
          },
          false
        )
      }
    },
    set_keep_alive_update_data (key, value) {
      this.keep_alive_update_data[key] = value
    }
  },
  mounted () {
    if (window.plus) {
      this.user_info = JSON.parse(plus.storage.getItem('user_info'))
    } else {
      this.user_info = JSON.parse(localStorage.getItem('user_info'))
    }
    let self = this
    FastClick.attach(document.body)
    Vue.prototype.$keep_alive_update = (key, value) => {
      if (window.plus) {
        let all_view = plus.webview.all()
        let js = 'window.VueObj.$root.$children[0].set_keep_alive_update_data("' + key + '", ' + JSON.stringify(value) + ');'
        for (let i = 0; i < all_view.length; i++) {
          all_view[i].evalJS(js)
        }
      } else {
        self.set_keep_alive_update_data(key, value)
      }
    }
    document.body.addEventListener(
      'click',
      function (e) {
        let blur_fun = function () {
          setTimeout(() => {
            if (
              !(
                document.activeElement &&
                (document.activeElement.type == 'textarea' ||
                  document.activeElement.type == 'text' ||
                  document.activeElement.type == 'password' ||
                  document.activeElement.type == 'search' ||
                  document.activeElement.type == 'number')
              ) &&
              window.plus
            ) {
              plus.webview.currentWebview().setStyle({
                softinputMode: 'adjustResize',
                height: localStorage.getItem('window_height')
              })
            }
          }, 200)
          e.target.classList.remove('cur_focus')
          setTimeout(() => {
            localStorage.removeItem('has_input_focus')
          }, 50)
          if (window.plus) {
            var bar_height = plus.navigator.getStatusbarHeight()
            document.documentElement.style.marginTop = bar_height + 'px'
            document.documentElement.style.height = 'calc(100% - ' + bar_height + 'px)'
          }
        }
        e.target.removeEventListener('blur', blur_fun, false)
        localStorage.setItem('last_click_pos', JSON.stringify({ y: e.offsetY, x: e.offsetX }))
        self.getParentNodes(e.target, 'van-cell--clickable', 'cell-clicked-bg')
        self.getParentNodes(e.target, 'van-grid-item__content', 'col-clicked-bg')
        if (
          e.target.type == 'textarea' ||
          e.target.type == 'text' ||
          e.target.type == 'password' ||
          e.target.type == 'search' ||
          e.target.type == 'number' ||
          e.target.classList.contains('input_label') ||
          e.target.classList.contains('hidden_input')
        ) {
          if (navigator.userAgent.indexOf('Android') > 0 && window.plus) {
            setTimeout(() => {
              let _target = e.target.cloneNode(true)
              e.target.parentNode.insertBefore(_target, e.target)
              e.target.classList.add('ad_has_focus')
              plus.webview.currentWebview().setStyle({
                softinputMode: 'adjustResize',
                height: '100%'
              })
              setTimeout(() => {
                e.target.classList.remove('ad_has_focus')
                e.target.parentNode.removeChild(_target)
                e.target.classList.add('cur_focus')
                setTimeout(() => {
                  window.scroll(0, 0)
                  var myEvent = new Event('resize')
                  window.dispatchEvent(myEvent)
                }, 100)
              }, 100)
            }, 200)
          }

          if (e.target.classList.contains('input_label')) {
            if (e.target.children[0].classList.contains('hasfocus')) {
              return
            }
            e.target.children[0].classList.add('hasfocus')
            e.target.children[0].focus()
            e.target.children[0].classList.remove('hidden_input')
            e.target.children[0].addEventListener('blur', blur_fun, false)
          } else if (e.target.classList.contains('hidden_input')) {
            if (e.target.classList.contains('hasfocus')) {
              return
            }
            e.target.classList.add('hasfocus')
            e.target.focus()
            e.target.classList.remove('hidden_input')
            e.target.addEventListener('blur', blur_fun, false)
          } else {
            if (e.target.classList.contains('hasfocus')) {
              return
            }
            e.target.classList.add('hasfocus')
            e.target.focus()
            e.target.addEventListener('blur', blur_fun, false)
          }
          localStorage.setItem('has_input_focus', 1)
        } else {
          // 如果当前有一个元素是一个input，它获取了焦点，那么这时点击别的区域是要让它失去焦点的，要去掉其它区域的点击事件，防止乱跳
          // 只针对安卓
          if (navigator.userAgent.indexOf('Android') > 0 && localStorage.getItem('has_input_focus')) {
            document.activeElement.blur()
          }
        }
      },
      true
    )
  },
  created () {
    localStorage.removeItem('menuCommon')
    localStorage.removeItem('menu')
    if (navigator.userAgent.indexOf('Android') > 0) {
      this.$setCache('isAndroid', 1)
    } else {
      this.$setCache('isAndroid', 2)
    }
    let self = this
    self.create_web_view(false)
    self.$router.beforeEach((to, from, next) => {
      let view_id = ''
      if (window.plus) {
        view_id = plus.storage.getItem(process.env.APPID)
      } else {
        self.parse_com(self.$root.$children)
        self.keep_alive_update_data = {}
      }
      if (window.plus && plus.webview.currentWebview().id != view_id && from.name != 'empty' && to.fullPath.indexOf('replace=1') < 0) {
        let StatusBarStyle = plus.navigator.getStatusBarStyle()
        plus.navigator.setStatusBarStyle('light')
        let div_mark = document.createElement('DIV')
        div_mark.style.zIndex = 1000
        div_mark.id = 'div_mark'
        div_mark.style.top = 0
        div_mark.style.left = 0
        div_mark.style.right = 0
        div_mark.style.bottom = 0
        div_mark.style.position = 'fixed'
        document.body.appendChild(div_mark)
        var plusUrl = plus.webview.currentWebview().getURL()
        var _empty_webview = plus.webview.getWebviewById(view_id)
        plusUrl = plusUrl.split('#')[0] + '#' + to.fullPath
        if (_empty_webview && plus.storage.getItem(view_id + '_loaded')) {
          _empty_webview.evalJS('window.VueObj.$router.replace({path: "' + to.fullPath + '"});')
          setTimeout(() => {
            _empty_webview.show(
              'pop-in',
              300,
              function () {
                // 窗口显示动画完成
                plus.nativeUI.closeWaiting()
                self.create_web_view(true)
              },
              { acceleration: 'capture' }
            )
            document.body.removeChild(div_mark)
          }, 100)
          _empty_webview.onclose = function () {
            let close_setp = localStorage.getItem('close_setp')
            if (close_setp * 1 < -1) {
              localStorage.setItem('close_setp', close_setp * 1 + 1)
              plus.webview.currentWebview().close()
            }
            plus.navigator.setStatusBarStyle(StatusBarStyle)
          }
        } else {
          if (window.plus) {
            let webview = plus.webview.create(plusUrl, plusUrl)
            plus.nativeUI.showWaiting('加载中....')
            webview.onloaded = function () {
              document.body.removeChild(div_mark)
              webview.show(
                'pop-in',
                300,
                function () {
                  // 窗口显示动画完成
                  plus.nativeUI.closeWaiting()
                },
                { acceleration: 'capture' }
              )
            }
            webview.onclose = function () {
              let close_setp = localStorage.getItem('close_setp')
              if (close_setp * 1 < -1) {
                localStorage.setItem('close_setp', close_setp * 1 + 1)
                plus.webview.currentWebview().close()
              }
              plus.navigator.setStatusBarStyle(StatusBarStyle)
            }
          }
        }
        return false
      }

      let routersArr = (sessionStorage.getItem('routers') && sessionStorage.getItem('routers').split(',')) || []
      if (routersArr.length == 0) {
        routersArr.push(from.path)
        routersArr.push(to.path)
        next()
      } else {
        // 如果是后退
        if (routersArr.indexOf(to.path) != -1) {
          // 从哪里后退的，调用他的状态更新方法，复原状态
          self.$store.commit('RESET', window.$routes_map[from.name].store_name)
          routersArr.splice(routersArr.indexOf(to.path) + 1, 100)
          // 后退时延迟100毫秒执行动画，这样体验会好一些
          next()
          self.transitionName = 'slide-right'
        } else {
          self.transitionName = 'slide-left'
          routersArr.push(to.path)
          next()
        }
      }
      sessionStorage.setItem('routers', routersArr.join(','))
    })
  }
}
</script>

<style>
.slide-right-enter-active,
.slide-right-leave-active,
.slide-left-enter-active,
.slide-left-leave-active {
  will-change: transform;
  transition: all 500ms;
  position: fixed;
  webkit-transform: translateZ(0);
  -moz-transform: translateZ(0);
  -ms-transform: translateZ(0);
  -o-transform: translateZ(0);
  transform: translateZ(0);
  animation-timing-function: cubic-bezier(0, 2, 4, 4, 2, 1, 0);
  -moz-animation-timing-function: cubic-bezier(0, 2, 4, 4, 2, 1, 0);
  -webkit-animation-timing-function: cubic-bezier(0, 2, 4, 4, 2, 1, 0);
}

.slide-right-enter {
  opacity: 0;
  transform: translate3d(-100%, 0, 0);
}

.slide-right-leave-active {
  opacity: 0;
  transform: translate3d(100%, 0, 0);
}

.slide-left-enter {
  opacity: 0;
  transform: translate3d(100%, 0, 0);
}

.slide-left-leave-active {
  opacity: 0;
  transform: translate3d(-100%, 0, 0);
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#app {
  width: 100%;
  margin: 0 auto;
  height: 100%;
}
.suspendButton {
  height: 1.3rem;
  width: 1.3rem;
  /*1.3 如果碰到滑动问题，请检查 z-index。z-index需比web大一级*/
  z-index: 999;
  position: fixed;
  bottom: 1.3rem;
  right: 0.1rem;
  border-radius: 50%;
  background-color: rgb(38 161 255);
  color: #fff;
  touch-action: none;
}
.yuanqiu {
  font-size: 0.2rem;
  text-align: center;
  padding: 0.15rem 0;
}
.yuanqiu i.van-icon.van-icon-shopping-cart {
}
/*  * {
      touch-action: pan-y;
  } */
</style>
