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

import { confirm, Page } from '@vben/common-ui';

import { Button, Drawer, Empty, List, message, Modal, Tag } from 'ant-design-vue';

import { JsonViewer } from '@vben/common-ui';

import { downloadByData } from '#/util/tool';
import {
  batchGenerationApi,
  codeGenerationDownloadApi,
  generationApi,
  getCodeGenerationListApi,
} from '#/views/code-generation/api';

import type { CodeGenData } from './utils/data-transformer';
import type { GenerationMode } from './utils/draft-manager';

import AiPrompt from './components/ai-prompt.vue';
import DatabaseSelect from './components/database-select.vue';
import JsonImport from './components/json-import.vue';
import ManualForm from './components/manual-form.vue';
import ModeSelector from './components/mode-selector.vue';

// 生成历史相关
interface GenerationHistory {
  id: number;
  title: string;
  file_name: string;
  path: string;
  params: any; // JSON对象
  created_at: string; // 已格式化的时间字符串
  updated_at: string;
}

const historyDrawerVisible = ref(false);
const historyList = ref<GenerationHistory[]>([]);
const historyLoading = ref(false);

// JSON详情查看
const jsonViewerVisible = ref(false);
const currentJsonData = ref<any>(null);

// 懒加载组件
const ModeSelectorComponent = defineAsyncComponent(() =>
  Promise.resolve(ModeSelector),
);
const JsonImportComponent = defineAsyncComponent(() =>
  Promise.resolve(JsonImport),
);
const ManualFormComponent = defineAsyncComponent(() =>
  Promise.resolve(ManualForm),
);
const DatabaseSelectComponent = defineAsyncComponent(() =>
  Promise.resolve(DatabaseSelect),
);
const AiPromptComponent = defineAsyncComponent(() =>
  Promise.resolve(AiPrompt),
);

// 当前模式
const currentMode = ref<GenerationMode | null>(null);

// 模式标题映射
const modeTitles: Record<GenerationMode, string> = {
  json: 'JSON导入模式',
  manual: '手动填写模式',
  database: '数据库表模式',
  ai: 'AI提示词模式',
};

// 选择模式
const handleSelectMode = (mode: GenerationMode) => {
  currentMode.value = mode;
};

// 返回模式选择
const handleBack = () => {
  currentMode.value = null;
};

// 生成代码（支持单个或批量）
const handleGenerate = async (data: CodeGenData | CodeGenData[]) => {
  try {
    // 判断是否为数组（批量生成）
    if (Array.isArray(data)) {
      const res = await batchGenerationApi(data);
      confirm({
        cancelText: '迟点下载',
        confirmText: '查看生成结果',
        content:
          `已成功生成 ${res.length} 个模块！\r\n` +
          '后端代码已经自动生成：\r\n' +
          '（Controller、Service、Model、Route、Mysql数据表），无需您操作。\r\n' +
          '您只需要把代码黏贴至 "您的根目录/apps/web-antd/src/views/my-gen"文件夹下即可使用',
        icon: 'success',
        title: '批量代码生成成功！',
      }).then(() => {
        // 批量下载所有生成的模块
        res.forEach((item: any, index: number) => {
          setTimeout(() => {
            codeGenerationDownloadApi(item.id).then((blob) => {
              downloadByData(blob, item.file_name, 'application/zip');
            });
          }, index * 500); // 延迟下载避免浏览器阻止
        });
      });
    } else {
      // 单个生成
      const res = await generationApi(data);
      confirm({
        cancelText: '迟点下载',
        confirmText: '是的，马上下载',
        content:
          '您的模块已经生成成功，是否立即下载？\r\n' +
          '后端代码已经自动生成：\r\n' +
          '（Controller、Service、Model、Route、Mysql数据表），无需您操作。\r\n' +
          '您只需要把代码黏贴至 "您的根目录/apps/web-antd/src/views/my-gen"文件夹下即可使用',
        icon: 'success',
        title: '代码生成成功！',
      }).then(() => {
        codeGenerationDownloadApi(res.id).then((blob) => {
          downloadByData(blob, res.file_name, 'application/zip');
        });
      });
    }
    // 生成成功后刷新历史记录
    if (historyDrawerVisible.value) {
      loadHistoryList();
    }
  } catch (error: any) {
    message.error(error.message || '代码生成失败');
  }
};

// 加载生成历史列表
const loadHistoryList = async () => {
  historyLoading.value = true;
  try {
    getCodeGenerationListApi({}).then((res) => {
      historyList.value = res.items;
    });
  } catch (error: any) {
    message.error(error.message || '加载历史记录失败');
    historyList.value = [];
  } finally {
    historyLoading.value = false;
  }
};

