<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { EasyFlowPanelModal } from '@easyflow/common-ui';

import { ElButton } from 'element-plus';

import PageData from '#/components/page/PageData.vue';
import { $t } from '#/locales';
import ResourceCardList from '#/views/ai/resource/ResourceCardList.vue';

const props = defineProps({
  attrName: {
    type: String,
    required: true,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  resourceType: {
    type: Number,
    default: undefined,
  },
});

const emit = defineEmits(['choose']);

const pageDataRef = ref();
const dialogVisible = ref(false);
const chooseResources = ref([]);
const currentChoose = ref<any>({});
const pageUrl = computed(() => {
  const baseUrl = '/api/v1/resource/page';
  return props.resourceType === undefined
    ? baseUrl
    : `${baseUrl}?resourceType=${props.resourceType}`;
});
function openDialog() {
  if (props.disabled) {
    return;
  }
  dialogVisible.value = true;
}
function closeDialog() {
  dialogVisible.value = false;
}
function confirm() {
  emit(
    'choose',
    props.multiple ? chooseResources.value : currentChoose.value,
    props.attrName,
  );
  closeDialog();
}
watch(
  () => chooseResources.value,
  (newValue) => {
    currentChoose.value = newValue.length > 0 ? newValue[0] : {};
  },
);
</script>

<template>
  <div>
    <EasyFlowPanelModal
      v-model:open="dialogVisible"
      :title="$t('aiResource.choose')"
      :before-close="closeDialog"
      width="80%"
    >
      <PageData
        ref="pageDataRef"
        :page-url="pageUrl"
        :page-size="8"
        :page-sizes="[8, 12, 16, 20]"
      >
        <template #default="{ pageList }">
          <ResourceCardList
            v-model="chooseResources"
            :data="pageList"
            :multiple="props.multiple"
          />
        </template>
      </PageData>
      <template #footer>
        <ElButton @click="closeDialog">
          {{ $t('button.cancel') }}
        </ElButton>
        <ElButton type="primary" @click="confirm">
          {{ $t('button.confirm') }}
        </ElButton>
      </template>
    </EasyFlowPanelModal>
    <ElButton :disabled="disabled" @click="openDialog()">
      {{ $t('button.choose') }}
    </ElButton>
  </div>
</template>

<style scoped></style>
