<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <div class="flex items-center justify-between">
          <span>{{ t('qc.task.detail.title') }}</span>
          <el-button type="primary" plain size="small" @click="handleBack">{{ t('qc.task.detail.backToList') }}</el-button>
        </div>
      </template>

      <div v-if="loading" class="text-center py-10">
        <el-skeleton :rows="15" animated />
      </div>

      <div v-else-if="taskDetail" class="detail-content">
        <!-- 顶部布局：左上角任务名称和状态，右上角项目名称和完成度 -->
        <el-row :gutter="20" class="mb-6">
          <el-col :span="12">
            <div class="flex items-center">
              <h1 class="text-2xl font-bold mr-4">{{ taskDetail.name }}</h1>
              <el-tag v-if="taskDetail.status === 0" type="info" size="large">{{ t('qc.task.status.notStarted') }}</el-tag>
              <el-tag v-else-if="taskDetail.status === 1" type="warning" size="large">{{ t('qc.task.status.inProgress') }}</el-tag>
              <el-tag v-else-if="taskDetail.status === 2" type="success" size="large">{{ t('qc.task.status.completed') }}</el-tag>
              <el-tag v-else type="info" size="large">{{ t('qc.task.status.unknown') }}</el-tag>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="flex flex-col items-end">
              <div class="mb-4 p-3 bg-gray-50 rounded-lg w-full max-w-md">
                <div class="mb-2">
                  <span class="text-sm text-gray-500">{{ t('qc.task.detail.qcProject') }}</span>
                  <div class="text-xl font-semibold">{{ taskDetail.projectName || taskDetail.projectId }}</div>
                </div>
                <div>
                  <span class="text-sm text-gray-500">{{ t('qc.task.detail.completion') }}</span>
                  <div class="mt-1">
                    <el-progress :percentage="Math.round((Number(taskDetail.schedule) || 0) * 100 * 100) / 100"
                      :stroke-width="12" :show-text="true" :format="(percentage) => `${percentage}%`"
                      :empty-color="'#e0e0e0'" color="#409eff" style="width: 100%" />
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>

        <el-divider />

        <!-- 任务基本信息 -->
        <el-descriptions :title="t('qc.task.detail.basicInfo')" :column="3" border>
          <el-descriptions-item :label="t('qc.task.detail.createTime')">{{ parseTime(taskDetail.createTime) }}</el-descriptions-item>
          <el-descriptions-item :label="t('qc.task.detail.deadline')">{{ parseTime(taskDetail.deadline, '{y}-{m}-{d}') }}</el-descriptions-item>
          <el-descriptions-item :label="t('qc.task.detail.note')" :span="3">{{ taskDetail.note || t('qc.task.detail.noNote') }}</el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <!-- 任务详情列表 -->
        <div class="mb-8">
          <h3 class="text-xl font-semibold mb-3">{{ t('qc.task.detail.taskList') }}</h3>
          <el-table v-loading="taskItemsLoading" :data="taskItems" border>
            <el-table-column prop="id" :label="t('qc.task.detail.index')" width="80" />
            <el-table-column prop="documentName" :label="t('qc.task.detail.documentName')" width="180" show-overflow-tooltip>
              <template #default="scope">
                {{ formatDocumentName(scope.row.documentName) }}
              </template>
            </el-table-column>
            <el-table-column prop="executorName" :label="t('qc.task.detail.executor')" width="150" />
            <el-table-column :label="t('qc.task.detail.status')" width="120">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 0 || scope.row.status === 3" type="info">{{ t('qc.task.detailStatus.pending') }}</el-tag>
                <el-tag v-else-if="scope.row.status === 1" type="success">{{ t('qc.task.detailStatus.approved') }}</el-tag>
                <el-tag v-else-if="scope.row.status === 2" type="danger">{{ t('qc.task.detailStatus.rejected') }}</el-tag>
                <el-tag v-else type="warning">{{ t('qc.task.detailStatus.unknown') }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="executionTime" :label="t('qc.task.detail.executionTime')" width="180" />
            <el-table-column prop="finishTime" :label="t('qc.task.detail.finishTime')" width="180" />
            <el-table-column prop="note" :label="t('qc.task.detail.note')" />
            <el-table-column :label="t('qc.task.detail.action')" width="280" align="center" fixed="right">
              <template #default="scope">
                <el-button
                  v-if="taskDetail?.status === 1 && (scope.row.status === 0 || scope.row.status === 3) && scope.row.executor === userStore.userId"
                  v-hasPermi="['qc:task:audit']" type="primary" icon="Check"
                  style="padding: 0 5px; font-size: 10px; height: 24px" @click="handleAudit(scope.row)">
                  {{ t('qc.task.detail.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('qc.task.detail.download') }}
                </el-button>
                <el-button v-hasPermi="['qc:task:logAudit']" type="warning" icon="Document"
                  style="padding: 0 5px; font-size: 10px; height: 24px" @click="handleViewLog(scope.row)">
                  {{ t('qc.task.detail.viewLog') }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="mt-4">
            <pagination v-show="taskItemsTotal > 0" :total="taskItemsTotal" v-model:page="taskItemsQuery.pageNum"
              v-model:limit="taskItemsQuery.pageSize" @pagination="handleTaskItemsPagination" />
          </div>
        </div>
      </div>

      <div v-else class="text-center py-20">
        <el-result icon="error" :title="t('qc.task.detail.errorTitle')" :sub-title="t('qc.task.detail.errorSubtitle')">
          <template #extra>
            <el-button type="primary" @click="handleBack">{{ t('qc.task.detail.backToList') }}</el-button>
          </template>
        </el-result>
      </div>
    </el-card>

    <!-- 审核弹窗 -->
    <QcAuditDialog 
      v-model="auditDialog.visible" 
      :task-detail="currentAuditRow" 
      :qc-question-type="qc_question_type"
      :dealer-search-method="searchDealersForComponent"
      @submit="handleAuditSubmit" 
    />

    <!-- 审核记录弹窗 -->
    <QcLogDialog v-model="logDialogVisible" :detail-id="currentLogDetailId" />
  </div>
</template>

<script setup name="TaskDetail" lang="ts">
import { ref, reactive, onMounted, watch, computed, toRefs, getCurrentInstance } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { getTask, listTaskDetail, auditTaskDetail } from '@/api/qc/task';
import { TaskVO, TaskDetailAuditForm } from '@/api/qc/task/types';
import { downloadDocumentFile } from '@/api/document/document';
import { queryMemberNotInCenter } from '@/api/project/management';
import { MemberNotInCenterVO, MemberNotInCenterQuery } from '@/api/project/management/types';
import { ElMessage } from 'element-plus';
import type { FormInstance, ComponentInternalInstance } from 'element-plus';
import { useUserStore } from '@/store/modules/user';
import { parseI18nName } from '@/utils/i18n';
import { formatDocumentName } from '@/utils/ruoyi';
import QcLogDialog from '@/components/QcLogDialog/index.vue';
import QcAuditDialog from '@/components/QcAuditDialog/index.vue';

// 定义任务详情项类型
interface TaskDetailItem {
  id: number;
  document: number;
  documentName: string;
  ossId: number;
  actualDocument: string;
  actualDocumentName: string;
  executor: number;
  executorName: string;
  status: number;
  note: string;
  executionTime: string;
  finishTime: string;
}

// 任务列表数据
const taskItems = ref<TaskDetailItem[]>([]);
const taskItemsLoading = ref(false);
const taskItemsTotal = ref(0);
const taskItemsQuery = ref({
  pageNum: 1,
  pageSize: 10,
  projectId: undefined,
  taskId: undefined,
  documentName: undefined,
  status: undefined
});

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const { qc_question_type } = toRefs<any>(proxy?.useDict('qc_question_type'));

// 从路由参数获取任务ID
const taskId = computed(() => {
  const id = route.query.id;
  if (!id) return undefined;
  const numId = typeof id === 'string' ? parseInt(id) : id;
  return numId;
});

const loading = ref(true);
const taskDetail = ref<TaskVO | null>(null);

// 审核相关
const auditDialog = reactive({
  visible: false
});
const currentAuditRow = ref<TaskDetailItem | null>(null);

// 审核记录相关
const logDialogVisible = ref(false);
const currentLogDetailId = ref<number | undefined>(undefined);

const fetchTaskDetail = async () => {
  if (!taskId.value) return;

  try {
    loading.value = true;
    const res = await getTask(taskId.value);
    taskDetail.value = res.data;
    // 获取任务列表
    await fetchTaskItems();
  } catch (error) {
    console.error('获取任务详情失败:', error);
    proxy?.$modal.msgError(t('qc.task.message.getDetailFailed'));
    taskDetail.value = null;
  } finally {
    loading.value = false;
  }
};

/** 获取任务列表 */
const fetchTaskItems = async () => {
  if (!taskDetail.value?.id) return;

  try {
    taskItemsLoading.value = true;
    taskItemsQuery.value.projectId = taskDetail.value.projectId;
    taskItemsQuery.value.taskId = taskDetail.value.id;

    const res = await listTaskDetail(taskItemsQuery.value);
    if (res.code === 200) {
      taskItems.value = res.rows;
      taskItemsTotal.value = res.total;
    } else {
      proxy?.$modal.msgError(res.msg || t('qc.task.message.getTaskItemsFailed'));
    }
  } catch (error) {
    console.error('获取任务列表失败:', error);
    proxy?.$modal.msgError(t('qc.task.message.getTaskItemsFailed'));
  } finally {
    taskItemsLoading.value = false;
  }
};

/** 任务列表分页变化 */
const handleTaskItemsPagination = (pageNum: number, pageSize: number) => {
  taskItemsQuery.value.pageNum = pageNum;
  taskItemsQuery.value.pageSize = pageSize;
  fetchTaskItems();
};

/** 审核任务 */
const handleAudit = (row: TaskDetailItem) => {
  currentAuditRow.value = row;
  auditDialog.visible = true;
};

/** 搜索处理人（供组件使用） */
const searchDealersForComponent = async (query: string): Promise<MemberNotInCenterVO[]> => {
  try {
    const queryParams: MemberNotInCenterQuery = {
      pageNum: 1,
      pageSize: 10,
      projectId: taskDetail.value?.projectId || 0,
      folderId: 0,
      name: query
    };
    const res = await queryMemberNotInCenter(queryParams);
    return res.rows || [];
  } catch (error) {
    console.error('搜索处理人失败:', error);
    ElMessage.error(t('qc.task.message.searchDealerFailed'));
    return [];
  }
};

/** 处理审核提交 */
const handleAuditSubmit = async (data: any) => {
  try {
    const submitData: TaskDetailAuditForm = {
      taskId: taskDetail.value?.id as number,
      detailId: currentAuditRow.value?.id as number,
      result: data.result
    };

    // 驳回时添加额外字段
    if (data.result === 2) {
      submitData.rejectionType = data.rejectionType;
      submitData.opinion = data.opinion;
      submitData.designatedDealer = data.designatedDealer;
      submitData.deadline = data.deadline;
    }

    await auditTaskDetail(submitData);
    proxy?.$modal.msgSuccess(t('qc.task.message.auditSuccess'));
    auditDialog.visible = false;
    // 刷新任务列表
    await fetchTaskItems();
    // 刷新任务详情
    await fetchTaskDetail();
  } catch (error) {
    console.error(t('qc.task.message.auditFailed'), error);
  }
};

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

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

/** 查看审核记录 */
const handleViewLog = (row: TaskDetailItem) => {
  currentLogDetailId.value = row.id;
  logDialogVisible.value = true;
};

const handleBack = () => {
  router.push('/task');
};

watch(
  () => route.query.id,
  (newId) => {
    if (newId) {
      fetchTaskDetail();
    }
  }
);

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

<style scoped>
.detail-content {
  width: 100%;
  margin: 0;
}

/* 确保卡片内容占满宽度 */
:deep(.el-card__body) {
  padding: 20px;
}

/* 调整描述列表的样式 */
:deep(.el-descriptions) {
  margin-bottom: 20px;
}

/* 调整表格的样式 */
:deep(.el-table) {
  margin-top: 20px;
}
</style>
