<script setup lang="ts">
import { ref } from "vue";
import { ImageService } from "~/services";

const prompt = ref("");
const imageUrl = ref("");
const errorMessage = ref("");
const loading = ref(false);

const generate = async () => {
  const text = prompt.value.trim();
  if (!text) {
    errorMessage.value = "请输入图片描述";
    return;
  }

  loading.value = true;
  errorMessage.value = "";
  imageUrl.value = "";

  try {
    const res = await ImageService.GenerateImage({
      prompt: text
    });

    if (res.code === 0 && res.data?.imageUrl) {
      imageUrl.value = res.data.imageUrl;
      return;
    }

    errorMessage.value = res.msg || "图片生成失败";
  } catch (error) {
    errorMessage.value = getErrorMessage(error, "图片生成失败");
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div class="w-full max-w-xl space-y-3">
    <el-input
      v-model="prompt"
      type="textarea"
      :rows="3"
      placeholder="请输入图片描述"
      :disabled="loading"
    />

    <el-button type="primary" :loading="loading" @click="generate">
      立即生成
    </el-button>

    <p v-if="errorMessage" class="text-sm text-red-500">
      {{ errorMessage }}
    </p>

    <img
      v-if="imageUrl"
      :src="imageUrl"
      alt="生成图片"
      class="block max-w-full rounded border"
    />
  </div>
</template>
