<template>
  <div class="draft-dynamic-container">
    <!-- 头部 -->
    <div class="header-section">
      <el-button @click="handleGoBack"> 返回 </el-button>
      <div class="header-title">本地草稿</div>
      <div class="header-right" />
    </div>

    <!-- 草稿列表 -->
    <div v-if="draftList.length > 0" class="content-section">
      <div class="content-grid">
        <div v-for="item in draftList" :key="item.id" class="content-card" @click="handleEditDraft(item)">
          <!-- 封面图片/视频区域 -->
          <div class="content-cover-wrapper">
            <img v-if="item.coverUrl" :src="item.coverUrl" :alt="item.title" class="content-cover" />
            <div v-else class="cover-placeholder">
              <el-icon :size="48" color="#999">
                <Picture />
              </el-icon>
            </div>

            <!-- 视频播放按钮 -->
            <div v-if="item.type === 'video'" class="play-overlay">
              <el-icon :size="40" color="#fff">
                <VideoPlay />
              </el-icon>
            </div>
          </div>

          <!-- 底部信息 -->
          <div class="content-info">
            <div class="content-title">
              {{ item.title || "未命名" }}
            </div>
            <div class="content-meta">
              <span class="meta-time">{{ formatTime(item.createdTime) }}</span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="card-actions">
            <el-button size="small" type="primary" plain @click.stop="handleEditDraft(item)">
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" plain @click.stop="handleDeleteDraft(item)">
              <el-icon>
                <Delete />
              </el-icon>
              删除
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-section">
      <el-empty description="暂无数据" />
    </div>
  </div>
</template>

<script setup lang="ts" name="draftDynamic">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowLeft, Picture, VideoPlay, Edit, Delete, Plus } from "@element-plus/icons-vue";
import { getUserDraftDynamics, deleteDynamicsById } from "@/api/modules/newLoginApi";
import { deleteDraft } from "@/api/modules/dynamicManagement";
import { useUserStore } from "@/stores/modules/user";

const router = useRouter();
const userStore = useUserStore();

// 接口定义
interface DraftItem {
  id: number;
  title: string;
  coverUrl: string;
  type: "image" | "video";
  createdTime: string;
  context?: string;
  imagePath?: string;
  addressName?: string;
  address?: string;
  addressProvince?: string;
}

// 响应式数据
const draftList = ref<DraftItem[]>([]);
const loading = ref(false);

// 返回上一页
const handleGoBack = () => {
  router.back();
};

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return "";

  const date = new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  // 小于1分钟
  if (diff < 60000) {
    return "刚刚";
  }

  // 小于1小时
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`;
  }

  // 小于1天
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`;
  }

  // 小于7天
  if (diff < 604800000) {
    return `${Math.floor(diff / 86400000)}天前`;
  }

  // 显示具体日期
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");

  if (year === now.getFullYear()) {
    return `${month}-${day}`;
  }

  return `${year}-${month}-${day}`;
};

// 加载草稿列表
const loadDraftList = async () => {
  try {
    loading.value = true;

    // 获取当前用户的手机号，并在前面拼接 "store_"
    const phone = userStore.userInfo?.phone || "";
    const phoneId = phone.startsWith("store_") ? phone : `store_${phone}`;

    // 调用接口获取草稿列表
    const res: any = await getUserDraftDynamics({
      phoneId: phoneId,
      page: 1,
      size: 1000
    });

    if (res.code === 200) {
      const dataList = res.data?.records || res.data?.list || [];

      draftList.value = dataList.map((item: any) => {
        const firstImage = item.imagePath ? item.imagePath.split(",")[0] : "";
        const isVideo = firstImage.toLowerCase().endsWith(".mp4");

        return {
          id: item.id,
          title: item.title || item.context || "未命名",
          coverUrl: firstImage,
          type: isVideo ? "video" : "image",
          createdTime: item.createdTime || item.createdTime || new Date().toISOString(),
          // 保留原始数据，用于编辑
          ...item
        };
      });

      console.log("加载草稿列表成功:", draftList.value);
    }
  } catch (error) {
    console.error("加载草稿列表失败:", error);
    ElMessage.error("加载草稿列表失败");
  } finally {
    loading.value = false;
  }
};

// 编辑草稿
const handleEditDraft = (item: DraftItem) => {
  // 跳转到发布动态页面，并传递草稿ID
  router.push({
    path: "/dynamicManagement/publishDynamic",
    query: {
      draftId: item.id,
      mode: "edit"
    }
  });
};

