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

import { EasyFlowFormModal } from '@easyflow/common-ui';
import { $t } from '@easyflow/locales';

import { ElMessage } from 'element-plus';

import { api } from '#/api/request';
import ImportKnowledgeFileContainer from '#/views/ai/documentCollection/ImportKnowledgeFileContainer.vue';
import { buildKnowledgePath } from '#/views/ai/documentCollection/share-path';

const props = defineProps({
  requestClient: {
    type: Object as any,
    default: () => api,
  },
  endpointPrefix: {
    type: String,
    default: '',
  },
  knowledgeIdProp: {
    type: String,
    default: '',
  },
});

const emits = defineEmits(['imported']);

const route = useRoute();
const fileUploadRef = ref<InstanceType<typeof ImportKnowledgeFileContainer>>();
const dialogVisible = ref(false);
const submitting = ref(false);

const knowledgeId = computed(
  () => props.knowledgeIdProp || (route.query.id as string) || '',
);

const resetDialogState = () => {
  fileUploadRef.value?.reset?.();
};

const closeDialog = () => {
  if (submitting.value) {
    return false;
  }
  dialogVisible.value = false;
  resetDialogState();
  return true;
};

const openDialog = () => {
  resetDialogState();
  dialogVisible.value = true;
};

const createTasks = async () => {
  const files = fileUploadRef.value?.getFilesData?.() || [];
  if (files.length === 0) {
    ElMessage.error($t('message.uploadFileFirst'));
    return;
  }

  submitting.value = true;
  let successCount = 0;
  let failedCount = 0;

  try {
    for (const file of files) {
      try {
        const res = await props.requestClient.post(
          buildKnowledgePath(
            props.endpointPrefix,
            '/api/v1/document/import/task/create',
          ),
          {
            knowledgeId: knowledgeId.value,
            fileName: file.fileName,
            filePath: file.filePath,
          },
        );
        if (res.errorCode === 0) {
          successCount += 1;
        } else {
          failedCount += 1;
        }
      } catch {
        failedCount += 1;
      }
    }

    if (successCount > 0) {
      ElMessage.success(
        failedCount > 0
          ? $t('documentCollection.importDoc.partialCreateSuccess')
          : $t('documentCollection.importDoc.createSuccess'),
      );
      dialogVisible.value = false;
      resetDialogState();
      emits('imported');
      return;
    }

    ElMessage.error($t('documentCollection.importDoc.importFailed'));
  } finally {
    submitting.value = false;
  }
};

defineExpose({
  closeDialog,
  openDialog,
});
</script>

<template>
  <EasyFlowFormModal
    v-model:open="dialogVisible"
    :title="$t('button.importFile')"
    :before-close="closeDialog"
    :closable="!submitting"
    :centered="true"
    :confirm-loading="submitting"
    :confirm-text="$t('button.importFile')"
    :submitting="submitting"
    width="xl"
    @confirm="createTasks"
  >
    <div class="import-dialog">
      <p class="import-dialog__tip">
        {{ $t('documentCollection.importDoc.uploadCreateTip') }}
      </p>

      <ImportKnowledgeFileContainer ref="fileUploadRef" />
    </div>
  </EasyFlowFormModal>
</template>

<style scoped>
.import-dialog {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.import-dialog__tip {
  margin: 0;
  font-size: 14px;
  line-height: 22px;
  color: var(--el-text-color-secondary);
}

:deep(.upload-demo) {
  width: 100%;
}

:deep(.upload-demo .el-upload) {
  width: 100%;
}

:deep(.upload-demo .el-upload-dragger) {
  padding: 24px 20px;
  border-radius: 18px;
  box-shadow: none;
}

:deep(.upload-demo .el-icon) {
  margin-bottom: 8px;
}

:deep(.el-table) {
  --el-table-border-color: transparent;
}

:deep(.el-table__inner-wrapper::before) {
  display: none;
}

:deep(.el-table th.el-table__cell) {
  padding-top: 10px;
  padding-bottom: 10px;
  background: transparent;
}

:deep(.el-table td.el-table__cell) {
  padding-top: 10px;
  padding-bottom: 10px;
}
</style>
