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

      <!-- 搜索栏 -->
      <el-form :model="queryParams" :inline="true" class="search-form" label-width="110px">
        <el-form-item :label="t('home.taskCenter.submission.search.name')">
          <el-input v-model="queryParams.name" :placeholder="t('home.taskCenter.submission.search.namePlaceholder')" clearable style="width: 240px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item :label="t('home.taskCenter.submission.search.projectCode')">
          <el-input v-model="queryParams.projectCode" :placeholder="t('home.taskCenter.submission.search.projectCodePlaceholder')" clearable style="width: 240px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item :label="t('home.taskCenter.submission.search.projectName')">
          <el-input v-model="queryParams.projectName" :placeholder="t('home.taskCenter.submission.search.projectNamePlaceholder')" clearable style="width: 240px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item :label="t('home.taskCenter.submission.search.status')">
          <el-select v-model="queryParams.status" :placeholder="t('home.taskCenter.submission.search.statusPlaceholder')" clearable style="width: 120px">
            <el-option :label="t('home.taskCenter.submission.search.toSubmit')" :value="0" />
            <el-option :label="t('home.taskCenter.submission.search.auditReject')" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">{{ t('home.taskCenter.submission.button.search') }}</el-button>
          <el-button icon="Refresh" @click="resetQuery">{{ t('home.taskCenter.submission.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.submission.table.id')" width="80" align="center" />
        <el-table-column prop="name" :label="t('home.taskCenter.submission.table.name')" 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="t('home.taskCenter.submission.table.type')" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.row.type === 0">{{ t('home.taskCenter.submission.table.normalDocument') }}</span>
            <span v-else-if="scope.row.type === 1">{{ t('home.taskCenter.submission.table.planDocument') }}</span>
            <span v-else>{{ scope.row.type }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="documentType" :label="t('home.taskCenter.submission.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.submission.table.status')" width="120" align="center">
          <template #default="scope">
            <DocumentStatusTag :status="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column prop="planSubmitter" :label="t('home.taskCenter.submission.table.planSubmitter')" width="120" align="center" />

        <el-table-column prop="deadline" :label="t('home.taskCenter.submission.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="overdueDays" :label="t('home.taskCenter.submission.table.overdueDays')" 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="t('home.taskCenter.submission.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.submission.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 prop="sendStatus" :label="t('home.taskCenter.submission.table.sendStatus')" width="100" align="center">
          <template #default="scope">
            <span v-if="!scope.row.sendFlag">-</span>
            <el-tag v-else-if="scope.row.sendStatus" type="success">{{ t('home.taskCenter.submission.table.sent') }}</el-tag>
            <el-tag v-else type="warning">{{ t('home.taskCenter.submission.table.notSent') }}</el-tag>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column :label="t('home.taskCenter.submission.table.action')" 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)">
              {{ t('home.taskCenter.submission.button.submit') }}
            </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)">
              {{ t('home.taskCenter.submission.button.auditLog') }}
            </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)">
              {{ t('home.taskCenter.submission.button.send') }}
            </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="t('home.taskCenter.submission.dialog.uploadTip')" type="info" :closable="false" style="margin-bottom: 20px" />
      <el-form ref="submitFormRef" :model="submitForm" :rules="submitRules" label-width="120px">
        <el-form-item :label="t('home.taskCenter.submission.dialog.file')" prop="ossId">
          <fileUpload v-model="submitForm.ossId" :limit="1" :action="'/common/resource/oss/upload'" accept=".pdf" />
        </el-form-item>
        <el-form-item :label="t('home.taskCenter.submission.dialog.effectiveDate')" prop="effectiveDate">
          <el-date-picker v-model="submitForm.effectiveDate" type="date" value-format="YYYY-MM-DD" :placeholder="t('home.taskCenter.submission.dialog.effectiveDatePlaceholder')"
            style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="submitButtonLoading" type="primary" @click="submitSubmitForm"> {{ t('home.taskCenter.submission.dialog.confirm') }} </el-button>
          <el-button @click="cancelSubmit">{{ t('home.taskCenter.submission.dialog.cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>

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

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, getCurrentInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
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 { t } = useI18n();
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: t('home.taskCenter.submission.rule.fileRequired'), trigger: 'change' }],
  effectiveDate: [{ required: true, message: t('home.taskCenter.submission.rule.effectiveDateRequired'), 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 || t('home.taskCenter.submission.message.getListFailed'));
    }
  } catch (error) {
    console.error(t('home.taskCenter.submission.message.getListFailed'), error);
    ElMessage.error(t('home.taskCenter.submission.message.getListFailed'));
  } 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 = t('home.taskCenter.submission.dialog.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(t('home.taskCenter.submission.message.submitSuccess'));
        submitDialog.visible = false;
        // 刷新任务列表
        await getTaskList();
      } catch (error) {
        console.error(t('home.taskCenter.submission.message.submitFailed'), error);
        ElMessage.error(t('home.taskCenter.submission.message.submitFailed'));
      } finally {
        submitButtonLoading.value = false;
      }
    }
  });
};

/**
 * 处理寄送
 */
const handleSend = (row: SubmissionTaskVO) => {
  ElMessageBox.confirm(t('home.taskCenter.submission.message.sendConfirm'), t('home.taskCenter.submission.message.confirmTitle'), {
    confirmButtonText: t('home.taskCenter.submission.message.confirmButton'),
    cancelButtonText: t('home.taskCenter.submission.message.cancelButton'),
    type: 'warning'
  })
    .then(async () => {
      try {
        await sendDocument(row.id);
        ElMessage.success(t('home.taskCenter.submission.message.sendSuccess'));
        // 刷新任务列表
        await getTaskList();
      } catch (error) {
        console.error(t('home.taskCenter.submission.message.sendFailed'), error);
        ElMessage.error(t('home.taskCenter.submission.message.sendFailed'));
      }
    })
    .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>