// 打开历史记录抽屉
const handleOpenHistory = () => {
  historyDrawerVisible.value = true;
  loadHistoryList();
};

// 下载历史记录
const handleDownloadHistory = async (item: GenerationHistory) => {
  try {

    // return console.log(item);
    codeGenerationDownloadApi(item.id).then((blob) => {
      downloadByData(blob, item.file_name, 'application/zip');
      message.success('下载成功');
    });
    // const blob = await codeGenerationDownloadApi(item.id);
    // downloadByData(blob, item.file_name, 'application/zip');
  } catch (error: any) {
    message.error(error.message || '下载失败');
  }
};

// 查看JSON详情
const handleViewJson = (item: GenerationHistory) => {
  currentJsonData.value = item.params;
  jsonViewerVisible.value = true;
};
</script>

<template>
  <Page
    :title="currentMode ? modeTitles[currentMode] : '代码生成器'"
    auto-content-height
  >
    <template #extra>
      <Button
        v-if="!currentMode"
        type="primary"
        @click="handleOpenHistory"
      >
        <i class="fa-solid fa-clock-rotate-left mr-2"></i>生成历史
      </Button>
    </template>
    <Transition name="fade-slide" mode="out-in">
      <!-- 模式选择界面 -->
      <div v-if="!currentMode" key="selector" class="mode-selector-container">
        <div class="flex min-h-[calc(100vh-200px)] flex-col items-center">
          <div class="mb-12 w-full max-w-2xl">
            <div class="mb-6 flex items-center justify-center gap-3">
              <div class="h-px flex-1 bg-gradient-to-r from-transparent via-gray-300 to-gray-300 dark:via-gray-600 dark:to-gray-600"></div>
              <div class="flex items-center gap-2">
                <div class="flex h-2 w-2 rounded-full bg-primary"></div>
                <h2 class="text-2xl font-bold text-gray-900 dark:text-gray-100">
                  选择代码生成方式
                </h2>
                <div class="flex h-2 w-2 rounded-full bg-primary"></div>
              </div>
              <div class="h-px flex-1 bg-gradient-to-l from-transparent via-gray-300 to-gray-300 dark:via-gray-600 dark:to-gray-600"></div>
            </div>
            <p class="text-center text-base text-gray-500 dark:text-gray-400">
              请选择一种适合您的代码生成方式
            </p>
          </div>
          <ModeSelectorComponent @select="handleSelectMode" />
        </div>
      </div>

      <!-- JSON导入模式 -->
      <JsonImportComponent
        v-else-if="currentMode === 'json'"
        key="json"
        @generate="handleGenerate"
        @back="handleBack"
      />

      <!-- 手动填写模式 -->
      <ManualFormComponent
        v-else-if="currentMode === 'manual'"
        key="manual"
        @generate="handleGenerate"
        @back="handleBack"
      />

      <!-- 数据库表模式 -->
      <DatabaseSelectComponent
        v-else-if="currentMode === 'database'"
        key="database"
        @generate="handleGenerate"
        @back="handleBack"
      />

      <!-- AI提示词模式 -->
      <AiPromptComponent
        v-else-if="currentMode === 'ai'"
        key="ai"
        @generate="handleGenerate"
        @back="handleBack"
      />
    </Transition>

    <!-- 生成历史抽屉 -->
    <Drawer
      v-model:open="historyDrawerVisible"
      title="生成历史"
      :width="700"
      placement="right"
      class="history-drawer"
    >
      <div v-if="historyLoading" class="flex h-64 items-center justify-center">
        <div class="text-center">
          <i class="fa-solid fa-spinner fa-spin text-2xl text-primary mb-2"></i>
          <p class="text-sm text-gray-500 dark:text-gray-400">加载中...</p>
        </div>
      </div>
      <div v-else-if="historyList.length === 0" class="flex h-64 items-center justify-center">
        <Empty description="暂无生成记录" />
      </div>
      <div v-else class="history-list-clean">
        <div
          v-for="item in historyList"
          :key="item.id"
          class="history-item-clean"
        >
          <div class="history-item-wrapper">
            <!-- 左侧内容 -->
            <div class="history-item-left">
              <div class="history-item-header">
                <h4 class="history-item-title">{{ item.title || '未命名' }}</h4>
              </div>
              <div class="history-item-file-row">
                <svg
                  class="history-file-icon"
                  width="16"
                  height="16"
                  viewBox="0 0 16 16"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M3 2C2.44772 2 2 2.44772 2 3V13C2 13.5523 2.44772 14 3 14H13C13.5523 14 14 13.5523 14 13V5.41421C14 5.149 13.8946 4.89464 13.7071 4.70711L11.2929 2.29289C11.1054 2.10536 10.851 2 10.5858 2H3Z"
                    fill="currentColor"
                    fill-opacity="0.1"
                  />
                  <path
                    d="M3 2C2.44772 2 2 2.44772 2 3V13C2 13.5523 2.44772 14 3 14H13C13.5523 14 14 13.5523 14 13V5.41421C14 5.149 13.8946 4.89464 13.7071 4.70711L11.2929 2.29289C11.1054 2.10536 10.851 2 10.5858 2H3Z"
                    stroke="currentColor"
                    stroke-width="1.5"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                  <path
                    d="M10 2V5H13"
                    stroke="currentColor"
                    stroke-width="1.5"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                  <path
                    d="M5 8H11M5 10H9"
                    stroke="currentColor"
                    stroke-width="1.5"
                    stroke-linecap="round"
                  />
                </svg>
                <span class="history-item-file">{{ item.file_name || '未命名文件' }}</span>
              </div>
              <div class="history-item-time-row">
                <span class="history-item-time-label">生成时间：</span>
                <span class="history-item-time">{{ item.created_at || '-' }}</span>
              </div>
            </div>

            <!-- 右侧操作 -->
            <div class="history-item-right">
              <Button
                v-if="item.params"
                type="link"
                size="small"
                class="history-btn-link"
                @click="handleViewJson(item)"
              >
                <i class="fa-solid fa-code mr-1"></i>
                查看
              </Button>
              <Button
                type="primary"
                size="small"
                class="history-btn-primary"
                @click="handleDownloadHistory(item)"
              >
                <i class="fa-solid fa-download mr-1"></i>
                下载
              </Button>
            </div>
          </div>
        </div>
      </div>
    </Drawer>

    <!-- JSON详情查看Modal -->
    <Modal
      v-model:open="jsonViewerVisible"
      title="生成参数详情"
      :width="800"
      :footer="null"
      class="json-viewer-modal"
    >
      <div class="json-viewer-container">
        <JsonViewer
          :value="currentJsonData"
          :expand-depth="3"
          copyable
          boxed
        />
      </div>
    </Modal>
  </Page>
