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

import { Button, Card, message, Select, Steps } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { codeGenerationForm } from '#/views/code-generation/config/form';

import CodeGenerationFiledTable from './fileds.vue';
import type { CodeGenData } from '../utils/data-transformer';
import { transformManualToStandard, validateData } from '../utils/data-transformer';
import {
  deleteDraft,
  listDrafts,
  loadDraft,
  saveDraft,
  type GenerationMode,
} from '../utils/draft-manager';

const mode: GenerationMode = 'manual';

const emit = defineEmits<{
  generate: [data: CodeGenData];
  back: [];
}>();

// 表单相关
const [Form, formApi] = useVbenForm(codeGenerationForm);
const tableRef = ref<InstanceType<typeof CodeGenerationFiledTable> | null>(null);

// 步骤
const stepsCurrent = ref(0);
const stepsItems = [
  {
    title: '基础信息',
    description: '类和菜单的基础信息',
  },
  {
    title: '字段信息',
    description: '设计数据库字段信息',
  },
];

// 草稿相关
const draftId = ref<string | null>(null);
const drafts = ref<ReturnType<typeof listDrafts>>([]);
const selectedDraft = ref<string>('');

// 加载草稿列表
const loadDraftList = () => {
  drafts.value = listDrafts(mode);
};

// 加载草稿
const handleLoadDraft = (id: string) => {
  const draft = loadDraft(mode, id);
  if (draft && draft.data) {
    draftId.value = id;
    selectedDraft.value = id;

    // 恢复表单数据
    if (draft.data.formData) {
      formApi.setValues(draft.data.formData);
    }

    // 恢复字段数据
    if (draft.data.fields && tableRef.value) {
      tableRef.value.tableData = draft.data.fields;
    }

    message.success('草稿已加载');
  }
};

// 手动保存草稿
const handleSaveDraft = () => {
  formApi.getValues().then((formData) => {
    const fields = tableRef.value?.tableData || [];
    const draftData = {
      formData,
      fields,
    };

    try {
      const id = saveDraft(mode, draftData, undefined, draftId.value || undefined);
      draftId.value = id;
      loadDraftList();
      message.success('草稿已保存');
    } catch (error) {
      console.error('保存草稿失败:', error);
      message.error('保存草稿失败');
    }
  });
};

// 下一步
const handleNext = async () => {
  if (stepsCurrent.value === 0) {
    const { valid } = await formApi.validate();
    if (valid) {
      stepsCurrent.value++;
      saveCurrentDraft();
    }
  }
};

// 上一步
const handlePrev = () => {
  if (stepsCurrent.value > 0) {
    stepsCurrent.value--;
  }
};

// 生成代码
const handleGenerate = async () => {
  const { valid } = await formApi.validate();
  if (!valid) {
    message.warning('请先完成基础信息填写');
    return;
  }

  const formData = await formApi.getValues();
  const fields = tableRef.value?.tableData || [];

  if (!fields || fields.length === 0) {
    message.warning('请至少添加一个字段');
    return;
  }

  // 转换为标准格式
  const standardData = transformManualToStandard(formData, fields);

  // 验证数据
  const validation = validateData(standardData);
  if (!validation.valid) {
    message.error(validation.message);
    return;
  }

  emit('generate', standardData);
};

// 删除草稿
const handleDeleteDraft = (id: string) => {
  if (deleteDraft(mode, id)) {
    message.success('草稿已删除');
    loadDraftList();
    if (draftId.value === id) {
      draftId.value = null;
      selectedDraft.value = '';
    }
  }
};

onMounted(() => {
  loadDraftList();
});
</script>

