<template>
  <div class="filing-task-container">
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-bold">文件归档任务</span>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :model="queryParams" :inline="true" class="search-form">
        <el-form-item label="项目编号">
          <el-input v-model="queryParams.projectCode" placeholder="请输入项目编号" clearable style="width: 240px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="项目名称">
          <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="中心名称">
          <el-input v-model="queryParams.centerName" placeholder="请输入中心名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="queryParams.name" placeholder="请输入名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 任务列表 -->
      <el-table v-loading="loading" :data="taskList" border style="margin-top: 10px">
        <el-table-column prop="id" label="序号" width="80" align="center" />
        <el-table-column prop="name" label="名称" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            <el-badge v-if="scope.row.status === 3" is-dot class="status-badge" />
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.row.type === 0">非计划文档</span>
            <span v-else-if="scope.row.type === 1">计划文档</span>
            <span v-else>{{ scope.row.type }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="documentType" label="计划文档类型" width="120" align="center">
          <template #default="scope">
            <dict-tag v-if="scope.row.documentType" :options="plan_document_type" :value="scope.row.documentType" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <DocumentStatusTag :status="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column prop="folderName" label="所属文件夹" min-width="150" show-overflow-tooltip />
        <el-table-column prop="submitter" label="递交人" width="120" align="center" />
        <el-table-column prop="passTime" label="审核通过时间" width="160" align="center">
          <template #default="scope">
            <span v-if="scope.row.passTime">{{ parseTime(scope.row.passTime) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="submitTime" label="递交时间" width="160" align="center">
          <template #default="scope">
            <span v-if="scope.row.submitTime">{{ scope.row.submitTime }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" align="center">
          <template #default="scope">
            <span v-if="scope.row.createTime">{{ scope.row.createTime }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="200" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 3"
              v-hasPermi="['taskCenter:filing:filing']"
              type="primary"
              icon="FolderAdd"
              style="padding: 0 5px; font-size: 10px; height: 24px"
              @click="handleArchive(scope.row)"
            >
              归档
            </el-button>
            <el-button
              v-if="scope.row.ossId"
              type="success"
              icon="Download"
              style="padding: 0 5px; font-size: 10px; height: 24px"
              @click="handleDownload(scope.row)"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="getTaskList"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { listFilingTasks, filingDocument } from '@/api/home/taskCenter/filing';
import { FilingTaskVO, FilingTaskFilingForm } from '@/api/home/taskCenter/filing/types';
import { downloadDocumentFile } from '@/api/document/document';
import { FolderAdd, Download } from '@element-plus/icons-vue';
import DictTag from '@/components/DictTag/index.vue';
import DocumentStatusTag from '@/components/DocumentStatusTag/index.vue';

const { proxy } = getCurrentInstance() as any;
const { plan_document_type } = proxy.useDict('plan_document_type');

const loading = ref(false);

// 查询参数
const queryParams = reactive({
  name: '',
  projectCode: '',
  projectName: '',
  centerName: '',
  pageNum: 1,
  pageSize: 10
});

// 任务列表数据
const taskList = ref<FilingTaskVO[]>([]);
const total = ref(0);

/**
 * 解析时间格式
 * @param time 时间字符串
 * @param pattern 格式模式
 */
const parseTime = (time: string, pattern = '{y}-{m}-{d}') => {
  if (!time) return '';
  const date = new Date(time);
  const formatObj: any = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = pattern.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    if (key === 'a') return ['日', '一', '二', '三', '四', '五', '六'][value];
    if (result.length > 0 && value < 10) {
      value = '0' + value;
    }
    return String(value);
  });
  return time_str;
};

/**
 * 获取任务列表
 */
const getTaskList = async () => {
  try {
    loading.value = true;
    const res = await listFilingTasks(queryParams);
    if (res.code === 200) {
      taskList.value = res.rows || [];
      total.value = res.total || 0;
    } else {
      ElMessage.error(res.msg || '获取任务列表失败');
    }
  } catch (error) {
    console.error('获取任务列表失败:', error);
    ElMessage.error('获取任务列表失败');
  } finally {
    loading.value = false;
  }
};

/**
 * 处理搜索
 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getTaskList();
};

/**
 * 重置搜索
 */
const resetQuery = () => {
  queryParams.name = '';
  queryParams.projectCode = '';
  queryParams.projectName = '';
  queryParams.centerName = '';
  handleQuery();
};

/**
 * 处理归档
 */
const handleArchive = async (row: FilingTaskVO) => {
  try {
    await proxy?.$modal.confirm('确认要归档该文档吗？');
    const filingData: FilingTaskFilingForm = {
      documentId: row.id
    };
    await filingDocument(filingData);
    ElMessage.success('归档成功');
    await getTaskList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('归档失败:', error);
      ElMessage.error('归档失败');
    }
  }
};

/**
 * 下载文件
 */
const handleDownload = async (row: FilingTaskVO) => {
  if (!row.ossId) {
    ElMessage.warning('暂无文件可下载');
    return;
  }

  await downloadDocumentFile(row.ossId, row.name);
};

onMounted(() => {
  getTaskList();
});
</script>

<style scoped lang="scss">
.filing-task-container {
  padding: 20px;

  .flex {
    display: flex;
  }

  .justify-between {
    justify-content: space-between;
  }

  .items-center {
    align-items: center;
  }

  .text-lg {
    font-size: 1.125rem;
  }

  .font-bold {
    font-weight: 700;
  }

  .search-form {
    margin-bottom: 15px;
  }

  :deep(.el-table) {
    .cell {
      white-space: nowrap;
    }
  }

  :deep(.status-badge) {
    margin-right: 8px;
    vertical-align: middle;
  }
}
</style>