// 删除草稿
const handleDeleteDraft = async (item: DraftItem) => {
  try {
    await ElMessageBox.confirm("确定要删除这条草稿吗？删除后将无法恢复。", "删除确认", {
      confirmButtonText: "确定删除",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "el-button--danger"
    });

    // 调用删除接口
    await deleteDynamicsById({
      id: item.id
    });

    ElMessage.success("删除成功");

    // 从列表中移除该项
    const index = draftList.value.findIndex(draft => draft.id === item.id);
    if (index > -1) {
      draftList.value.splice(index, 1);
    }
  } catch (error: any) {
    // 用户取消删除或删除失败
    if (error !== "cancel") {
      console.error("删除草稿失败:", error);
      ElMessage.error("删除草稿失败");
    }
  }
};

// 创建新动态
const handleCreateNew = () => {
  router.push("/dynamicManagement/publishDynamic");
};

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

<style scoped lang="scss">
.draft-dynamic-container {
  min-height: calc(100vh - 120px);
  padding: 20px;
  background: #ffffff;

  // 头部区域
  .header-section {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 16px;
    margin-bottom: 24px;
    border-bottom: 1px solid #e4e7ed;
    .back-btn {
      display: flex;
      gap: 4px;
      align-items: center;
      padding: 8px 16px;
      font-size: 15px;
      color: #606266;
      transition: all 0.3s;
      &:hover {
        color: #409eff;
        background: #ecf5ff;
      }
    }
    .header-title {
      flex: 1;
      font-size: 20px;
      font-weight: 600;
      color: #303133;
      text-align: center;
    }
    .header-right {
      width: 100px;
    }
  }

  // 内容区域
  .content-section {
    margin-top: 20px;
  }

  // 内容网格布局
  .content-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;

    @media (width <= 1400px) {
      grid-template-columns: repeat(3, 1fr);
    }

    @media (width <= 1024px) {
      grid-template-columns: repeat(2, 1fr);
    }

    @media (width <= 768px) {
      grid-template-columns: repeat(1, 1fr);
    }
  }

  // 内容卡片
  .content-card {
    position: relative;
    overflow: hidden;
    cursor: pointer;
    background: #ffffff;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    transition: all 0.3s;
    &:hover {
      border-color: #409eff;
      box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
      transform: translateY(-2px);
      .card-actions {
        opacity: 1;
      }
      .play-overlay {
        opacity: 1;
      }
    }

    // 封面区域
    .content-cover-wrapper {
      position: relative;
      width: 100%;
      aspect-ratio: 16 / 9;
      overflow: hidden;
      background: #f5f7fa;
      .content-cover {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      .cover-placeholder {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        background: #f5f7fa;
      }

      // 播放按钮覆盖层
      .play-overlay {
        position: absolute;
        inset: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgb(0 0 0 / 30%);
        opacity: 0;
        transition: opacity 0.3s;
        .el-icon {
          filter: drop-shadow(0 2px 4px rgb(0 0 0 / 20%));
        }
      }

      // 草稿标签
      .draft-label {
        position: absolute;
        top: 8px;
        left: 8px;
        display: flex;
        gap: 4px;
        align-items: center;
        padding: 4px 10px;
        font-size: 12px;
        color: #ffffff;
        background: rgb(255 152 0 / 90%);
        backdrop-filter: blur(4px);
        border-radius: 4px;
        .el-icon {
          font-size: 12px;
        }
      }
    }

    // 内容信息
    .content-info {
      padding: 12px;
      .content-title {
        margin-bottom: 8px;
        overflow: hidden;
        font-size: 15px;
        font-weight: 500;
        line-height: 1.4;
        color: #303133;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .content-meta {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 13px;
        color: #909399;
        .meta-time {
          display: flex;
          gap: 4px;
          align-items: center;
        }
      }
    }

    // 操作按钮
    .card-actions {
      position: absolute;
      inset: 0;
      display: flex;
      gap: 12px;
      align-items: center;
      justify-content: center;
      background: rgb(0 0 0 / 60%);
      opacity: 0;
      transition: opacity 0.3s;
    }
  }

  // 空状态
  .empty-section {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 400px;
    padding: 80px 0;
    :deep(.el-empty) {
      .el-button {
        margin-top: 16px;
      }
    }
  }
}
</style>