<template>
  <div class="manual-form">
    <!-- 顶部操作栏 -->
    <Card class="mb-4">
      <template #title>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-2">
            <Button type="text" @click="emit('back')">
              <svg
                class="mr-2 inline-block"
                width="14"
                height="14"
                viewBox="0 0 14 14"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  d="M8.75 3.5L5.25 7L8.75 10.5"
                  stroke="currentColor"
                  stroke-width="1.5"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                />
              </svg>
              返回
            </Button>
            <span class="text-lg font-semibold">手动填写模式</span>
          </div>
          <div class="flex items-center gap-2">
            <Select
              v-model:value="selectedDraft"
              placeholder="选择草稿"
              style="width: 200px"
              allow-clear
              @change="handleLoadDraft"
            >
              <Select.Option
                v-for="draft in drafts"
                :key="draft.id"
                :value="draft.id"
              >
                <div class="flex items-center justify-between">
                  <span>{{ draft.name }}</span>
                  <Button
                    type="text"
                    danger
                    size="small"
                    @click.stop="handleDeleteDraft(draft.id)"
                  >
                    <i class="fa-solid fa-trash"></i>
                  </Button>
                </div>
              </Select.Option>
            </Select>
          </div>
        </div>
      </template>
    </Card>

    <!-- 内容区域 -->
    <Card class="content-area mb-24 shadow-sm">
      <Steps :current="stepsCurrent" :items="stepsItems" class="mb-8" />

      <div class="min-h-[500px]">
        <div v-show="stepsCurrent === 0" class="fade-in">
          <Form />
        </div>
        <div v-show="stepsCurrent === 1" class="fade-in">
          <CodeGenerationFiledTable ref="tableRef" />
        </div>
      </div>
    </Card>

    <!-- 固定底部操作栏 -->
    <div class="fixed-bottom-bar">
      <div class="fixed-bottom-bar-wrapper">
        <div class="fixed-bottom-bar-content">
          <!-- 左侧状态信息 -->
          <div class="flex items-center gap-3">
            <div class="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 text-primary">
              <i class="fa-solid fa-list-check"></i>
            </div>
            <div>
              <div class="text-sm font-medium text-gray-900 dark:text-gray-100">
                步骤
                <span class="text-primary font-semibold">{{ stepsCurrent + 1 }}</span>
                /
                <span class="text-gray-500 dark:text-gray-400">{{ stepsItems.length }}</span>
                <span class="ml-2">{{ stepsItems[stepsCurrent].title }}</span>
              </div>
              <div class="text-xs text-gray-400 dark:text-gray-500">
                {{ stepsItems[stepsCurrent].description }}
              </div>
            </div>
          </div>

          <!-- 右侧操作按钮 -->
          <div class="flex items-center gap-2">
            <Button
              v-if="stepsCurrent > 0"
              size="large"
              class="action-btn-secondary"
              @click="handlePrev"
            >
              <i class="fa-solid fa-arrow-left mr-2"></i>上一步
            </Button>
            <Button size="large" class="action-btn-secondary" @click="handleSaveDraft">
              <i class="fa-solid fa-save mr-2"></i>保存草稿
            </Button>
            <Button
              v-if="stepsCurrent < stepsItems.length - 1"
              type="primary"
              size="large"
              class="action-btn-primary"
              @click="handleNext"
            >
              下一步
              <i class="fa-solid fa-arrow-right ml-2"></i>
            </Button>
            <Button
              v-if="stepsCurrent === stepsItems.length - 1"
              type="primary"
              size="large"
              class="action-btn-primary"
              @click="handleGenerate"
            >
              <i class="fa-solid fa-code mr-2"></i>生成代码
            </Button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.manual-form {
  animation: fade-slide-enter 0.3s ease-out;
  padding-bottom: 120px; /* 为固定底部栏留出空间 */
}

.content-area {
  min-height: 500px;
}

/* 优化卡片样式 */
:deep(.ant-card) {
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

:deep(.ant-card:hover) {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.dark :deep(.ant-card) {
  border-color: rgba(255, 255, 255, 0.1);
}

/* 优化步骤条样式 */
:deep(.ant-steps) {
  padding: 24px 0;
}

.fade-in {
  animation: fade-in 0.3s ease-out;
}

@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 固定底部操作栏 - 现代化设计 */
.fixed-bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  padding: 0 24px 24px;
  pointer-events: none;
}

.fixed-bottom-bar-wrapper {
  max-width: 1400px;
  margin: 0 auto;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(20px) saturate(180%);
  border: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: 16px;
  box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.08), 0 0 0 1px rgba(0, 0, 0, 0.04);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  pointer-events: all;
}

.dark .fixed-bottom-bar-wrapper {
  background: rgba(31, 41, 55, 0.98);
  border-color: rgba(255, 255, 255, 0.12);
  box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.4), 0 0 0 1px rgba(255, 255, 255, 0.08);
}

.fixed-bottom-bar-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  gap: 24px;
}

.action-btn-secondary {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.action-btn-secondary:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.action-btn-primary {
  border-radius: 8px;
  font-weight: 600;
  padding: 0 24px;
  height: 44px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
  transition: all 0.2s ease;
}

.action-btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.4);
}

.action-btn-primary:active:not(:disabled) {
  transform: translateY(0);
}

@keyframes fade-slide-enter {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 响应式优化 */
@media (max-width: 768px) {
  .fixed-bottom-bar {
    padding: 0 16px 16px;
  }

  .fixed-bottom-bar-wrapper {
    border-radius: 12px;
  }

  .fixed-bottom-bar-content {
    flex-direction: column;
    align-items: stretch;
    padding: 16px;
    gap: 16px;
  }

  .fixed-bottom-bar-content > div:first-child {
    justify-content: center;
  }

  .fixed-bottom-bar-content > div:last-child {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
  }

  .fixed-bottom-bar-content > div:last-child .action-btn-primary {
    grid-column: 1 / -1;
  }
}
</style>

