import { useEditor } from "@/modules/editor";
import { initResource, useResource } from "@/modules/resource";
import { css } from "@linaria/core";
import { Image, List, Loadmore } from "@queenjs/ui";
import { Radio } from "ant-design-vue";
import { defineComponent, reactive } from "vue";

export const MySources = defineComponent({
  setup() {
    const editor = useEditor();
    const resource = useResource();
    const state = reactive({
      sourceType: "Image" as "Image" | "Video",
    });

    function getCurrCtrl() {
      return resource.controls[
        state.sourceType === "Image"
          ? "materialImageListCtrl"
          : "materialVideoListCtrl"
      ];
    }

    function switchSource(v: "Image" | "Video") {
      state.sourceType = v;
      const ctrl = getCurrCtrl();
      ctrl.hasLimit = true;
      ctrl.loadPage(1);
    }

    function clickToDesign(url: string) {
      editor.actions.clickCompToDesign(state.sourceType, (comp) => {
        comp.value.url = url;
      });
    }

    switchSource("Image");

    return () => {
      const control =
        resource.controls[
          state.sourceType === "Image"
            ? "materialImageListCtrl"
            : "materialVideoListCtrl"
        ];
      return (
        <div class="space-y-20px -mt-10px flex flex-col overflow-hidden">
          <Radio.Group
            class={radioCls}
            value={state.sourceType}
            size="small"
            onChange={(e) => switchSource(e.target.value)}
          >
            <Radio.Button value="Image">图片</Radio.Button>
            <Radio.Button value="Video">视频</Radio.Button>
          </Radio.Group>
          <div class="scrollbar flex-1 -mr-15px pr-15px">
            <List data={control.state.list} columns={2} gap="20px">
              {{
                item(item: any) {
                  return (
                    <div
                      style={{ aspectRatio: 1 }}
                      onClick={() => clickToDesign(item.file.url)}
                    >
                      <Image
                        class="w-full h-full"
                        src={item.file.url}
                        size={240}
                      />
                    </div>
                  );
                },
                loadmore() {
                  return (
                    <Loadmore
                      class="mt-20px"
                      loading={control.state.loading}
                      canLoad={control.state.canLoadNext}
                      onChange={control.loadNextPage}
                    />
                  );
                },
              }}
            </List>
          </div>
        </div>
      );
    };
  },
});

const radioCls = css`
  display: flex;
  > label {
    flex: 1;
    width: 0;
    text-align: center;
  }
`;
