import { css, cx } from "@linaria/core";
import { defineComponent, inject } from "vue";
import { bool, string } from "vue-types";
import { CompCardObj } from ".";
import { CompUI } from "../..";
import { useEditor } from "../../../..";
import { DesignComp } from "../../../../objects/DesignTemp/DesignComp";
import { useCompData } from "../../defines/hook";
import { View } from "../View";

export const Component = defineComponent({
  props: {
    compId: string().isRequired,
    showMask: bool().def(false),
    meta: bool().def(true),
  },
  setup(props) {
    const { helper, controls, store } = useEditor();
    const comp = useCompData<CompCardObj>(props.compId);
    const isStreamCard = helper.isStreamCard(props.compId);
    const isPreview = inject("isPreview", false);
    const isShowSwiper = () => {
      const { value } = controls.pageCtrl.rootPage;
      return value.pageMode == "short" && isPreview;
    };

    const getContainerStyles = () => {
      const rootPage = controls.pageCtrl.rootPage;
      const isPcDesign = rootPage.value.useFor == "pc";
      const isShortDesign = rootPage.value.pageMode == "short";

      const style: any = {};
      // 翻页
      if (isStreamCard && isShortDesign && store.isDisplay) {
        if (!isPcDesign) {
          style.height = "100%";
          style.width = "100%";
        } else {
          style.height = "100vh";
          style.width = "100vw";
        }

        style.display = "flex";
        style.justifyContent = "center";
        style.alignItems = "center";
      }
      return style;
    };

    const createScale = () => {
      const showSwiper = isShowSwiper();
      if (!showSwiper) return;
      const scale = controls.previewCtrl.state.scale;
      const style = { transform: `scale(${scale})` };
      return style;
    };

    return () => {
      const showSwiper = isShowSwiper();
      const containerStyles = getContainerStyles();
      const containerScale = createScale();

      const rootPage = controls.pageCtrl.rootPage;

      return (
        <div
          class={cx(rootStyles, showSwiper && "swiper-slide")}
          style={containerStyles}
          key={rootPage.children.default.indexOf(props.compId) + props.compId}
        >
          <View
            class="JS_viewRoot"
            compId={props.compId}
            style={containerScale}
            showMask={props.showMask}
            meta={props.meta}
          >
            {comp.children.default?.map((compId, index) => {
              const compItem = helper.findComp(compId) as DesignComp;
              const Comp =
                controls.compUICtrl.state.components.get(compItem?.compKey)
                  ?.Component || CompUI.Container.Component;
              if (!compItem) return;
              return <Comp key={compItem?.id + index} compId={compItem?.id} />;
            })}
          </View>
        </div>
      );
    };
  },
});

const rootStyles = css`
  &.swiper-slide-active {
    z-index: 10;
  }
`;
