<template>
  <!-- 添加/编辑Banner对话框 -->
  <el-dialog
    :model-value="visible"
    :title="dialogTitle"
    width="600px"
    :close-on-click-modal="false"
    @update:model-value="handleDialogClose"
  >
    <el-form
      :model="currentBanner"
      label-width="100px"
      :rules="formRules"
      ref="bannerFormRef"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="currentBanner.title"
          placeholder="请输入Banner标题"
          maxlength="255"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="简介" prop="desc">
        <el-input
          v-model="currentBanner.desc"
          type="textarea"
          :rows="4"
          placeholder="请输入Banner简介"
        />
      </el-form-item>

      <el-form-item label="跳转地址" prop="url">
        <el-input
          v-model="currentBanner.url"
          placeholder="例如：https://www.example.com 或 /page/detail"
        />
        <div style="margin-top: 8px; font-size: 12px; color: var(--el-text-color-secondary);">
          支持外部链接（http://）和内部路由（/）
        </div>
      </el-form-item>

      <el-form-item label="Banner图片" prop="image">
        <el-upload
          class="image-uploader"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :show-file-list="false"
          :on-success="handleImageSuccess"
          :on-error="handleImageError"
          :before-upload="beforeImageUpload"
          accept="*"
        >
          <img
            v-if="currentBanner.image"
            :src="getImageUrl(currentBanner.image)"
            class="image-preview"
          />
          <div v-else class="upload-placeholder">
            <el-icon class="image-uploader-icon"><Plus /></el-icon>
            <div class="el-upload__text">点击上传图片</div>
          </div>
        </el-upload>
        <div style="margin-top: 8px; font-size: 12px; color: var(--el-text-color-secondary);">
          建议尺寸：1920x600，支持 jpg、png、gif 格式，大小不超过 5MB
        </div>
        <el-button
          v-if="currentBanner.image"
          size="small"
          type="danger"
          text
          @click="handleRemoveImage"
          style="margin-top: 8px;"
        >
          删除图片
        </el-button>
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="currentBanner.sort"
          :min="0"
          placeholder="数字越小越靠前"
          style="width: 100%"
        />
        <div style="margin-top: 8px; font-size: 12px; color: var(--el-text-color-secondary);">
          数字越小，排序越靠前
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage, ElForm } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

// 定义Banner数据类型
interface Banner {
  id: number;
  title: string;
  desc: string;
  url: string;
  image: string;
  sort: number;
  create_time?: number;
  update_time?: number;
  delete_time?: number;
}

// Props
interface Props {
  visible: boolean;
  banner: Partial<Banner> | null;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  banner: null,
});

// Emits
const emit = defineEmits<{
  (e: "update:visible", value: boolean): void;
  (e: "save", banner: Partial<Banner>): void;
  (e: "cancel"): void;
}>();

// 表单引用
const bannerFormRef = ref<InstanceType<typeof ElForm>>();

// 当前操作的Banner
const currentBanner = ref<Partial<Banner>>({
  id: 0,
  title: "",
  desc: "",
  url: "",
  image: "",
  sort: 0,
});

// 上传配置
// @ts-ignore
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
const uploadUrl = ref(API_BASE_URL + "/admin/uploadfiles");
const uploadHeaders = ref({
  Authorization: "Bearer " + (localStorage.getItem("token") || ""),
});

// 对话框标题
const dialogTitle = computed(() => {
  return props.banner?.id && props.banner.id > 0 ? "编辑Banner" : "添加Banner";
});

// 表单验证规则
const formRules = ref({
  title: [{ required: true, message: "请输入Banner标题", trigger: "blur" }],
  sort: [{ required: true, message: "请输入排序号", trigger: "blur" }],
});

// 监听props变化，更新当前Banner
watch(
  () => props.banner,
  (newBanner) => {
    if (newBanner) {
      currentBanner.value = {
        ...newBanner,
      };
    } else {
      // 重置表单
      currentBanner.value = {
        id: 0,
        title: "",
        desc: "",
        url: "",
        image: "",
        sort: 0,
      };
    }
  },
  { immediate: true }
);

// 监听props.visible变化
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible && (!props.banner || !props.banner.id)) {
      // 新增时重置表单
      currentBanner.value = {
        id: 0,
        title: "",
        desc: "",
        url: "",
        image: "",
        sort: 0,
      };
    }
  }
);

// 取消操作
const handleCancel = () => {
  emit("update:visible", false);
  emit("cancel");
};

// 处理对话框关闭
const handleDialogClose = (value: boolean) => {
  if (!value) {
    emit("update:visible", false);
    emit("cancel");
  }
};

// 图片上传前校验
const beforeImageUpload = (file: any) => {
  return true;
};

// 图片上传成功
const handleImageSuccess = (response: any) => {
  if (response.code === 200) {
    // 直接保存相对路径，不拼接API_BASE_URL
    currentBanner.value.image = response.data.url || response.data.path;
    ElMessage.success("图片上传成功");
  } else {
    ElMessage.error(response.msg || "图片上传失败");
  }
};

// 图片上传失败
const handleImageError = () => {
  ElMessage.error("图片上传失败，请重试");
};

// 删除图片
const handleRemoveImage = () => {
  currentBanner.value.image = "";
  ElMessage.success("图片已删除");
};

// 获取图片完整URL（用于预览）
const getImageUrl = (imagePath: string) => {
  if (!imagePath) return "";
  // 如果是绝对路径，直接返回
  if (imagePath.startsWith("http")) return imagePath;
  // 如果是相对路径，拼接API基础地址
  return API_BASE_URL + imagePath;
};

// 保存Banner
const handleSave = async () => {
  // 表单验证
  if (!bannerFormRef.value) return;
  const valid = await bannerFormRef.value.validate();
  if (!valid) return;

  // 准备提交数据
  const payload = { ...currentBanner.value };

  // 触发保存事件
  emit("save", payload);
};
</script>

<style lang="less" scoped>
/* 对话框样式精简 */
:deep(.el-dialog__body) {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

/* 图片上传样式 */
.image-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.image-preview {
  width: 100%;
  max-width: 500px;
  height: auto;
  max-height: 300px;
  display: block;
  object-fit: contain;
  border-radius: 4px;
}

.upload-placeholder {
  width: 100%;
  min-height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--el-text-color-secondary);

  .image-uploader-icon {
    font-size: 48px;
    margin-bottom: 12px;
  }

  .el-upload__text {
    font-size: 14px;
  }
}
</style>
