<script setup lang="ts">
import type { UploadUserFile } from 'element-plus';

import { computed, ref } from 'vue';

import {
  ElButton,
  ElDrawer,
  ElInput,
  ElOption,
  ElSelect,
  ElUpload,
} from 'element-plus';

defineProps<{
  actionLoading: boolean;
  fieldOptions: { label: string; value: string }[];
  managedTables: any[];
  pendingUploadFile: File | null;
}>();

const emit = defineEmits<{
  (e: 'import'): void;
  (e: 'split'): void;
  (e: 'merge'): void;
  (e: 'derive'): void;
  (e: 'export'): void;
  (e: 'update:pendingUploadFile', file: File | null): void;
}>();

const visible = defineModel<boolean>('visible', { default: false });
const activeAction = ref<'derive' | 'export' | 'import' | 'merge' | 'split'>(
  'import',
);

const splitForm = defineModel<any>('splitForm', { required: true });
const mergeForm = defineModel<any>('mergeForm', { required: true });
const deriveForm = defineModel<any>('deriveForm', { required: true });
const exportForm = defineModel<any>('exportForm', { required: true });

const drawerTitle = computed(() => {
  const titles: Record<string, string> = {
    import: '导入 Excel',
    split: '拆分数据',
    merge: '合并数据',
    derive: '生成新表',
    export: '导出数据',
  };
  return titles[activeAction.value] || '数据操作';
});

const deriveRenamePlaceholder = '字段重命名 JSON，例如 {"old":"new"}';
const deriveFilterPlaceholder =
  '筛选条件 JSON，例如 [{"column":"status","operator":"EQ","value":"OPEN"}]';

function open(action: 'derive' | 'export' | 'import' | 'merge' | 'split') {
  activeAction.value = action;
  visible.value = true;
}

function handleUploadChange(file: UploadUserFile) {
  emit('update:pendingUploadFile', file.raw || null);
}

function handleConfirm() {
  const action = activeAction.value;
  switch (action) {
    case 'derive': {
      emit('derive');
      break;
    }
    case 'export': {
      emit('export');
      break;
    }
    case 'import': {
      emit('import');
      break;
    }
    case 'merge': {
      emit('merge');
      break;
    }
    case 'split': {
      emit('split');
      break;
    }
  }
}

defineExpose({ open });
</script>

<template>
  <ElDrawer
    v-model="visible"
    :title="drawerTitle"
    size="480px"
    destroy-on-close
  >
    <div class="action-form">
      <!-- 导入 -->
      <template v-if="activeAction === 'import'">
        <ElUpload
          drag
          :auto-upload="false"
          :show-file-list="true"
          :limit="1"
          :on-change="handleUploadChange"
        >
          <div class="upload-hint">拖拽或点击上传 Excel 文件</div>
        </ElUpload>
      </template>

      <!-- 拆分 -->
      <template v-if="activeAction === 'split'">
        <ElSelect v-model="splitForm.splitMode">
          <ElOption label="按行数" value="BY_ROW_COUNT" />
          <ElOption label="按字段值" value="BY_FIELD_VALUE" />
          <ElOption label="按工作表" value="BY_SHEET" />
        </ElSelect>
        <ElInput
          v-model="splitForm.targetNamePrefix"
          placeholder="新表名前缀"
        />
        <ElInput
          v-if="splitForm.splitMode === 'BY_ROW_COUNT'"
          v-model="splitForm.rowBatchSize"
          placeholder="每份行数"
        />
        <ElSelect
          v-if="splitForm.splitMode === 'BY_FIELD_VALUE'"
          v-model="splitForm.fieldName"
          placeholder="选择拆分字段"
        >
          <ElOption
            v-for="item in fieldOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </ElSelect>
      </template>

      <!-- 合并 -->
      <template v-if="activeAction === 'merge'">
        <ElSelect v-model="mergeForm.mergeMode">
          <ElOption label="纵向合并" value="VERTICAL" />
          <ElOption label="横向合并" value="HORIZONTAL" />
        </ElSelect>
        <ElSelect
          v-model="mergeForm.tableIds"
          multiple
          collapse-tags
          placeholder="选择要合并的表"
        >
          <ElOption
            v-for="item in managedTables"
            :key="item.id"
            :label="item.tableName"
            :value="item.id"
          />
        </ElSelect>
        <ElInput v-model="mergeForm.targetTableName" placeholder="新表名称" />
        <ElInput
          v-if="mergeForm.mergeMode === 'HORIZONTAL'"
          v-model="mergeForm.joinKey"
          placeholder="关联字段"
        />
      </template>

      <!-- 生成新表 -->
      <template v-if="activeAction === 'derive'">
        <ElInput v-model="deriveForm.targetTableName" placeholder="新表名称" />
        <ElInput
          v-model="deriveForm.selectedColumnsText"
          placeholder="保留字段，多个字段用逗号分隔"
        />
        <ElInput
          v-model="deriveForm.renameMappingsText"
          type="textarea"
          :rows="4"
          :placeholder="deriveRenamePlaceholder"
        />
        <ElInput
          v-model="deriveForm.filtersText"
          type="textarea"
          :rows="5"
          :placeholder="deriveFilterPlaceholder"
        />
      </template>

      <!-- 导出 -->
      <template v-if="activeAction === 'export'">
        <ElSelect v-model="exportForm.exportScope">
          <ElOption label="当前表" value="TABLE" />
          <ElOption label="当前库" value="WORKBOOK" />
        </ElSelect>
        <ElInput v-model="exportForm.fileName" placeholder="导出文件名，可选" />
      </template>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <ElButton @click="visible = false">取消</ElButton>
        <ElButton
          type="primary"
          :loading="actionLoading"
          @click="handleConfirm"
        >
          {{
            activeAction === 'import'
              ? '开始导入'
              : activeAction === 'split'
                ? '开始拆分'
                : activeAction === 'merge'
                  ? '开始合并'
                  : activeAction === 'derive'
                    ? '开始生成'
                    : '生成并下载'
          }}
        </ElButton>
      </div>
    </template>
  </ElDrawer>
</template>

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

.upload-hint {
  padding: 24px;
  font-size: 14px;
  color: hsl(var(--text-muted));
}

.drawer-footer {
  display: flex;
  gap: 8px;
  align-items: center;
}
</style>
