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({
      list: [] as { id: string; qos: 1 }[],
    }) as any;

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

    return () => {
      return (
        <div>
          {resource.store.sourceDetail.images.length == 0 && (
            <Empty description="暂无数据" />
          )}
          <div class="grid grid-cols-4 gap-10px">
            {resource.store.sourceDetail.images.map((record: any) => (
              <OutputTemplateItem
                record={record}
                class="cursor-pointer"
                active={!!state.list.find((v: any) => v.id == record.id)}
                onChange={(qos) => {
                  const selected = state.list.find(
                    (v: any) => v.id == record.id
                  );
                  selected.qos = qos;
                }}
                onSelect={() => {
                  const selected = !!state.list.find(
                    (v: any) => v.id == record.id
                  );
                  if (selected) {
                    const index = state.list.findIndex(
                      (d: any) => d.id == record.id
                    );
                    state.list.splice(index);
                    return;
                  }
                  state.list.push({ id: record.id, qos: 1 });
                }}
              />
            ))}
          </div>

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