<template>
  <div class="audit-task-container">
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-bold">{{ t('home.taskCenter.audit.title') }}</span>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :model="queryParams" :inline="true" class="search-form" label-width="110px">
        <el-form-item :label="t('home.taskCenter.audit.search.projectCode')">
          <el-input
            v-model="queryParams.projectCode"
            :placeholder="t('home.taskCenter.audit.search.projectCodePlaceholder')"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('home.taskCenter.audit.search.projectName')">
          <el-input
            v-model="queryParams.projectName"
            :placeholder="t('home.taskCenter.audit.search.projectNamePlaceholder')"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('home.taskCenter.audit.search.name')">
          <el-input
            v-model="queryParams.name"
            :placeholder="t('home.taskCenter.audit.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.audit.button.search') }}</el-button>
          <el-button icon="Refresh" @click="resetQuery">{{ t('home.taskCenter.audit.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.audit.table.id')" width="80" align="center" />
        <el-table-column prop="name" :label="t('home.taskCenter.audit.table.name')" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            <el-badge v-if="scope.row.status === 1" is-dot class="status-badge" />
            <span>{{ formatDocumentName(scope.row.name) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" :label="t('home.taskCenter.audit.table.type')" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.row.type === 0">{{ t('home.taskCenter.audit.table.normalDocument') }}</span>
            <span v-else-if="scope.row.type === 1">{{ t('home.taskCenter.audit.table.planDocument') }}</span>
            <span v-else>{{ scope.row.type }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="documentType" :label="t('home.taskCenter.audit.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.audit.table.status')" width="120" align="center">
          <template #default="scope">
            <DocumentStatusTag :status="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column prop="submitter" :label="t('home.taskCenter.audit.table.submitter')" width="120" align="center" />
        <el-table-column prop="deadline" :label="t('home.taskCenter.audit.table.deadline')" width="160" align="center">
          <template #default="scope">
            <span v-if="scope.row.deadline">{{ parseTime(scope.row.deadline) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="submitTime" :label="t('home.taskCenter.audit.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.audit.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.audit.table.action')"
          width="200"
          align="center"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 1"
              type="primary"
              icon="Check"
              style="padding: 0 5px; font-size: 10px; height: 24px"
              @click="handleAudit(scope.row)"
            >
              {{ t('home.taskCenter.audit.table.audit') }}
            </el-button>
            <el-button
              v-if="scope.row.actualDocument"
              type="success"
              icon="Download"
              style="padding: 0 5px; font-size: 10px; height: 24px"
              @click="handleDownload(scope.row)"
            >
              {{ t('home.taskCenter.audit.table.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>

    <!-- 审核文档对话框 -->
    <DocumentAuditDialog v-model="auditDialog.visible" :document="auditDialog.document" @submit="handleAuditSubmit" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { listAuditTasks, auditDocument } from '@/api/home/taskCenter/audit';
import { AuditTaskVO } from '@/api/home/taskCenter/audit/types';
import { downloadDocumentFile } from '@/api/document/document';
import { formatDocumentName } from '@/utils/ruoyi';
import DictTag from '@/components/DictTag/index.vue';
import DocumentStatusTag from '@/components/DocumentStatusTag/index.vue';
import DocumentAuditDialog from '@/components/DocumentAuditDialog/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: '',
  pageNum: 1,
  pageSize: 10
});

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

// 审核对话框
const auditDialog = reactive({
  visible: false,
  document: null as AuditTaskVO | null
});

/**
 * 解析时间格式
 * @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 listAuditTasks(queryParams);
    if (res.code === 200) {
      taskList.value = res.rows || [];
      total.value = res.total || 0;
    } else {
      ElMessage.error(res.msg || t('home.taskCenter.audit.message.getListFailed'));
    }
  } catch (error) {
    console.error(t('home.taskCenter.audit.message.getListFailed'), error);
    ElMessage.error(t('home.taskCenter.audit.message.getListFailed'));
  } finally {
    loading.value = false;
  }
};

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

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

/**
 * 处理审核
 */
const handleAudit = (row: AuditTaskVO) => {
  auditDialog.document = row;
  auditDialog.visible = true;
};

/**
 * 处理审核提交
 */
const handleAuditSubmit = async (data: any) => {
  try {
    await auditDocument(data);
    ElMessage.success(t('home.taskCenter.audit.message.auditSuccess'));
    auditDialog.visible = false;
    await getTaskList();
  } catch (error) {
    console.error(t('home.taskCenter.audit.message.auditFailed'), error);
    ElMessage.error(t('home.taskCenter.audit.message.auditFailed'));
  }
};

/**
 * 下载文件
 */
const handleDownload = async (row: AuditTaskVO) => {
  if (!row.actualDocument) {
    ElMessage.warning(t('home.taskCenter.audit.message.noFileToDownload'));
    return;
  }

  await downloadDocumentFile(row.actualDocument, row.actualDocumentName || row.name);
};

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

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

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

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

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