<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">{{ t('home.taskCenter.filing.title') }}</span>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :model="queryParams" :inline="true" class="search-form" label-width="110px">
        <el-form-item :label="t('home.taskCenter.filing.search.projectCode')">
          <el-input
            v-model="queryParams.projectCode"
            :placeholder="t('home.taskCenter.filing.search.projectCodePlaceholder')"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('home.taskCenter.filing.search.projectName')">
          <el-input
            v-model="queryParams.projectName"
            :placeholder="t('home.taskCenter.filing.search.projectNamePlaceholder')"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('home.taskCenter.filing.search.centerName')">
          <el-input
            v-model="queryParams.centerName"
            :placeholder="t('home.taskCenter.filing.search.centerNamePlaceholder')"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('home.taskCenter.filing.search.name')">
          <el-input
            v-model="queryParams.name"
            :placeholder="t('home.taskCenter.filing.search.namePlaceholder')"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">{{ t('home.taskCenter.filing.button.search') }}</el-button>
          <el-button icon="Refresh" @click="resetQuery">{{ t('home.taskCenter.filing.button.reset') }}</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="t('home.taskCenter.filing.table.id')" width="80" align="center" />
        <el-table-column prop="name" :label="t('home.taskCenter.filing.table.name')" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            <el-badge v-if="scope.row.status === 3" is-dot class="status-badge" />
            <span>{{ formatDocumentName(scope.row.name) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" :label="t('home.taskCenter.filing.table.type')" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.row.type === 0">{{ t('home.taskCenter.filing.table.normalDocument') }}</span>
            <span v-else-if="scope.row.type === 1">{{ t('home.taskCenter.filing.table.planDocument') }}</span>
            <span v-else>{{ scope.row.type }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="documentType" :label="t('home.taskCenter.filing.table.documentType')" 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="t('home.taskCenter.filing.table.status')" width="120" align="center">
          <template #default="scope">
            <DocumentStatusTag :status="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column prop="folderName" :label="t('home.taskCenter.filing.table.folderName')" min-width="150" show-overflow-tooltip />
        <el-table-column prop="submitter" :label="t('home.taskCenter.filing.table.submitter')" width="120" align="center" />
        <el-table-column prop="passTime" :label="t('home.taskCenter.filing.table.passTime')" 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="t('home.taskCenter.filing.table.submitTime')" 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="t('home.taskCenter.filing.table.createTime')" 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="t('home.taskCenter.filing.table.action')"
          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)"
            >
              {{ t('home.taskCenter.filing.button.filing') }}
            </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)"
            >
              {{ t('home.taskCenter.filing.button.download') }}
            </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 { useI18n } from 'vue-i18n';
import { listFilingTasks, filingDocument } from '@/api/home/taskCenter/filing';
import { FilingTaskVO, FilingTaskFilingForm } from '@/api/home/taskCenter/filing/types';
import { downloadDocumentFile } from '@/api/document/document';
import { formatDocumentName } from '@/utils/ruoyi';
import { FolderAdd, Download } from '@element-plus/icons-vue';
import DictTag from '@/components/DictTag/index.vue';
import DocumentStatusTag from '@/components/DocumentStatusTag/index.vue';

const { t } = useI18n();
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 || t('home.taskCenter.filing.message.getListFailed'));
    }
  } catch (error) {
    console.error(t('home.taskCenter.filing.message.getListFailed'), error);
    ElMessage.error(t('home.taskCenter.filing.message.getListFailed'));
  } 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(t('home.taskCenter.filing.message.filingConfirm'));
    const filingData: FilingTaskFilingForm = {
      documentId: row.id
    };
    await filingDocument(filingData);
    ElMessage.success(t('home.taskCenter.filing.message.filingSuccess'));
    await getTaskList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error(t('home.taskCenter.filing.message.filingFailed'), error);
      ElMessage.error(t('home.taskCenter.filing.message.filingFailed'));
    }
  }
};

/**
 * 下载文件
 */
const handleDownload = async (row: FilingTaskVO) => {
  if (!row.ossId) {
    ElMessage.warning(t('home.taskCenter.filing.message.noFileToDownload'));
    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>
