<template>
  <div class="push-system">
    <!-- 顶部区域：高度 240px -->
    <div class="ps-top">
      <div class="ps-top-inner">
        <div class="ps-title">信息中心不可移动文物资源数据库数据推送系统</div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="ps-content w1100">
      <!-- 上传区域：仅允许 .xls 文件 -->
      <div class="upload-wrapper">
        <el-upload v-if="!selectedFileName" class="upload" drag action="#" :auto-upload="false" accept=".xls"
          :show-file-list="true" :before-upload="beforeUpload" :on-change="onFileChange" ref="uploadRef">
          <img class="upload-icon" src="@/assets/img/Inbox.svg" alt="">
          <div class="el-upload__text">点击或拖拽文件到此处上传</div>
          <div class="el-upload__tip">支持扩展名：.xls</div>
        </el-upload>
        <div v-else class="file-bar">
          <div class="file-info">
            <el-icon class="file-icon">
              <Document />
            </el-icon>
            <span class="file-name">{{ selectedFileName }}</span>
          </div>
          <div class="file-actions">
            <div text @click="clearSelectedFile" class="clear-btn">
              <img src="@/assets/img/DeleteOutlined.svg" alt="">
            </div>
            <span class="action-divider"></span>
            <div link class="push-btn" @click="startPush">
              <img src="@/assets/img/push.svg" alt="">
              <span class="push-text">开始推送</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 推送内容：切换推送中 / 已完成 -->
      <el-tabs v-model="activeTab" class="ps-tabs">
        <el-tab-pane :label="`推送中（${runningTotal}）`" name="running">
          <div v-loading="runningLoading" class="loading-container">
            <ul class="task-list" v-if="runningList.length > 0 && !runningLoading">
              <li v-for="(item, idx) in runningPageItems" :key="idx" class="task-item">
                <div class="task-left">
                  <div class="task-title" :title="item.title">{{ item.title }}</div>
                  <div class="task-status">{{ getStatusText(item.status) }}</div>
                </div>
                <div class="cancel-btn" v-if="item.status === 0" @click="cancelPush(item)">取消</div>
              </li>
            </ul>
            <div v-if="!runningList.length" class="empty">暂无推送任务</div>
          </div>
          <div class="pagination">
            <el-pagination background layout="prev, pager, next" v-model:current-page="runningPageNum"
              :page-size="runningPageSize" :total="runningTotal" @current-change="onRunningPageChange" />
          </div>
        </el-tab-pane>
        <el-tab-pane :label="`已完成（${doneTotal}）`" name="done">
          <div v-loading="doneLoading" class="loading-container">
            <ul class="task-list" v-if="doneList.length > 0 && !doneLoading">
              <li v-for="(item, idx) in donePageItems" :key="idx" class="task-item">
                <div class="task-left">
                  <div class="task-title" :title="item.title + ' | ' + item.num">{{ item.title }} | {{ item.num }}</div>
                  <div class="task-status">推送时间：{{ item.updateTime }}</div>
                </div>
                <!-- <div class="task-right">
                  <el-button link type="primary">查看</el-button>
                </div> -->
              </li>
            </ul>
            <div v-if="!doneList.length" class="empty">暂无已完成任务</div>
          </div>
          <div class="pagination">
            <el-pagination background layout="prev, pager, next" v-model:current-page="donePageNum"
              :page-size="donePageSize" :total="doneTotal" @current-change="onDonePageChange" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import api from '@/api'

const activeTab = ref('running')
const uploadRef = ref()
const selectedFileName = ref('')
const selectedFile = ref(null)
const runningList = ref([])
const runningLoading = ref(true)
const doneList = ref([])
const doneLoading = ref(true)
const runningTotal = ref(0)
const doneTotal = ref(0)
// 分页：推送中
const runningPageNum = ref(1)
const runningPageSize = 10
const runningPageItems = computed(() => runningList.value)
function onRunningPageChange(page) {
  runningPageNum.value = page
  fetchRunningList()
}

// 分页：已完成
const donePageNum = ref(1)
const donePageSize = 10
const donePageItems = computed(() => doneList.value)
function onDonePageChange(page) {
  donePageNum.value = page
  fetchDoneList()
}

function beforeUpload(file) {
  // 仅允许 .xls 文件
  const isXls = /\.xls$/i.test(file.name)
  if (!isXls) {
    ElMessage.error('仅支持 .xls 文件上传')
  }
  return isXls
}

function onFileChange(file) {
  const fileName = file?.name || file?.raw?.name || ''
  const isXls = /\.xls$/i.test(fileName)
  if (!isXls) {
    ElMessage.error('仅支持 .xls 文件上传')
    selectedFileName.value = ''
    selectedFile.value = null
    if (uploadRef.value) uploadRef.value.clearFiles()
    return
  }

  selectedFile.value = file.raw || file
  selectedFileName.value = fileName
}

async function cancelPush(item) {
  try {
    await api.cancelTaskApi(item.id)
    ElMessage.success('取消成功')
    fetchRunningList()
  } catch (e) {
    ElMessage.error(e?.message || '取消失败')
  }
}

function clearSelectedFile() {
  selectedFileName.value = ''
  selectedFile.value = null
  if (uploadRef.value) uploadRef.value.clearFiles()
}

function getStatusText(status) {
  const s = Number(status)
  switch (s) {
    case -1:
      return '推送失败'
    case 0:
      return '等待中'
    case 1:
      return '成功'
    case 2:
      return '推送中'
    default:
      return '未知状态'
  }
}

