<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <div class="flex items-center justify-between">
          <span>任务详情</span>
          <el-button type="primary" plain size="small" @click="handleBack">返回列表</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">未开始</el-tag>
              <el-tag v-else-if="taskDetail.status === 1" type="warning" size="large">进行中</el-tag>
              <el-tag v-else-if="taskDetail.status === 2" type="success" size="large">已完成</el-tag>
              <el-tag v-else type="info" size="large">未知</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">质控项目</span>
                  <div class="text-xl font-semibold">{{ taskDetail.projectName || taskDetail.projectId }}</div>
                </div>
                <div>
                  <span class="text-sm text-gray-500">完成度</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="基本信息" :column="3" border>
          <el-descriptions-item label="创建时间">{{ parseTime(taskDetail.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="截止时间">{{ parseTime(taskDetail.deadline, '{y}-{m}-{d}') }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="3">{{ taskDetail.note || '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <!-- 任务详情列表 -->
        <div class="mb-8">
          <h3 class="text-xl font-semibold mb-3">任务列表</h3>
          <el-table v-loading="taskItemsLoading" :data="taskItems" border>
            <el-table-column prop="id" label="序号" width="80" />
            <el-table-column prop="documentName" label="文档名称" width="180" show-overflow-tooltip>
              <template #default="scope">
                {{ formatDocumentName(scope.row.documentName) }}
              </template>
            </el-table-column>
            <el-table-column prop="executorName" label="质控人" width="150" />
            <el-table-column label="状态" width="120">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 0 || scope.row.status === 3" type="info">待审核</el-tag>
                <el-tag v-else-if="scope.row.status === 1" type="success">审核通过</el-tag>
                <el-tag v-else-if="scope.row.status === 2" type="danger">审核拒绝</el-tag>
                <el-tag v-else type="warning">未知</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="executionTime" label="执行时间" width="180" />
            <el-table-column prop="finishTime" label="完成时间" width="180" />
            <el-table-column prop="note" label="备注" />
            <el-table-column label="操作" 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)">
                  审核
                </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)">
                  下载
                </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)">
                  查看审核记录
                </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="获取任务详情失败" sub-title="请重试或返回列表">
          <template #extra>
            <el-button type="primary" @click="handleBack">返回列表</el-button>
          </template>
        </el-result>
      </div>
    </el-card>

    <!-- 审核弹窗 -->
    <el-dialog v-model="auditDialog.visible" title="审核" width="500px" append-to-body>
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="结果" prop="result">
          <el-radio-group v-model="auditForm.result">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="auditForm.result === 2">
          <el-form-item label="问题类型" prop="rejectionType">
            <el-select v-model="auditForm.rejectionType" placeholder="请选择问题类型" style="width: 100%">
              <el-option v-for="dict in qc_question_type" :key="dict.value" :label="parseI18nName(dict.label)"
                :value="dict.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="意见" prop="opinion">
            <el-input v-model="auditForm.opinion" type="textarea" :rows="3" placeholder="请输入意见" />
          </el-form-item>

          <el-form-item label="指定处理人" prop="designatedDealer">
            <el-select v-model="auditForm.designatedDealer" filterable remote reserve-keyword placeholder="请输入成员昵称搜索"
              :remote-method="searchDealers" :loading="dealerSearchLoading" style="width: 100%">
              <el-option v-for="dealer in dealerOptions" :key="dealer.id"
                :label="`${dealer.name} / ${dealer.dept} --- ${dealer.phoneNumber}`" :value="dealer.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="截止日期" prop="deadline">
            <el-date-picker v-model="auditForm.deadline" type="date" value-format="YYYY-MM-DD" placeholder="请选择截止日期"
              style="width: 100%" />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelAudit">取消</el-button>
          <el-button type="primary" :loading="auditLoading" @click="submitAudit">确认</el-button>
        </div>
      </template>
    </el-dialog>

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

<script setup name="TaskDetail" lang="ts">
import { ref, reactive, onMounted, watch, computed, toRefs } from 'vue';
import { useRoute, useRouter } from 'vue-router';
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 } 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';

// 定义任务详情项类型
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 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 auditFormRef = ref<FormInstance>();
const auditDialog = reactive({
  visible: false
});
const auditLoading = ref(false);
const currentAuditRow = ref<TaskDetailItem | null>(null);

// 审核表单初始数据
const initAuditForm: TaskDetailAuditForm = {
  taskId: 0,
  detailId: 0,
  result: 1,
  rejectionType: undefined,
  opinion: undefined,
  designatedDealer: undefined,
  deadline: undefined
};

const auditForm = ref<TaskDetailAuditForm>({ ...initAuditForm });

// 审核表单验证规则
const auditRules = computed(() => ({
  result: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  rejectionType: auditForm.value.result === 2 ? [{ required: true, message: '请选择问题类型', trigger: 'change' }] : [],
  opinion: auditForm.value.result === 2 ? [{ required: true, message: '请输入意见', trigger: 'blur' }] : [],
  designatedDealer: auditForm.value.result === 2 ? [{ required: true, message: '请选择指定处理人', trigger: 'change' }] : [],
  deadline: auditForm.value.result === 2 ? [{ required: true, message: '请选择截止日期', trigger: 'change' }] : []
}));

// 处理人搜索相关
const dealerSearchLoading = ref(false);
const dealerOptions = ref<MemberNotInCenterVO[]>([]);
let dealerSearchTimer: NodeJS.Timeout | 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('获取任务详情失败');
    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 || '获取任务列表失败');
    }
  } catch (error) {
    console.error('获取任务列表失败:', error);
    proxy?.$modal.msgError('获取任务列表失败');
  } 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;
  auditForm.value = {
    ...initAuditForm,
    taskId: taskDetail.value?.id as number,
    detailId: row.id
  };
  dealerOptions.value = [];
  auditDialog.visible = true;
};

