/* eslint-disable @typescript-eslint/no-empty-function */
/**
 * 生命周期处理函数
 */
import * as React from 'react';
import { throttle } from 'lodash-es';
import * as querystring from 'query-string';
import { IPageAPI } from '../app/global-api';
import { runtime } from './adapter';

const noops = () => {};

const APPLIFECYCLE = {
  onAppShow: noops,
  onAppHide: noops,
  onAppError: noops,
  onAppUnhandledRejection: noops,
  onAppLaunch: noops,
  beforeCustomLaunch: noops,
};
// 小程序 端使用lifeCycle
let alreadyInitAppLifeCycle = false;
let _HANDLER_MAP = {};
export function initAppLifeCycle(app, appLifeCycle) {
  appLifeCycle = { ...APPLIFECYCLE, ...appLifeCycle };
  const onAppLaunch = async (query) => {
    await appLifeCycle?.beforeCustomLaunch(query);
    await appLifeCycle?.onAppLaunch(query);
  };
  const onAppShow = async (query) => {
    await appLifeCycle?.onAppShow(app.getLaunchOptionsSync());
  };
  // 应用级别事件监听
  if (!alreadyInitAppLifeCycle) {
    onAppLaunch(app.getLaunchOptionsSync());
    onAppShow(app.getLaunchOptionsSync());

    // 预留等客户端来触发
    _HANDLER_MAP = {
      appShow: (...args) => appLifeCycle.onAppShow(...args),
      appHide: (...args) => appLifeCycle.onAppHide(...args),
      error: (...args) => appLifeCycle.onAppError(...args),
      unhandledrejection: (event) => appLifeCycle.onAppUnhandledRejection(event?.reason),
    };
    for (const event in _HANDLER_MAP) {
      runtime.addEventListener(event, _HANDLER_MAP[event]);
    }
    alreadyInitAppLifeCycle = true;
  }
}

export function removeAppLifeCycle() {
  for (const event in _HANDLER_MAP) {
    runtime.removeEventListener(event, _HANDLER_MAP[event]);
  }
  _HANDLER_MAP = {};
  alreadyInitAppLifeCycle = false;
}

let isReachBottom = false;
// web 端使用lifeCycle
export function usePageLifeCycle(
  {
    beforePageCustomLaunch = function (query) {},
    onPageLoad = function (query) {},
    onPageShow = function () {},
    onPageReady = function () {},
    onPageHide = function () {},
    onPageUnload = function () {},
    onPullDownRefresh = function () {},
    onReachBottom = function () {},
    onShareAppMessage = function () {},
    onPageScroll = function () {},
    onResize = function () {},
    onAddToFavorites = function () {},
    onShareTimeline = function () {},
    onTabItemTap = function () {},
  },
  context: { app; page: IPageAPI; options },
) {
  runtime['$page'] = context.page;
  let reachBottomDistance = 50;
  try {
    const config = context.app.__internal__.getConfig().pages.find((page) => page.id === context.page.id);
    reachBottomDistance = config.reachBottomDistance;
    if (typeof reachBottomDistance !== 'number') {
      reachBottomDistance = 50;
    }
  } catch (e) {}

  React.useEffect(() => {
    const _onPageLoad = async function (query) {
      await beforePageCustomLaunch?.(query);
      return typeof onPageLoad === 'function' ? onPageLoad(query) : () => {};
    };
    try {
      _onPageLoad.call(context.page, getCurrentPageQuery());
      typeof onPageReady === 'function' && onPageReady.call(context.page);
      typeof onPageShow === 'function' && onPageShow.call(context.page);
    } catch (e) {
      if (!context.options?.looseError) {
        throw e;
      } else {
        console.error('Catched error:', e);
      }
    }

    return () => {
      try {
        typeof onPageHide === 'function' && onPageHide.call(context.page, {});
        typeof onPageUnload === 'function' && onPageUnload.call(context.page, {});
      } catch (e) {
        if (!context.options?.looseError) {
          throw e;
        } else {
          console.error('Catched error:', e);
        }
      }
    };
  }, []);

  React.useEffect(() => {
    if (typeof onPageScroll === 'function' || typeof onReachBottom === 'function') {
      runtime.onscroll = throttle(() => {
        // 变量scrollTop是滚动条滚动时，滚动条上端距离顶部的距离
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

        // 变量windowHeight是可视区的高度
        let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;

        // 变量scrollHeight是滚动条的总高度（当前可滚动的页面的总高度）
        let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
        if (typeof onPageScroll === 'function') {
          onPageScroll.call(context.page, {
            scrollTop: runtime.pageYOffset,
          });
        }

        // console.log(scrollTop, windowHeight, scrollTop + windowHeight, scrollHeight, isReachBottom)
        // 滚动条到底部
        if (scrollTop + windowHeight >= scrollHeight - reachBottomDistance) {
          // 要进行的操作
          if (!isReachBottom) {
            isReachBottom = true;
            if (typeof onReachBottom === 'function') {
              onReachBottom();
            }
          }
        } else {
          isReachBottom = false;
        }
      }, 300);
    }
    // todo
    if (typeof onShareAppMessage === 'function') {
      runtime['onShareAppMessage'] = onShareAppMessage.bind(context.page);
    }

    if (typeof onResize === 'function') {
      runtime.onresize = () => {
        onResize.call(context.page, {
          size: {
            windowWidth: runtime.innerWidth,
            windowHeight: runtime.innerHeight,
          },
        });
      };
    }
    return () => {
      runtime.onscroll = null;
      runtime.onresize = null;
    };
  }, []);
}

function getCurrentPageQuery() {
  let queryObj = querystring.parse((location.search || '').split('?')[1] || '') || {};
  let hashQueryObj = querystring.parse((location.hash || '').split('?')[1] || '') || {};
  let query = { ...hashQueryObj, ...queryObj };
  // query string parse decode succeess
  // Object.keys(query).forEach((key) => {
  //   query[key] = decodeURIComponent(query[key] as string);
  // });
  return query;
}

export function initWebConfig(app, appConfig) {
  // miniprogram.config 配置截取
  app.setConfig(appConfig);
}
