<template>
  <view class="container">
    <!-- 生成记录列表 -->
    <view class="record-list">
      <uv-swipe-action>
        <uv-swipe-action-item
          @click="delItem(record)"
          :options="options"
          v-for="record in list"
          :key="record.id"
        >
          <view class="record-item">
            <!-- 记录信息 -->
            <view class="record-info">
              <view class="record-title">{{ record.file_name }}</view>
              <view class="record-time">
                生成时间:
                {{
                  record.CreatedAt
                    ? dayjs(record.CreatedAt).format("YYYY-MM-DD")
                    : ""
                }}
              </view>
            </view>

            <!-- 状态标签 -->
            <view
              class="status-tag"
              :class="{
                completed: record.status == 4,
                failed: record.status == 5,
              }"
            >
              <span v-if="record.status == 4">已完成</span>
              <span v-else-if="record.status == 5">生成失败</span>
              <span v-else>生成中</span>
            </view>

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

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

    <!-- 加载更多 -->
    <uv-load-more :status="loadingStatus" @loadmore="loadmore" />
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import RPC from "@/utils/request";
import dayjs from "dayjs";
import { onShow, onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";

const options = ref([
  {
    text: "删除",
    style: {
      backgroundColor: "#f56c6c",
    },
  },
]);
const delItem = (item) => {
  console.log(item);
  deleteRecord(item);
};
// 响应式数据
const loading = ref(false);
const loadingStatus = ref("loadmore");
const page = ref(1);
const list = ref([]);
const count = ref(0);

// 下载记录
const downloadRecord = (record) => {
  uni.showLoading({
    title: "准备下载...",
  });

  // #ifdef H5
  // H5端直接使用浏览器下载
  const link = document.createElement("a");
  link.href = record.result_url;
  link.download = record.file_name || "download";
  link.target = "_blank";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  uni.hideLoading();
  uni.showToast({
    title: "开始下载",
    icon: "success",
  });
  // #endif
  // #ifdef MP-WEIXIN
  // 小程序和App端使用uni.downloadFile
  uni.downloadFile({
    url: 'https://ksdt-1255846884.cos.ap-shanghai.myqcloud.com/lift-result/2025/09/24/d6180add4cd94875a1854a4febce8966.pdf',
    success: (res) => {
      console.log(res);
      if (res.statusCode === 200) {
        uni.openDocument({
		  filePath: res.tempFilePath,
		  showMenu: true,
          success: () => {
            uni.hideLoading();
            uni.showToast({
              title: "下载成功",
              icon: "success",
            });
          },
          fail: () => {
            uni.hideLoading();
            uni.showToast({
              title: "保存失败",
              icon: "none",
            });
          },
        });
      } else {
        uni.hideLoading();
        uni.showToast({
          title: "下载失败",
          icon: "none",
        });
      }
    },
    fail: () => {
      uni.hideLoading();
      uni.showToast({
        title: "下载失败",
        icon: "none",
      });
    },
  });
  // #endif
};

// 删除记录
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 loadRecords = async () => {
  loadingStatus.value === "loading";
  RPC.post("/planned_list", { page: page.value, page_size: 20 })
    .then((res) => {
      list.value = [...list.value, ...res.list];
      count.value = res.total;
      if (list.value.length >= count.value) {
        loadingStatus.value = "nomore";
      } else {
        loadingStatus.value = "loadmore";
      }
    })
    .catch(() => {
      loadingStatus.value = "loadmore";
    });
};

// 刷新数据
onPullDownRefresh(() => {
  list.value = [];
  page.value = 1;
  loadingStatus.value === "loading";
  RPC.post("/planned_list", { page: page.value, page_size: 20 })
    .then((res) => {
      list.value = [...list.value, ...res.list];
      count.value = res.total;
      if (list.value.length >= count.value) {
        loadingStatus.value = "nomore";
      } else {
        loadingStatus.value = "loadmore";
      }
    })
    .catch(() => {
      loadingStatus.value = "loadmore";
    })
    .finally(() => {
      uni.stopPullDownRefresh();
    });
});

onReachBottom(() => {
  loadmore();
});

const loadmore = () => {
  if (list.value.length >= count.value || loadingStatus.value === "loading")
    return;
  console.log("上拉加载:");
  loadingStatus.value = "loading";
  page.value = ++page.value;
  loadRecords();
};

onShow(() => {
  // 页面显示时刷新数据
  list.value = [];
  page.value = 1;
  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;
      background: #fff7e6;
      color: #fa8c16;

      &.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>