<template>
  <view class="container">
    <!-- 生成记录列表 -->
    <view class="record-list">
      <view class="record-item" v-for="record in records" :key="record.id">
        <!-- 记录信息 -->
        <view class="record-info">
          <view class="record-title">{{ record.title }}</view>
          <view class="record-time">生成时间: {{ record.generateTime }}</view>
        </view>

        <!-- 状态标签 -->
        <view class="status-tag" :class="record.status">
          {{ record.statusText }}
        </view>

        <!-- 操作按钮 -->
        <view class="record-actions">
          <u-button
            v-if="record.status === 'completed'"
            type="primary"
            size="small"
            @click="downloadRecord(record)"
          >
            <u-icon
              name="download"
              size="14"
              color="white"
              style="margin-right: 4px"
            ></u-icon>
            下载
          </u-button>
          <u-button v-else type="info" size="small" disabled>
            <u-icon
              name="download"
              size="14"
              color="white"
              style="margin-right: 4px"
            ></u-icon>
            下载
          </u-button>

          <u-button
            v-if="record.status === 'failed'"
            type="error"
            size="small"
            @click="deleteRecord(record)"
            style="margin-left: 8px"
          >
            <u-icon
              name="trash"
              size="14"
              color="white"
              style="margin-right: 4px"
            ></u-icon>
            删除
          </u-button>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="records.length === 0" class="empty-state">
      <u-icon name="file-text" size="60" color="#ccc"></u-icon>
      <text class="empty-text">暂无生成记录</text>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore && records.length > 0" class="load-more">
      <u-button
        type="default"
        size="small"
        :loading="loading"
        @click="loadMore"
      >
        {{ loading ? "加载中..." : "加载更多" }}
      </u-button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app";

// 响应式数据
const loading = ref(false);
const hasMore = ref(true);
const records = ref([
  {
    id: 1,
    title: "乘客电梯标准图纸",
    generateTime: "2025-05-15 14:30",
    status: "completed",
    statusText: "已完成",
    downloadUrl: "/static/files/passenger-elevator.pdf",
  },
  {
    id: 2,
    title: "货运电梯专用图纸",
    generateTime: "2025-05-15 14:30",
    status: "failed",
    statusText: "未完成",
    downloadUrl: null,
  },
  {
    id: 3,
    title: "医用电梯专业图纸",
    generateTime: "2025-05-15 14:30",
    status: "completed",
    statusText: "已完成",
    downloadUrl: "/static/files/medical-elevator.pdf",
  },
  {
    id: 4,
    title: "观光电梯定制图纸",
    generateTime: "2025-05-15 14:30",
    status: "completed",
    statusText: "已完成",
    downloadUrl: "/static/files/sightseeing-elevator.pdf",
  },
  {
    id: 5,
    title: "货运电梯专用图纸",
    generateTime: "2025-05-15 14:30",
    status: "failed",
    statusText: "未完成",
    downloadUrl: null,
  },
]);

// 下载记录
const downloadRecord = (record) => {
  if (record.status !== "completed" || !record.downloadUrl) {
    uni.showToast({
      title: "文件未准备好",
      icon: "none",
    });
    return;
  }

  uni.showLoading({
    title: "准备下载...",
  });

  // 模拟下载过程
  setTimeout(() => {
    uni.hideLoading();

    // 在实际项目中，这里应该调用下载API或打开文件
    uni.showToast({
      title: "下载成功",
      icon: "success",
    });

    // 实际下载逻辑
    // uni.downloadFile({
    //   url: record.downloadUrl,
    //   success: (res) => {
    //     if (res.statusCode === 200) {
    //       uni.saveFile({
    //         tempFilePath: res.tempFilePath,
    //         success: () => {
    //           uni.showToast({
    //             title: '下载成功',
    //             icon: 'success'
    //           })
    //         }
    //       })
    //     }
    //   },
    //   fail: () => {
    //     uni.showToast({
    //       title: '下载失败',
    //       icon: 'none'
    //     })
    //   }
    // })
  }, 1500);
};

// 删除记录
const deleteRecord = (record) => {
  uni.showModal({
    title: "确认删除",
    content: "确定要删除这条生成记录吗？删除后无法恢复。",
    success: (res) => {
      if (res.confirm) {
        // 从列表中移除记录
        const index = records.value.findIndex((item) => item.id === record.id);
        if (index !== -1) {
          records.value.splice(index, 1);
        }

        uni.showToast({
          title: "删除成功",
          icon: "success",
        });

        // 实际项目中调用删除API
        // try {
        //   await RPC.post('/api/generate-record/delete', { id: record.id })
        // } catch (error) {
        //   console.error('删除失败:', error)
        // }
      }
    },
  });
};

// 加载更多数据
const loadMore = async () => {
  if (loading.value) return;

  loading.value = true;
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 模拟没有更多数据
    hasMore.value = false;

    uni.showToast({
      title: "没有更多数据了",
      icon: "none",
    });
  } catch (error) {
    console.error("加载更多失败:", error);
    uni.showToast({
      title: "加载失败，请重试",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 加载生成记录
const loadRecords = async () => {
  try {
    // 调用获取生成记录API
    // const result = await RPC.get('/api/generate-records')
    // records.value = result.data
  } catch (error) {
    console.error("加载生成记录失败:", error);
    uni.showToast({
      title: "加载失败，请重试",
      icon: "none",
    });
  }
};

// 刷新数据
const onRefresh = async () => {
  hasMore.value = true;
  await loadRecords();
};

onMounted(() => {
  loadRecords();
});

onShow(() => {
  // 页面显示时刷新数据
  loadRecords();
});
</script>

<style lang="scss" scoped>
.container {
  font-size: 14px;
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 16px;
}

.record-list {
  .record-item {
    background: white;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    gap: 12px;

    .record-info {
      flex: 1;

      .record-title {
        font-size: 16px;
        color: #333;
        font-weight: 500;
        margin-bottom: 6px;
      }

      .record-time {
        font-size: 13px;
        color: #999;
      }
    }

    .status-tag {
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: 500;

      &.completed {
        background: #e8f5e8;
        color: #52c41a;
      }

      &.failed {
        background: #fff1f0;
        color: #ff4d4f;
      }

      &.processing {
        background: #fff7e6;
        color: #fa8c16;
      }
    }

    .record-actions {
      display: flex;
      align-items: center;
      flex-shrink: 0;
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;

  .empty-text {
    color: #999;
    font-size: 14px;
    margin-top: 16px;
  }
}

.load-more {
  padding: 20px;
  text-align: center;
}
</style>