<template>
  <div class="submission-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.name" placeholder="请输入名称" clearable style="width: 240px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <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-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="未递交" :value="0" />
            <el-option label="待审核" :value="1" />
            <el-option label="审核拒绝" :value="2" />
          </el-select>
        </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="ID" 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 === 0 || scope.row.status === 2" is-dot class="badge-dot" />
            <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="submitter" label="递交人" width="120" align="center" />
        <el-table-column prop="deadline" label="截止时间" 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="overdueDays" label="递交逾期天数" width="120" align="center">
          <template #default="scope">
            {{ calculateOverdueDays(scope.row.deadline, scope.row.submitTime, scope.row.status) }}
          </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="150" align="center" fixed="right">
          <template #default="scope">
            <el-button v-if="scope.row.status === 0 || scope.row.status === 2" type="primary" link
              @click="handleTaskSubmit(scope.row)" title="递交">
              <el-icon>
                <Upload />
              </el-icon>
            </el-button>
            <el-button v-hasPermi="['taskCenter:submission:logAudit']" type="primary" link
              @click="handleViewAuditLog(scope.row)" title="查看审核记录">
              <el-icon>
                <DocumentCopy />
              </el-icon>
            </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>

    <!-- 递交文档对话框 -->
    <el-dialog v-model="submitDialog.visible" :title="submitDialog.title" width="500px" append-to-body>
      <el-form ref="submitFormRef" :model="submitForm" :rules="submitRules" label-width="120px">
        <el-form-item label="文件" prop="ossId">
          <fileUpload v-model="submitForm.ossId" :limit="1" :action="'/common/resource/oss/upload'" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="submitButtonLoading" type="primary" @click="submitSubmitForm"> 确认递交 </el-button>
          <el-button @click="cancelSubmit">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核记录对话框 -->
    <AuditLogDialog 
      v-model:visible="auditLogDialog.visible" 
      :document-id="auditLogDialog.documentId"
      :api-function="listSubmissionAuditLog"
      i18n-prefix="home.taskCenter.submission"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, getCurrentInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { listSubmissionTasks, submitDocument, listSubmissionAuditLog } from '@/api/home/taskCenter/submission';
import fileUpload from '@/components/FileUpload/index.vue';
import DictTag from '@/components/DictTag/index.vue';
import DocumentStatusTag from '@/components/DocumentStatusTag/index.vue';
import AuditLogDialog from '@/components/AuditLogDialog/index.vue';
import { Upload, DocumentCopy } from '@element-plus/icons-vue';
import { SubmissionTaskVO, SubmissionTaskSubmitForm } from '@/api/home/taskCenter/submission/types';

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

const loading = ref(false);
const submitButtonLoading = ref(false);

// 当前任务
const currentTask = ref<SubmissionTaskVO | null>(null);

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

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

// 递交对话框
const submitDialog = reactive({
  visible: false,
  title: ''
});

// 递交表单ref
const submitFormRef = ref<FormInstance>();

// 递交表单数据
const submitForm = ref({
  ossId: ''
});

// 递交表单验证规则
const submitRules = {
  ossId: [{ required: true, message: '请上传文件', trigger: 'change' }]
};

// 审核记录对话框
const auditLogDialog = reactive({
  visible: false,
  documentId: 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;
};

/**
 * 计算逾期天数
 * @param deadline 截止日期
 * @param submitTime 递交日期
 * @param status 状态
 */
const calculateOverdueDays = (deadline: string, submitTime: string, status: number) => {
  // 如果截止日期为空，返回 '-'
  if (!deadline) return '-';

  const deadlineDate = new Date(deadline);
  const today = new Date();
  // 设置时间为当天开始，避免时间部分影响比较
  today.setHours(0, 0, 0, 0);

  // 未递交的情况
  if (status === 0) {
    // 如果截止日期不早于今天，返回 '-'
    if (deadlineDate >= today) {
      return '-';
    }
    // 计算今天到截止日期的天数差
    const timeDiff = today.getTime() - deadlineDate.getTime();
    const dayDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
    return dayDiff > 0 ? dayDiff : '-';
  }
  // 已递交的情况
  else if (status === 1 || status === 2) {
    // 如果递交日期为空，按未递交处理
    if (!submitTime) {
      if (deadlineDate >= today) {
        return '-';
      }
      const timeDiff = today.getTime() - deadlineDate.getTime();
      const dayDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
      return dayDiff > 0 ? dayDiff : '-';
    }

    const submitDate = new Date(submitTime);
    // 设置时间为当天开始，避免时间部分影响比较
    submitDate.setHours(0, 0, 0, 0);

    // 如果递交日期早于等于截止日期，返回 '-'
    if (submitDate <= deadlineDate) {
      return '-';
    }
    // 计算递交日期与截止日期的天数差
    const timeDiff = submitDate.getTime() - deadlineDate.getTime();
    const dayDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
    return dayDiff > 0 ? dayDiff : '-';
  }
  // 其他状态返回 '-'
  else {
    return '-';
  }
};

/**
 * 获取任务列表
 */
const getTaskList = async () => {
  try {
    loading.value = true;
    const res = await listSubmissionTasks(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.status = undefined;
  queryParams.projectCode = '';
  queryParams.projectName = '';
  queryParams.centerName = '';
  handleQuery();
};

/**
 * 处理任务递交
 */
const handleTaskSubmit = (row: SubmissionTaskVO) => {
  currentTask.value = row;
  submitForm.value = {
    ossId: ''
  };
  submitDialog.visible = true;
  submitDialog.title = '递交文档';
  // 重置表单验证
  nextTick(() => {
    submitFormRef.value?.clearValidate();
  });
};

/**
 * 查看审核记录
 */
const handleViewAuditLog = (row: SubmissionTaskVO) => {
  auditLogDialog.documentId = row.id;
  auditLogDialog.visible = true;
};

/**
 * 取消递交
 */
const cancelSubmit = () => {
  submitDialog.visible = false;
  submitForm.value = {
    ossId: ''
  };
  currentTask.value = null;
};

/**
 * 提交递交表单
 */
const submitSubmitForm = () => {
  submitFormRef.value?.validate(async (valid: boolean) => {
    if (valid && currentTask.value) {
      submitButtonLoading.value = true;
      try {
        const submitData: SubmissionTaskSubmitForm = {
          documentId: currentTask.value.id,
          ossId: Number(submitForm.value.ossId)
        };
        await submitDocument(submitData);
        ElMessage.success('递交成功');
        submitDialog.visible = false;
        // 刷新任务列表
        await getTaskList();
      } catch (error) {
        console.error('递交失败:', error);
        ElMessage.error('递交失败');
      } finally {
        submitButtonLoading.value = false;
      }
    }
  });
};

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

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

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

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

  .badge-dot {
    margin-right: 8px;
    vertical-align: middle;
  }
}
</style>
