import type { Ref } from 'vue';

import { reactive, ref } from 'vue';

import { downloadFileFromBlob } from '@easyflow/utils';

import { ElMessage } from 'element-plus';

import { api } from '#/api/request';

export function useDatacenterExcel(
  selectedSourceId: Ref<null | number>,
  selectedCatalogId: Ref<null | number>,
  selectedTableId: Ref<null | number>,
  reloadAll: () => Promise<void>,
) {
  const actionLoading = ref(false);
  const pendingUploadFile = ref<File | null>(null);

  const splitForm = reactive({
    splitMode: 'BY_ROW_COUNT',
    rowBatchSize: 1000,
    fieldName: '',
    targetNamePrefix: '',
  });

  const mergeForm = reactive({
    mergeMode: 'VERTICAL',
    tableIds: [] as number[],
    targetTableName: '',
    joinKey: '',
  });

  const deriveForm = reactive({
    targetTableName: '',
    selectedColumnsText: '',
    renameMappingsText: '{}',
    filtersText: '[]',
  });

  const exportForm = reactive({
    fileName: '',
    exportScope: 'TABLE',
  });

  function resetSplitForm() {
    splitForm.splitMode = 'BY_ROW_COUNT';
    splitForm.rowBatchSize = 1000;
    splitForm.fieldName = '';
    splitForm.targetNamePrefix = '';
  }

  function resetMergeForm() {
    mergeForm.mergeMode = 'VERTICAL';
    mergeForm.tableIds = [];
    mergeForm.targetTableName = '';
    mergeForm.joinKey = '';
  }

  function resetDeriveForm() {
    deriveForm.targetTableName = '';
    deriveForm.selectedColumnsText = '';
    deriveForm.renameMappingsText = '{}';
    deriveForm.filtersText = '[]';
  }

  function resetExportForm() {
    exportForm.fileName = '';
    exportForm.exportScope = 'TABLE';
  }

  async function handleImport() {
    if (!pendingUploadFile.value) {
      ElMessage.warning('请先选择 Excel 文件');
      return false;
    }
    actionLoading.value = true;
    try {
      const formData = new FormData();
      formData.append('file', pendingUploadFile.value);
      await api.postFile('/api/v1/datacenterExcel/import', formData, {
        timeout: 10 * 60 * 1000,
      });
      ElMessage.success('Excel 已导入');
      pendingUploadFile.value = null;
      await reloadAll();
      return true;
    } finally {
      actionLoading.value = false;
    }
  }

  async function handleSplit() {
    if (!selectedTableId.value) return false;
    if (
      splitForm.splitMode === 'BY_ROW_COUNT' &&
      Number(splitForm.rowBatchSize) <= 0
    ) {
      ElMessage.warning('每份行数必须大于 0');
      return false;
    }
    if (splitForm.splitMode === 'BY_FIELD_VALUE' && !splitForm.fieldName) {
      ElMessage.warning('请选择拆分字段');
      return false;
    }
    actionLoading.value = true;
    try {
      await api.post('/api/v1/datacenterExcel/split', {
        datasetRef: { tableId: selectedTableId.value },
        sourceId: selectedSourceId.value,
        catalogId: selectedCatalogId.value,
        splitMode: splitForm.splitMode,
        rowBatchSize: Number(splitForm.rowBatchSize),
        fieldName: splitForm.fieldName,
        targetNamePrefix: splitForm.targetNamePrefix,
      });
      ElMessage.success('拆分已完成');
      await reloadAll();
      return true;
    } finally {
      actionLoading.value = false;
    }
  }

  async function handleMerge() {
    if (mergeForm.tableIds.length < 2) {
      ElMessage.warning('请至少选择两个已接入表');
      return false;
    }
    if (!mergeForm.targetTableName.trim()) {
      ElMessage.warning('请输入新表名称');
      return false;
    }
    if (mergeForm.mergeMode === 'HORIZONTAL' && !mergeForm.joinKey.trim()) {
      ElMessage.warning('横向合并需要填写关联字段');
      return false;
    }
    actionLoading.value = true;
    try {
      await api.post('/api/v1/datacenterExcel/merge', {
        datasetRefs: mergeForm.tableIds.map((tableId) => ({ tableId })),
        mergeMode: mergeForm.mergeMode,
        targetTableName: mergeForm.targetTableName.trim(),
        joinKey: mergeForm.joinKey.trim(),
      });
      ElMessage.success('合并已完成');
      await reloadAll();
      return true;
    } finally {
      actionLoading.value = false;
    }
  }

  async function handleDerive() {
    if (!selectedTableId.value) return false;
    if (!deriveForm.targetTableName.trim()) {
      ElMessage.warning('请输入新表名称');
      return false;
    }
    const selectedColumns = deriveForm.selectedColumnsText
      ? deriveForm.selectedColumnsText
          .split(',')
          .map((item) => item.trim())
          .filter(Boolean)
      : [];

    let renameMappings: Record<string, string>;
    let filters: any[];
    try {
      renameMappings = deriveForm.renameMappingsText
        ? JSON.parse(deriveForm.renameMappingsText)
        : {};
      filters = deriveForm.filtersText
        ? JSON.parse(deriveForm.filtersText)
        : [];
    } catch {
      ElMessage.error('生成参数格式不正确，请检查输入内容');
      return false;
    }

    actionLoading.value = true;
    try {
      await api.post('/api/v1/datacenterExcel/derive', {
        datasetRef: { tableId: selectedTableId.value },
        targetTableName: deriveForm.targetTableName.trim(),
        selectedColumns,
        renameMappings,
        filters,
      });
      ElMessage.success('新表已生成');
      await reloadAll();
      return true;
    } finally {
      actionLoading.value = false;
    }
  }

  async function handleExport(loadTableRuntime: () => Promise<void>) {
    if (exportForm.exportScope === 'TABLE' && !selectedTableId.value) {
      ElMessage.warning('请先选择已接入表');
      return false;
    }
    actionLoading.value = true;
    try {
      const res = await api.post('/api/v1/datacenterExcel/export', {
        sourceId:
          exportForm.exportScope === 'WORKBOOK'
            ? selectedSourceId.value
            : undefined,
        catalogId:
          exportForm.exportScope === 'WORKBOOK'
            ? selectedCatalogId.value
            : undefined,
        datasetRefs:
          exportForm.exportScope === 'TABLE' && selectedTableId.value
            ? [{ tableId: selectedTableId.value }]
            : [],
        fileName: exportForm.fileName.trim(),
      });
      const blob = await api.download('/api/v1/datacenterExcel/download', {
        params: { jobId: res.data.id },
      });
      downloadFileFromBlob({
        fileName:
          res.data.fileName || exportForm.fileName || 'datacenter-export.xlsx',
        source: blob,
      });
      ElMessage.success('导出文件已生成');
      await loadTableRuntime();
      return true;
    } finally {
      actionLoading.value = false;
    }
  }

  return {
    actionLoading,
    pendingUploadFile,
    splitForm,
    mergeForm,
    deriveForm,
    exportForm,
    resetSplitForm,
    resetMergeForm,
    resetDeriveForm,
    resetExportForm,
    handleImport,
    handleSplit,
    handleMerge,
    handleDerive,
    handleExport,
  };
}
