<script lang="ts" setup>
import type { FeatureApi } from '#/api/product-manage';

import { computed, ref } from 'vue';

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

import { Button, Input, message } from 'ant-design-vue';

import { configFeatureExample, getFeatureExample } from '#/api/product-manage';

const emit = defineEmits(['success']);

const featureData = ref<FeatureApi.FeatureItem>();
const exampleData = ref('');
const loading = ref(false);
const saving = ref(false);

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    if (!featureData.value) return;

    saving.value = true;
    try {
      await configFeatureExample({
        feature_id: featureData.value.id,
        data: exampleData.value,
      });
      message.success('示例配置保存成功');
      emit('success');
      modalApi.close();
    } catch (error) {
      console.error('保存示例配置失败:', error);
    } finally {
      saving.value = false;
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<FeatureApi.FeatureItem>();
      if (data) {
        featureData.value = data;
        loadExampleData();
      }
    } else {
      featureData.value = undefined;
      exampleData.value = '';
    }
  },
});

// 加载示例数据
async function loadExampleData() {
  if (!featureData.value) return;

  loading.value = true;
  try {
    const response = await getFeatureExample(featureData.value.id);
    exampleData.value = response.data || '';
  } catch (error) {
    console.error('获取示例数据失败:', error);
    exampleData.value = '';
  } finally {
    loading.value = false;
  }
}

// 格式化JSON
function formatJson() {
  try {
    if (exampleData.value) {
      const parsed = JSON.parse(exampleData.value);
      exampleData.value = JSON.stringify(parsed, null, 2);
    }
  } catch {
    message.error('JSON格式错误，无法格式化');
  }
}

// 清空数据
function clearData() {
  exampleData.value = '';
}

const modalTitle = computed(() => {
  return featureData.value
    ? `示例配置 - ${featureData.value.name}`
    : '示例配置';
});

const isJsonValid = computed(() => {
  if (!exampleData.value) return true;
  try {
    JSON.parse(exampleData.value);
    return true;
  } catch {
    return false;
  }
});
</script>

<template>
  <Modal :title="modalTitle" class="w-[1200px]">
    <div class="space-y-4">
      <div>
        <div class="mb-2 flex items-center justify-between">
          <label class="text-sm font-medium">示例数据 (JSON格式)</label>
          <div class="space-x-2">
            <Button size="small" @click="formatJson">格式化</Button>
            <Button size="small" @click="clearData">清空</Button>
          </div>
        </div>
        <Input.TextArea
          v-model:value="exampleData"
          :loading="loading"
          :rows="15"
          :status="isJsonValid ? undefined : 'error'"
          placeholder="请输入JSON格式的示例数据..."
          class="font-mono text-sm"
        />
        <div v-if="!isJsonValid" class="mt-1 text-xs text-red-500">
          JSON格式错误，请检查语法
        </div>
      </div>

      <div class="text-xs text-gray-500">
        <p>提示：</p>
        <ul class="list-disc space-y-1 pl-4">
          <li>如果当前功能没有配置示例数据，输入框将为空</li>
          <li>可以在此输入JSON格式的示例数据</li>
          <li>点击"格式化"按钮可以美化JSON格式</li>
          <li>保存后该示例数据将用于功能展示</li>
        </ul>
      </div>
    </div>

    <template #footer>
      <div class="flex justify-end space-x-2">
        <Button @click="modalApi.close">取消</Button>
        <Button
          type="primary"
          :loading="saving"
          :disabled="!isJsonValid"
          @click="modalApi.onConfirm"
        >
          保存
        </Button>
      </div>
    </template>
  </Modal>
</template>