/** 搜索处理人 */
const searchDealers = async (query: string) => {
  if (!query || query.trim() === '') {
    dealerOptions.value = [];
    return;
  }

  if (dealerSearchTimer) {
    clearTimeout(dealerSearchTimer);
  }

  dealerSearchTimer = setTimeout(async () => {
    dealerSearchLoading.value = true;
    try {
      const queryParams: MemberNotInCenterQuery = {
        pageNum: 1,
        pageSize: 10,
        projectId: taskDetail.value?.projectId || 0,
        folderId: 0,
        name: query
      };
      const res = await queryMemberNotInCenter(queryParams);
      dealerOptions.value = res.rows || [];
    } catch (error) {
      console.error('搜索处理人失败:', error);
      ElMessage.error('搜索处理人失败');
    } finally {
      dealerSearchLoading.value = false;
    }
  }, 300);
};

/** 取消审核 */
const cancelAudit = () => {
  auditDialog.visible = false;
  auditFormRef.value?.resetFields();
  currentAuditRow.value = null;
};

/** 提交审核 */
const submitAudit = () => {
  auditFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      auditLoading.value = true;
      try {
        const submitData: TaskDetailAuditForm = {
          taskId: auditForm.value.taskId,
          detailId: auditForm.value.detailId,
          result: auditForm.value.result
        };

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

        await auditTaskDetail(submitData);
        proxy?.$modal.msgSuccess('审核成功');
        auditDialog.visible = false;
        // 刷新任务列表
        await fetchTaskItems();
        // 刷新任务详情
        await fetchTaskDetail();
      } catch (error) {
        console.error('审核失败:', error);
      } finally {
        auditLoading.value = false;
      }
    }
  });
};

/** 下载文件 */
const handleDownload = async (row: TaskDetailItem) => {
  if (!row.actualDocument) {
    ElMessage.warning('暂无文件可下载');
    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>
