<script lang="ts">
  import { defineComponent, toRefs, ref, unref } from 'vue';
  import { createAppProviderContext } from './useAppContext';
  import { createBreakpointListen } from '/@/hooks/event/useBreakpoint';
  import { prefixCls } from '/@/settings/designSetting';

  const props = {
    /**
     * class style prefix
     */
    prefixCls: { type: String, default: prefixCls },
  };
  export default defineComponent({
    name: 'AppProvider',
    inheritAttrs: false,
    props,
    setup(props, { slots }) {
      const isMobile = ref(false);
      const isSetState = ref(false);

      // 监控屏幕断点信息变化
      createBreakpointListen(({ screenMap, sizeEnum, width }) => {
        const lgWidth = screenMap.get(sizeEnum.LG);
        if (lgWidth) {
          isMobile.value = width.value - 1 < lgWidth;
        }
        handleRestoreState();
      });

      const { prefixCls } = toRefs(props);

      // 将变量注入全局
      createAppProviderContext({ prefixCls, isMobile });

      /**
       * 用于保持窗口变化前的状态
       */
      function handleRestoreState() {
        if (unref(isMobile)) {
          if (!unref(isSetState)) {
            isSetState.value = true;
          }
        } else {
          if (unref(isSetState)) {
            isSetState.value = false;
          }
        }
      }
      return () => slots.default?.();
    },
  });
</script>
