import { useResource } from "@/modules/resource";
import { Button, Empty } from "ant-design-vue";
import { queenApi, useModal } from "queenjs";
import { defineComponent, reactive } from "vue";
import { useRoute } from "vue-router";
import OutputTemplateItem from "./OutputTemplateItem";

export default defineComponent({
  setup() {
    const resource = useResource();
    const modal = useModal();
    const route = useRoute();

    const state = reactive({
      images: [] as { id: string; qos: number }[],
      videos: [] as { id: string; qos: number }[],
    });

    const submit = async () => {
      if (state.images.length == 0 && state.videos.length == 0) {
        queenApi.messageError("请选择至少一个模板");
        return;
      }
      const isOk = await resource.actions.submitRender(
        route.params.id as string,
        state.images,
        state.videos
      );
      if (isOk) {
        modal.submit(true);
      }
    };

    const selectTmp = (record: { id: string }, type = "image") => {
      const list = type == "image" ? state.images : state.videos;

      const selected = !!list.find((v: any) => v.id == record.id);
      if (selected) {
        const index = list.findIndex((d: any) => d.id == record.id);
        list.splice(index);
        return;
      }
      list.push({ id: record.id, qos: 1 });
    };

    const changeQos = (record: { id: string }, qos: number, type = "image") => {
      const list = type == "image" ? state.images : state.videos;
      const selected = list.find((v: any) => v.id == record.id);
      if (!selected) return;
      selected.qos = qos;
    };

    return () => {
      const { sourceDetail } = resource.store;
      const isEmpty =
        sourceDetail.images?.length == 0 && sourceDetail.videos?.length == 0;

      return (
        <div>
          {isEmpty && <Empty description="暂无数据" />}
          <div class="grid grid-cols-4 gap-10px">
            {sourceDetail.images?.map((record: any) => (
              <OutputTemplateItem
                record={record}
                active={!!state.images.find((v: any) => v.id == record.id)}
                onChange={(qos) => changeQos(record, qos)}
                onSelect={() => selectTmp(record)}
              />
            ))}
            {sourceDetail.videos?.map((record: any) => (
              <OutputTemplateItem
                type="video"
                record={record}
                active={!!state.videos.find((v: any) => v.id == record.id)}
                onChange={(qos) => changeQos(record, qos, "video")}
                onSelect={() => selectTmp(record, "video")}
              />
            ))}
          </div>

          <div class="text-right mt-10px">
            <Button onClick={modal.cancel}>取消</Button>
            <Button type="primary" class="ml-20px" onClick={submit}>
              确定
            </Button>
          </div>
        </div>
      );
    };
  },
});
