<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">文件审批任务</span>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :model="queryParams" :inline="true" class="search-form">
        <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.name" placeholder="请输入名称" clearable style="width: 240px"
            @keyup.enter="handleQuery" />
        </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 === 1" is-dot class="status-badge" />
            <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="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 === 1" type="primary" link @click="handleAudit(scope.row)" title="审核">
              <el-icon>
                <Check />
              </el-icon>
            </el-button>
            <el-button v-if="scope.row.ossId" type="primary" link @click="handleDownload(scope.row)" title="下载">
              <el-icon>
                <Download />
              </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="auditDialog.visible" :title="auditDialog.title" width="500px" append-to-body>
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="120px">
        <el-form-item label="审批结果" prop="result">
          <el-radio-group v-model="auditForm.result">
            <el-radio :label="3">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="拒绝原因" prop="rejectReason" v-if="auditForm.result === 2">
          <el-input v-model="auditForm.rejectReason" type="textarea" :rows="3" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="auditButtonLoading" type="primary" @click="submitAuditForm"> 确认审批 </el-button>
          <el-button @click="cancelAudit">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </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 { listAuditTasks, auditDocument } from '@/api/home/taskCenter/audit';
import { AuditTaskVO, AuditTaskAuditForm } from '@/api/home/taskCenter/audit/types';
import { downloadDocumentFile } from '@/api/document/document';
import { Edit, Download, Check } from '@element-plus/icons-vue';
import DictTag from '@/components/DictTag/index.vue';
import DocumentStatusTag from '@/components/DocumentStatusTag/index.vue';

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

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

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

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

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

// 审核对话框
const auditDialog = reactive({
  visible: false,
  title: ''
});

// 审核表单ref
const auditFormRef = ref<FormInstance>();

// 审核表单数据
const auditForm = ref({
  documentId: 0,
  result: 3, // 默认通过
  rejectReason: ''
});

// 审核表单验证规则
const auditRules = {
  result: [{ required: true, message: '请选择审批结果', trigger: 'change' }],
  rejectReason: [{ required: true, message: '请输入拒绝原因', trigger: 'blur' }]
};

/**
 * 解析时间格式
 * @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 || '获取任务列表失败');
    }
  } catch (error) {
    console.error('获取任务列表失败:', error);
    ElMessage.error('获取任务列表失败');
  } finally {
    loading.value = false;
  }
};

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

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

/**
 * 处理审核
 */
const handleAudit = (row: AuditTaskVO) => {
  currentTask.value = row;
  auditForm.value = {
    documentId: row.id,
    result: 3, // 默认通过
    rejectReason: ''
  };
  auditDialog.visible = true;
  auditDialog.title = '审核文档';
  // 重置表单验证
  nextTick(() => {
    auditFormRef.value?.clearValidate();
  });
};

/**
 * 取消审核
 */
const cancelAudit = () => {
  auditDialog.visible = false;
  auditForm.value = {
    documentId: 0,
    result: 3,
    rejectReason: ''
  };
  currentTask.value = null;
};

/**
 * 提交审核表单
 */
const submitAuditForm = () => {
  auditFormRef.value?.validate(async (valid: boolean) => {
    if (valid && currentTask.value) {
      auditButtonLoading.value = true;
      try {
        const auditData: AuditTaskAuditForm = {
          documentId: auditForm.value.documentId,
          result: auditForm.value.result,
          rejectReason: auditForm.value.rejectReason
        };
        await auditDocument(auditData);
        ElMessage.success('审批成功');
        auditDialog.visible = false;
        // 刷新任务列表
        await getTaskList();
      } catch (error) {
        console.error('审批失败:', error);
        ElMessage.error('审批失败');
      } finally {
        auditButtonLoading.value = false;
      }
    }
  });
};

/**
 * 下载文件
 */
const handleDownload = async (row: AuditTaskVO) => {
  if (!row.ossId) {
    ElMessage.warning('暂无文件可下载');
    return;
  }

  await downloadDocumentFile(row.ossId, 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>
