import {
  isWeixin
} from '@/common/utils/common';
import {
  webViewHref,
  navToPage,
  crossPage
} from '@/common/utils/navPag';
import {
  firstPerform
} from "js-perform-lock";
import store from '@/store/index.js'

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

// #ifdef H5
import wx from 'weixin-js-sdk'
// #endif

// 微信小程序页面劫持
export const goLoginPage = (new firstPerform(1000)).refactor(function (pageObj) {
  navToPage({
    url: pageObj ? ("/pages/login/indexs?pageObj=" + encodeURIComponent(pageObj)) : "/pages/login/indexs"
  }, "navigateTo")
  // store.dispatch('user/resetToken')
});

// #ifdef MP-WEIXIN
export const routerBeforeEach = (new firstPerform(200)).refactor(function () {
  function getrouter() {
    let routes = getCurrentPages();
    if (routes.length) {
      let curRoute = routes[routes.length - 1].route
      let whitePages = [
        'pages/login/index',
        'pages/login/indexs',
        'pages/index/index',
        'pages/goods/index',
        'pages/mine/index',
      ]
      if (!store.getters.token && whitePages.indexOf(curRoute) == -1) {
        goLoginPage()
      }
    } else {
      setTimeout(getrouter, 300)
    }
  }
  getrouter()
});
// #endif

const updatePageLay = function () {
  var uni_page_head = document.querySelector("uni-page-head[uni-page-head-type='default']")
  if (uni_page_head) {
    uni_page_head.remove()
  }
}

// (new firstPerform(1000)).refactor(function() {
//   // 去除顶部
//   var uni_page_head = document.querySelector("uni-page-head[uni-page-head-type='default']")
//   if (uni_page_head) {
//     uni_page_head.remove()
//   }
//   // 去除底部
//   // var uni_tabbar_bottom = document.getElementsByClassName("uni-tabbar-bottom")
//   // if (uni_tabbar_bottom.length) {
//   //   uni_tabbar_bottom[0].remove()
//   //   var uni_page_wrapper = document.getElementsByTagName("uni-page-wrapper")
//   //   if (uni_page_wrapper.length) {
//   //     loadStyleString(
//   //       "uni-page-wrapper{height: calc(100% - env(safe-area-inset-bottom)) !important} uni-page-wrapper::after{height: env(safe-area-inset-bottom) !important}"
//   //     );
//   //   }
//   // }
// });

window.backPage = function () {
  // 获取当前页面栈的实例数组
  const pages = getCurrentPages();

  if(pages.length > 1) {
    navToPage({delta: 1}, 'navigateBack')
  }else {
    var searchParams = window.location.search;
    navToPage({url: `/pages/index/index${searchParams}`}, 'reLaunch')
  }
}

// 插入样式
function loadStyleString(css) {
  var style = document.createElement("style");
  style.type = "text/css";
  try {
    style.appendChild(document.createTextNode(css));
  } catch (ex) {
    style.styleSheet.cssText = css;
  }
  var head = document.getElementsByTagName('head')[0];
  head.appendChild(style);
}

