<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="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="序号" 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>{{ formatDocumentName(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="planSubmitter" 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 prop="sendStatus" label="寄送状态" width="100" align="center">
          <template #default="scope">
            <span v-if="!scope.row.sendFlag">-</span>
            <el-tag v-else-if="scope.row.sendStatus" type="success">已寄送</el-tag>
            <el-tag v-else type="warning">未寄送</el-tag>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="280" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-if="scope.row.status === 0 || scope.row.status === 2" type="primary" icon="Upload"
              style="padding: 0 5px; font-size: 10px; height: 24px" @click="handleTaskSubmit(scope.row)">
              递交
            </el-button>
            <el-button v-hasPermi="['taskCenter:submission:logAudit']" type="info" icon="DocumentCopy"
              style="padding: 0 5px; font-size: 10px; height: 24px" @click="handleViewAuditLog(scope.row)">
              审核记录
            </el-button>
            <el-button v-if="scope.row.sendFlag && !scope.row.sendStatus" v-hasPermi="['taskCenter:submission:send']"
              type="success" icon="Promotion" style="padding: 0 5px; font-size: 10px; height: 24px"
              @click="handleSend(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>

    <!-- 递交文档对话框 -->
    <el-dialog v-model="submitDialog.visible" :title="submitDialog.title" width="500px" append-to-body>
      <el-alert title="仅支持上传 PDF 格式文件" type="info" :closable="false" style="margin-bottom: 20px" />
      <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'" accept=".pdf" />
        </el-form-item>
        <el-form-item label="生效日期" prop="effectiveDate">
          <el-date-picker v-model="submitForm.effectiveDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择生效日期"
            style="width: 100%" />
        </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, sendDocument } from '@/api/home/taskCenter/submission';
import { formatDocumentName } from '@/utils/ruoyi';
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, Promotion } 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: '',
  effectiveDate: ''
});

// 递交表单验证规则
const submitRules = {
  ossId: [{ required: true, message: '请上传文件', trigger: 'change' }],
  effectiveDate: [{ 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: '',
    effectiveDate: ''
  };
  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: '',
    effectiveDate: ''
  };
  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),
          effectiveDate: submitForm.value.effectiveDate
        };
        await submitDocument(submitData);
        ElMessage.success('递交成功');
        submitDialog.visible = false;
        // 刷新任务列表
        await getTaskList();
      } catch (error) {
        console.error('递交失败:', error);
        ElMessage.error('递交失败');
      } finally {
        submitButtonLoading.value = false;
      }
    }
  });
};

/**
 * 处理寄送
 */
const handleSend = (row: SubmissionTaskVO) => {
  ElMessageBox.confirm('确认已完成寄送？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await sendDocument(row.id);
        ElMessage.success('寄送确认成功');
        // 刷新任务列表
        await getTaskList();
      } catch (error) {
        console.error('寄送确认失败:', error);
        ElMessage.error('寄送确认失败');
      }
    })
    .catch(() => {
      // 用户取消操作
    });
};

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>