</template>

<style scoped>
.mode-selector-container {
  padding: 2rem 0;
}

.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: all 0.3s ease;
}

.fade-slide-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.fade-slide-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

/* 历史记录列表样式 - 简洁美观风格 */
.history-list-clean {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.history-item-clean {
  background: #ffffff;
  border: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: 10px;
  transition: all 0.2s ease;
  overflow: hidden;
}

.dark .history-item-clean {
  background: #1f2937;
  border-color: rgba(255, 255, 255, 0.1);
}

.history-item-clean:hover {
  border-color: rgba(24, 144, 255, 0.3);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.dark .history-item-clean:hover {
  border-color: rgba(24, 144, 255, 0.5);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.history-item-wrapper {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: 18px 20px;
  gap: 24px;
}

.history-item-left {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.history-item-header {
  margin-bottom: 0;
}

.history-item-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  line-height: 1.4;
  word-break: break-word;
}

.dark .history-item-title {
  color: #f9fafb;
}

.history-item-file-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.history-file-icon {
  color: #1890ff;
  width: 16px;
  height: 16px;
  flex-shrink: 0;
  margin-top: 2px;
}

.history-item-file {
  font-size: 14px;
  color: #6b7280;
  word-break: break-all;
  line-height: 1.5;
}

.dark .history-item-file {
  color: #9ca3af;
}

.history-item-time-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 2px;
}

.history-item-time-label {
  font-size: 13px;
  color: #9ca3af;
  flex-shrink: 0;
}

.dark .history-item-time-label {
  color: #6b7280;
}

.history-item-time {
  font-size: 13px;
  color: #6b7280;
  word-break: break-word;
}

.dark .history-item-time {
  color: #9ca3af;
}

.history-item-right {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
  padding-top: 2px;
}

.history-btn-link {
  height: auto;
  padding: 0;
  font-size: 13px;
  display: flex;
  align-items: center;
  transition: all 0.2s ease;
}

.history-btn-primary {
  height: 32px;
  padding: 0 16px;
  border-radius: 6px;
  font-size: 13px;
  display: flex;
  align-items: center;
  transition: all 0.2s ease;
}

.history-btn-primary:hover {
  transform: translateY(-1px);
}

/* JSON查看器样式 */
.json-viewer-container {
  max-height: 600px;
  overflow: auto;
  padding: 8px;
  background: #fafafa;
  border-radius: 8px;
}

.dark .json-viewer-container {
  background: #1f2937;
}

/* 抽屉样式优化 */
:deep(.history-drawer .ant-drawer-body) {
  padding: 20px;
}
</style>