async function startPush() {
  if (!selectedFile.value) {
    ElMessage.warning('请先上传 .xls 文件')
    return
  }
  const formData = new FormData()
  formData.append('file', selectedFile.value)
  try {
    await api.pushSceneApi(formData)
    // ElMessage.success('已开始推送')
    clearSelectedFile()
    activeTab.value = 'running'
    runningPageNum.value = 1
    await fetchRunningList()
  } catch (e) {

    ElMessageBox.alert(e?.message || '推送失败', '错误提示', { type: 'error' })
  }
}

async function fetchRunningList() {
  runningLoading.value = true
  try {
    const res = await api.getTaskListApi({
      pageSize: runningPageSize,
      pageNo: runningPageNum.value,
      status: 0,
    })
    const records = res?.pageData || res?.records || res?.list || res?.rows || []
    runningList.value = Array.isArray(records) ? records : []
    runningTotal.value = res?.total || res?.count || res?.page?.total || res?.page?.count || runningList.value.length || 0
    runningLoading.value = false
  } catch (e) {
    console.error('获取推送中任务失败:', e)
    runningList.value = []
    runningTotal.value = 0
  }
}

async function fetchDoneList() {
  doneLoading.value = true
  try {
    const res = await api.getTaskListApi({
      pageSize: donePageSize,
      pageNo: donePageNum.value,
      status: 1,
    })
    doneList.value = []
    const records = res?.pageData || res?.records || res?.list || res?.rows || []
    doneList.value = Array.isArray(records) ? records : []
    doneTotal.value = res?.total || res?.count || res?.page?.total || res?.page?.count || doneList.value.length || 0
    doneLoading.value = false
  } catch (e) {
    console.error('获取已完成任务失败:', e)
    doneList.value = []
    doneTotal.value = 0
  }
}

onMounted(() => {
  fetchRunningList()
  fetchDoneList()
})

// 切换标签时，根据状态刷新对应列表
watch(activeTab, (val) => {
  if (val === 'running') {
    runningPageNum.value = 1
    fetchRunningList()
  } else if (val === 'done') {
    donePageNum.value = 1
    fetchDoneList()
  }
})
</script>
<style>
.el-popup-parent--hidden {
  width: 100% !important;
}

.el-message-box__container {
  padding: 48px;
}

.el-message-box__header {
  border-bottom: 1px solid #f5f5f5;
}

.el-message-box__btns {
  border-top: 1px solid #f5f5f5;
}

.el-button:hover {
  background-color: #A9947D;
  border-color: #A9947D;
}

.el-button:active {
  background: #76614A;
  border-color: #76614A;
}
</style>
<style lang="scss" scoped>
.push-system {
  background: #f5f0ea;
  height: 100vh;
}

.ps-top {
  height: 240px;
  background-image: url('@/assets/img/home-bg.png');
  background-repeat: no-repeat;
  background-position: right top;
  background-size: auto 100%;

  .ps-top-inner {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .ps-title {
    width: 671px;
    height: 106px;
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: bold;
    font-size: 40px;
    color: #781C0B;
    letter-spacing: 4px;
    text-align: center;
    font-style: normal;
    text-transform: none;
  }
}

.ps-content {
  padding: 0px 0 40px;
}

.upload-wrapper {
  width: 1200px;
  height: 156px;
  margin: 0 0 24px;

  :deep(.el-upload-dragger) {
    width: 1200px;
    border: none;
  }

  :deep(.el-upload) {
    --el-upload-dragger-padding-horizontal: 34px;
  }
}

.upload {
  .upload-icon {
    width: 48px;
    height: 48px;
  }

  .el-upload__text {
    font-size: 16px;
    color: rgba(0, 0, 0, 0.85);
  }

  .el-upload__tip {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.45);
  }
}

.file-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  padding: 0 0 0 64px;
  border-radius: 6px;
  height: 158px;

  .file-actions {
    display: flex;
    align-items: center;
  }

  .push-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 264px;
    color: #a46a4b;
    padding: 0 8px;
    cursor: pointer;
    gap: 16px;

    span {
      display: flex;
      flex-direction: column;
    }
  }

  .push-btn :deep(.el-icon) {
    font-size: 32px;
    color: #a46a4b;
    margin-right: 8px;
  }
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

// .file-icon {
//   color: #a46a4b;
// }

.file-name {
  color: #333;
}

.push-text {
  color: #666;
  font-size: 16px;
  vertical-align: middle;
}

.clear-btn {
  color: #a46a4b;
  margin-right: 54px;
  cursor: pointer;
}

.action-divider {
  width: 2px;
  height: 158px;
  background: #FAFAFA;
  display: inline-block;
}

.ps-tabs {
  background: #fff;
  padding: 40px 64px;
  border-radius: 6px;

  :deep(.el-tabs__item) {
    color: rgba(0, 0, 0, 0.5);
  }

  :deep(.el-tabs__item.is-active) {
    color: #93795D;
  }

  :deep(.el-tabs__nav-wrap:after) {
    height: 1px;
    background-color: #f5f5f5;
  }
}

.loading-container {
  height: 35vh;
}

.task-list {
  margin: 0;
  padding: 0;
  list-style: none;
  height: 35vh;
  overflow: auto;
}

.task-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 8px;
  border-bottom: 1px solid #F5F5F5;

  .cancel-btn {
    cursor: pointer;
    color: #A62525;
  }
}

.task-title {
  max-width: 900px;
  font-size: 15px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.task-status {
  margin-top: 4px;
  font-size: 13px;
  color: #8c8c8c;
}

.empty {
  padding: 24px;
  color: #9c9c9c;
  text-align: center;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding-top: 44px;
}

:deep(.el-button:hover) {
  background-color: #93795D;
  color: #fff;
}
</style>