var insertFloatButton = (function () {
  var isDragging = false;
  var offsetX, offsetY;
  var div;
  let blackList = [`${process.env.VUE_APP_BASE_PATH}pages/index/index`, `${process.env.VUE_APP_BASE_PATH}pages/workorder/index`, `${process.env.VUE_APP_BASE_PATH}pages/goods/index`, `${process.env.VUE_APP_BASE_PATH}pages/mine/index`];

  // 获取手机信息配置接口
  const sys = uni.getSystemInfoSync();
  // 屏幕的宽高
  var windowWidth = sys.windowWidth;
  var windowHeight = sys.windowHeight;
  // 设置边界值
  var edge = 10;
  // 设置块宽度
  var divWidth = 52;


  // 触摸移动时更新块的位置
  document.addEventListener('touchmove', function (event) {
    event.stopPropagation();

    if (div && isDragging) {
      var touch = event.touches[0];

      div.style.left = touch.pageX - offsetX + 'px';

      let clientY = touch.clientY - divWidth;

      let edgeBottom = windowHeight - (divWidth * 2) - edge;

      let moveTop = 0;
      // 上下触及边界
      if (clientY < edge) {
        moveTop = edge;
      } else if (clientY > edgeBottom) {
        moveTop = edgeBottom;
      } else {
        moveTop = clientY
      }
      div.style.top = moveTop + 'px';

      setStorage('top', moveTop);
    }
  });

  // 触摸结束时停止拖动
  document.addEventListener('touchend', function (event) {
    event.stopPropagation();

    let edgeRigth = windowWidth - divWidth - edge;

    let moveLeft = div.style.left;
    // 左右触及边界
    if (moveLeft < windowWidth / 2 - divWidth) {
      moveLeft = edge;
    } else {
      moveLeft = edgeRigth;
    }
    div.style.left = moveLeft + 'px';

    setStorage('left', moveLeft);

    isDragging = false;
    // div.style.cursor = 'grab';
  });

  return function () {
    // 设置默认值
    if (!getStorage('left')) {
      setStorage('left', windowWidth - divWidth - edge);
    }
    if (!getStorage('top')) {
      setStorage('top', windowHeight - (divWidth * 2) - edge - 100);
    }

    let hasDiv = document.getElementById('floatButtonBox');
    let isBlack = blackList.includes(window.location.pathname);
    if (isBlack && hasDiv) {
      hasDiv.remove()
    } else if (!isBlack && !hasDiv) {

      // 获取当前页面的查询参数
      var searchParams = window.location.search;

      div = document.createElement('div');
      div.id = 'floatButtonBox';
      div.style.width = divWidth + 'px';
      div.style.position = 'fixed';
      div.style.top = getStorage('top') + 'px';
      div.style.left = getStorage('left') + 'px';
      div.style.zIndex = '99999';
      div.innerHTML = `
        <img style="width: 100%; height: 100%; display: block;" src='${process.env.VUE_APP_BASE_PATH}static/icon/floatButton1.png' onclick="(function(){navToPage({url: '/pages/index/index${searchParams}'}, 'reLaunch')})()"/>
        <img style="width: 100%; height: 100%; display: block;" src='${process.env.VUE_APP_BASE_PATH}static/icon/floatButton2.png' onclick="backPage()"/>
    `;
      // 鼠标按下时开始拖动
      div.addEventListener('touchstart', function (event) {
        event.stopPropagation();

        isDragging = true;
        var touch = event.touches[0];
        offsetX = touch.pageX - div.getBoundingClientRect().left;
        offsetY = touch.pageY - div.getBoundingClientRect().top;
        // div.style.cursor = 'grabbing';
      });
      document.body.appendChild(div);
    }
  }
})()

// 存放页面公用数据、方法...
export default {
  data() {
    return {
      crossPage: crossPage,
    }
  },
  computed: {
    crossPagePam() {
      var num = this.$store.state.user.crossPagePam || 0
      var city = this.$store.state.user.city || ''
      var province = this.$store.state.user.province || ''
      var data = getStorage("crossPageTs")
      return {
        crossPageTs: data,
        timestamp: num,
        city: city,
        province: province,
      }
    }
  },
  onLoad() {
    // #ifdef MP-WEIXIN
    // routerBeforeEach()
    // #endif
  },

  onShow() {
    insertFloatButton()
    // const originalTitle = document.title;
    // const fixedDescription = ` - ${'商户名称'}`;
    // if(!~document.title.indexOf(fixedDescription)){
    //   document.title = originalTitle + fixedDescription;
    // }
  },

  mounted() {
    // #ifdef MP-WEIXIN
    // routerBeforeEach()
    // #endif
    if (isWeixin()) {
      updatePageLay()
    }
  },
  methods: {
    webViewHref: webViewHref,
  }
}
