<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import VuePdfEmbed from 'vue-pdf-embed';
import PaginationControl from '@/components/contract-compare/PaginationControl.vue';
import {
  type CreateReviewTaskParams,
  type ReviewResult,
  type ReviewTaskItem,
  createReviewTask,
  deleteReviewTask,
  fetchReviewResults,
  fetchReviewTaskList,
  getReviewStatusText,
  getReviewStatusType
} from '@/service/api/reviewTask';
import { type RuleTemplate, getRuleTemplateList } from '@/service/api/ruleTemplate';
import { fetchModelConfigList } from '@/service/api/modelConfig';
import { pollManager } from '@/utils/pollManager';

defineOptions({
  name: 'ContractReviewPage'
});

// 分页参数
const pageParams = ref({
  // pageNum: 1,
  // pageSize: 10,
  contractName: ''
});

// 总条数
const total = ref(0);

// 加载状态
const loading = ref(false);
const resultsLoading = ref(false);
const templatesLoading = ref(false);
const submitLoading = ref(false);

const modelConfigData = ref<Api.ModelConfig.ContractModelConfigVo[]>([]);

const showType = ref<0 | 1 | 2>(0);

// 轮询状态管理
const pollingTaskIds = ref<(string | number)[]>([]);

// 合同审查任务列表
const reviewTasks = ref<ReviewTaskItem[]>([]);

// 审查结果列表
const reviewResults = ref<ReviewResult[]>([]);

// 当前选中的任务
const currentTask = ref<ReviewTaskItem | null>(null);

// PDF 预览相关
const pdfUrl = ref('');
const pdfLoading = ref(false);
const pdfError = ref<string | null>(null);
const totalPages = ref(1); // 新增总页数
const currentPage = ref(1); // 当前页码

// PDF 自适应缩放比例
const scale = ref(1);
let resizeTimer: number | null = null;
let isResizing = false; // 添加防抖标志

function fitWidth() {
  // 如果正在调整大小，直接返回
  if (isResizing) return;

  isResizing = true;

  nextTick(() => {
    const container = document.querySelector(
      '.contract-review .preview-content .pages-container'
    ) as HTMLElement | null;
    const pdfPage = document.querySelector(
      '.contract-review .preview-content .vue-pdf-embed__page'
    ) as HTMLElement | null;
    if (!container || !pdfPage) {
      isResizing = false;
      return;
    }

    const containerWidth = container.clientWidth - 32; // 预留少量内边距
    const pageRect = pdfPage.getBoundingClientRect();
    if (!pageRect.width || containerWidth <= 0) {
      isResizing = false;
      return;
    }

    const currentDisplayedWidth = pageRect.width;
    const ratio = containerWidth / currentDisplayedWidth;
    const nextScale = Number((scale.value * ratio).toFixed(2));
    if (Math.abs(nextScale - scale.value) > 0.05) {
      scale.value = nextScale;
    }

    isResizing = false;
  });
}

// 规则模板列表
const ruleTemplates = ref<RuleTemplate[]>([]);

// 文件上传路径
const uploadFileUrl = ref('');

// 新建审查表单
const newTaskForm = ref<{
  contractName: string;
  contractUrl: string;
  templateId: number | null;
  modelId: number | null;
  file: File | null;
}>({
  contractName: '',
  contractUrl: '',
  templateId: null,
  file: null,
  modelId: null
});

const getCheckList = computed(() => {
  if (showType.value === 0) return reviewResults.value;
  else if (showType.value === 1) return reviewResults.value.filter(result => result.specType === 1);
  return reviewResults.value.filter(result => result.specType === 2);
});

// 检查任务是否正在轮询
const isTaskPolling = (taskId: string | number) => {
  return pollingTaskIds.value.includes(taskId);
};

// 监听上传的文件URL变化，自动设置合同名称
watch(uploadFileUrl, newUrl => {
  if (newUrl) {
    // 从URL中提取文件名
    const fileName = newUrl.split('/').pop();
    if (fileName) {
      try {
        newTaskForm.value.contractName = decodeURIComponent(fileName);
      } catch {
        newTaskForm.value.contractName = fileName;
      }
    }
  }
});

// 服务器基础URL - 从环境变量获取或使用默认值
const baseUrl = import.meta.env.VITE_SERVICE_BASE_URL; // 与 foreground-home/index.vue 中使用的相同

// 获取合同审查任务列表
async function fetchReviewTasks(firstLoad = true) {
  loading.value = true;
  try {
    const response = await fetchReviewTaskList(pageParams.value);
    console.log('获取合同审查任务响应:', response);

    // 处理API返回的数据
    if (response?.response?.data && !response.error) {
      // 显式转换类型以解决类型错误
      const rows = response.response.data.rows || [];
      reviewTasks.value = rows as ReviewTaskItem[];
      total.value = response.response.data.total || 0;
    } else {
      console.error('获取合同审查任务失败:', response);
      window.$message?.error('获取合同审查任务列表失败');
    }

    // 如果有数据，默认选中第一条
    if (reviewTasks.value.length > 0 && firstLoad) {
      selectTask(reviewTasks.value[0]);
    }
  } catch (error) {
    console.error('获取合同审查任务异常:', error);
    window.$message?.error('获取合同审查任务列表失败');
  } finally {
    loading.value = false;
  }
}

// 获取规则模板列表
async function fetchRuleTemplates() {
  templatesLoading.value = true;
  try {
    const response = await getRuleTemplateList({
      pageNum: 1,
      pageSize: 100 // 获取所有可用的模板
    });
    if (response?.data?.data && !response.error) {
      ruleTemplates.value = response.data.data;
    } else {
      console.error('获取规则模板失败:', response);
      window.$message?.error('获取规则模板失败');
    }
  } catch (error) {
    console.error('获取规则模板异常:', error);
    window.$message?.error('获取规则模板失败');
  } finally {
    templatesLoading.value = false;
  }
}

// 获取审查结果
async function getReviewResults(taskId: string | null) {
  if (!taskId) {
    reviewResults.value = [];
    return;
  }

  resultsLoading.value = true;
  try {
    const response = await fetchReviewResults(taskId);
    console.log('获取审查结果响应:', response);
    if (response?.data && !response.error) {
      // 显式转换类型以解决类型错误
      reviewResults.value = (Array.isArray(response.data) ? response.data : []) as ReviewResult[];
    } else {
      reviewResults.value = [];
    }
  } catch (error) {
    console.error('获取审查结果异常:', error);
    window.$message?.error('获取审查结果失败');
    reviewResults.value = [];
  } finally {
    resultsLoading.value = false;
  }
}

// 选择任务
function selectTask(task: ReviewTaskItem, pdfLoad = true) {
  currentTask.value = task;

  // 加载PDF
  // eslint-disable-next-line @typescript-eslint/no-unused-expressions
  pdfLoad && loadPdf(task.contractUrl);

  // 加载审查结果
  getReviewResults(task.taskId);
}

// 加载PDF预览
function loadPdf(url: string) {
  if (!url) {
    pdfUrl.value = '';
    pdfError.value = '无合同文件';
    return;
  }

  try {
    pdfLoading.value = true;
    pdfError.value = null;

    // 构建完整的PDF URL，添加前缀（如果需要）
    pdfUrl.value = url.startsWith('http') ? url : `${baseUrl}${url}`;
    currentPage.value = 1;
    console.log('PDF预览URL:', pdfUrl.value);
  } catch (error) {
    console.error('加载PDF失败:', error);
    pdfError.value = '加载PDF失败';
  } finally {
    pdfLoading.value = false;
  }
}

// 从URL获取文件名
function getFileName(url: string): string {
  if (!url) return '-';
  try {
    const fileName = url.split('/').pop();
    return fileName ? decodeURIComponent(fileName) : '-';
  } catch {
    return url;
  }
}

// 提交表单创建新审查任务
async function submitNewTask() {
  // 验证表单
  if (!newTaskForm.value.contractName) {
    window.$message?.error('请输入合同名称');
    return;
  }

  if (!newTaskForm.value.templateId) {
    window.$message?.error('请选择规则模板');
    return;
  }

  if (!newTaskForm.value.modelId) {
    window.$message?.error('请先选择模型');
    return;
  }

  if (!uploadFileUrl.value) {
    window.$message?.error('请上传合同文件');
    return;
  }

  submitLoading.value = true;

  try {
    // 处理文件URL，移除服务器基础URL和端口，只保留路径部分
    let contractUrl = uploadFileUrl.value;

    // 如果URL包含基础URL，则移除
    if (contractUrl.startsWith(baseUrl)) {
      contractUrl = contractUrl.substring(baseUrl.length);
    } else if (contractUrl.includes('://')) {
      // 处理其他情况下的完整URL
      try {
        const urlObj = new URL(contractUrl);
        contractUrl = urlObj.pathname;
      } catch (e) {
        console.error('解析URL出错:', e);
        // 如果URL解析失败，则保留原始值
      }
    }

    // 创建审查任务
    const taskParams: CreateReviewTaskParams = {
      contractName: newTaskForm.value.contractName,
      contractUrl,
      templateId: newTaskForm.value.templateId!,
      modelId: newTaskForm.value.modelId
    };

    const res = await createReviewTask(taskParams);

    if (!res.error) {
      // 成功处理
      window.$message?.success('审查任务创建成功');

      // 重置表单
      newTaskForm.value = {
        contractName: '',
        contractUrl: '',
        templateId: null,
        file: null,
        modelId: null
      };
      uploadFileUrl.value = '';

      // 刷新任务列表
      await fetchReviewTasks();
    }
  } catch (error) {
    console.error('创建审查任务异常:', error);
    window.$message?.error((error as Error).message || '创建审查任务失败');
  } finally {
    submitLoading.value = false;
  }
}

// 创建新的审查任务
function createNewReview() {
  currentTask.value = null; // 清除当前选中任务
  pdfUrl.value = ''; // 清除PDF预览

  // 加载规则模板列表
  fetchRuleTemplates();
}

// PDF加载完成处理
function onPdfLoaded(pdf: any) {
  console.log('PDF加载完成', pdf);
  pdfLoading.value = false;
  // 获取总页数
  if (pdf && typeof pdf.numPages === 'number') {
    totalPages.value = pdf.numPages;
  } else {
    totalPages.value = 1;
  }
  // 初次加载后尝试自适应
  // setTimeout(() => {
  //   fitWidth();
  // }, 300);
}

// PDF 页面渲染完成后再次尝试自适应
function onPageRendered() {
  setTimeout(() => {
    fitWidth();
  }, 200);
}

// 滚动到指定页
function scrollToPage(pageNum: number) {
  // 等待 DOM 渲染
  setTimeout(() => {
    const pdfEmbed = document.querySelector('.pages-container .vue-pdf-embed') as HTMLElement;
    if (!pdfEmbed) {
      console.warn('找不到 PDF 嵌入组件');
      return;
    }

    const pdfPages = pdfEmbed.querySelectorAll('.vue-pdf-embed__page') as NodeListOf<HTMLElement>;
    if (pdfPages.length === 0 || pageNum > pdfPages.length) {
      console.warn(`页面 ${pageNum} 不存在`);
      return;
    }

    const targetPage = pdfPages[pageNum - 1]; // 数组从0开始，页面从1开始
    if (targetPage) {
      targetPage.scrollIntoView({ behavior: 'smooth', block: 'start' });
      console.log(`滚动到页面 ${pageNum}`);
    }
  }, 100);
}

// 处理页面变化
function handlePageChange(val: number) {
  currentPage.value = val;
}

// 监听 currentPage 变化自动滚动
watch(currentPage, val => {
  scrollToPage(val);
});

// PDF加载错误处理
function onPdfError(error: Error) {
  console.error('PDF加载错误:', error);
  pdfError.value = '加载PDF文件失败';
  pdfLoading.value = false;
}

// 按照类型获取审查结果
function getReviewResultsByType(type: number) {
  return reviewResults.value.filter(result => result.specType === type);
}

function handleRecognizeAgain() {
  const taskId = currentTask.value!.taskId!;

  // 添加到轮询列表
  if (!pollingTaskIds.value.includes(taskId)) {
    pollingTaskIds.value.push(taskId);
  }

  // 使用轮询管理器进行重试和轮询
  pollManager.retryReviewAndPoll(
    taskId,
    { type: '1' },
    async () => {
      await refresh(taskId);
    },
    // 成功回调
    completedTaskId => {
      console.log(`审查任务 ${completedTaskId} 完成`);
      // 从轮询列表中移除
      pollingTaskIds.value = pollingTaskIds.value.filter(id => id !== completedTaskId);
      // 刷新任务列表
      fetchReviewTasks(false);
      // 如果是当前任务，重新选择该任务以刷新结果
      if (currentTask.value?.taskId === completedTaskId) {
        const task = reviewTasks.value.find(t => t.taskId === completedTaskId);
        if (task) {
          selectTask(task);
        }
      }
    },
    // 错误回调
    errorTaskId => {
      console.error(`审查任务 ${errorTaskId} 失败或超时`);
      // 从轮询列表中移除
      pollingTaskIds.value = pollingTaskIds.value.filter(id => id !== errorTaskId);
    }
  );
}

function fetchModelConfig() {
  fetchModelConfigList().then(res => {
    if (!res.error) {
      modelConfigData.value = res.data.data;
    }
  });
}

function handleDeleteTask(taskId: string | number) {
  deleteReviewTask([taskId]).then(res => {
    if (!res.error) {
      window.$message?.success('删除成功');
      fetchReviewTasks();
    }
  });
}

// 搜索防抖定时器
let searchTimer: NodeJS.Timeout | null = null;

// 搜索处理函数
function handleSearch() {
  // 清除之前的定时器
  if (searchTimer) {
    clearTimeout(searchTimer);
  }

  // 设置新的定时器，300ms 后执行搜索
  searchTimer = setTimeout(() => {
    // 重置页码到第一页
    // pageParams.value.pageNum = 1;
    // 重新获取任务列表
    fetchReviewTasks();
  }, 300);
}

async function refresh(taskId: string) {
  await fetchReviewTasks(false);
  const task = reviewTasks.value.find(t => t.taskId === (taskId || currentTask.value!.taskId));
  if (task) {
    selectTask(task);
  }
}

onMounted(() => {
  fetchReviewTasks();
  // 加载规则模板列表
  fetchRuleTemplates();

  fetchModelConfig();
  // 窗口大小变化时自适应
  window.addEventListener('resize', () => {
    if (resizeTimer !== null) {
      window.clearTimeout(resizeTimer);
    }
    resizeTimer = window.setTimeout(() => {
      if (!isResizing) {
        fitWidth();
      }
    }, 400);
  });
});

onBeforeUnmount(() => {
  // 清理所有轮询
  pollManager.stopAllPolling();
  // 清理搜索定时器
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  if (resizeTimer !== null) {
    window.clearTimeout(resizeTimer);
  }
  window.removeEventListener('resize', fitWidth);
  // 重置状态
  isResizing = false;
});
</script>

<template>
  <div class="contract-review">
    <div class="main-content">
      <!-- 左侧：文件列表 -->
      <div class="file-list">
        <!-- 新建审查按钮 -->
        <div class="create-review-btn" @click="createNewReview">
          <i class="plus-icon">+</i>
          <span>新建审查</span>
        </div>

        <!-- 搜索框 -->
        <div class="search-box">
          <i class="search-icon">🔍</i>
          <input v-model="pageParams.contractName" type="text" placeholder="搜索合同" @input="handleSearch" />
        </div>

        <!-- 文件列表 -->
        <div class="files-container">
          <NSpin :show="loading" class="h-full" content-class="h-full">
            <div class="date-group flex-y-center justify-between">
              <span>全部合同 ({{ total }})</span>
              <NButton type="primary" text @click="refresh">
                <template #icon>
                  <SvgIcon icon="ep:refresh"></SvgIcon>
                </template>
                刷新
              </NButton>
            </div>
            <div v-if="reviewTasks.length === 0" class="empty-state-small">暂无审查任务</div>
            <div
              v-for="task in reviewTasks"
              :key="task.taskId || Math.random().toString()"
              class="contract-item group"
              :class="{
                active: currentTask && currentTask.taskId === task.taskId
              }"
              @click="selectTask(task)"
            >
              <div class="file-row">
                <span class="file-name">{{ getFileName(task.contractUrl) }}</span>
              </div>
              <div class="file-info">
                <span class="file-time">{{ task.createBy }}</span>
                <span class="status" :class="[`status-${getReviewStatusType(task.status)}`]">
                  {{ getReviewStatusText(task.status) }}
                </span>
              </div>
              <div class="mt-10px hidden justify-end px-20px py-10px group-hover:(flex)">
                <NPopconfirm @positive-click="handleDeleteTask(task.taskId || '')">
                  是否删除该任务？
                  <template #trigger>
                    <NButton type="error" text size="tiny" @click.stop="">
                      <template #icon>
                        <SvgIcon icon="ep:delete-filled" />
                      </template>
                    </NButton>
                  </template>
                </NPopconfirm>
              </div>
            </div>
          </NSpin>
        </div>
      </div>

      <!-- 中间：合同预览 -->
      <div class="contract-preview">
        <div v-if="currentTask" class="preview-container">
          <div class="preview-header">
            <h2>{{ getFileName(currentTask.contractUrl) }}</h2>
            <PaginationControl :current-page="currentPage" :total-pages="totalPages" @page-change="handlePageChange" />
          </div>
          <div class="preview-content">
            <!-- PDF预览 -->
            <div v-if="pdfUrl" class="pdf-viewer">
              <div v-if="pdfLoading" class="loading-state">正在加载PDF...</div>
              <div v-else-if="pdfError" class="error-state">{{ pdfError }}</div>
              <div v-else class="pages-container">
                <!-- 使用单个PDF组件加载整个文档 -->
                <VuePdfEmbed
                  :source="pdfUrl"
                  class="pdf-document"
                  :scale="scale"
                  @loaded="onPdfLoaded"
                  @rendered="onPageRendered"
                  @error="onPdfError"
                />
              </div>
            </div>
            <div v-else class="pdf-placeholder">
              <span>合同预览区域</span>
              <p>此处将显示选中合同的PDF预览</p>
              <div v-if="currentTask.contractUrl" class="pdf-url">{{ currentTask.contractUrl }}</div>
            </div>
          </div>
        </div>
        <div v-else class="new-review-container">
          <div class="new-review-header">
            <h2 class="title">AI审查、快捷高效</h2>
            <p class="description">精准锚定条款原文，供应专业的风险评估、风险探究并呈现修改实例。</p>
          </div>
          <div class="new-review-content">
            <NForm>
              <NFormItem label="上传合同文件" required>
                <FileUpload
                  v-model="uploadFileUrl"
                  :max-count="1"
                  :max-size="30"
                  :accept="['pdf', 'doc', 'docx']"
                  :draggable="true"
                  :default-upload="true"
                  class="flex-[1]"
                />
              </NFormItem>

              <NFormItem label="合同名称" required>
                <NInput v-model:value="newTaskForm.contractName" placeholder="请输入合同名称" />
              </NFormItem>

              <NFormItem label="规则模板" required>
                <NSelect
                  v-model:value="newTaskForm.templateId"
                  :options="ruleTemplates.map(item => ({ label: item.templateName, value: item.id }))"
                  placeholder="请选择规则模板"
                  :loading="templatesLoading"
                  clearable
                />
              </NFormItem>

              <NFormItem label="模型选择" required>
                <NSelect
                  v-model:value="newTaskForm.modelId"
                  :options="modelConfigData"
                  placeholder="请选择模型"
                  label-field="modelName"
                  value-field="id"
                  clearable
                />
              </NFormItem>

              <div class="mt-6 flex justify-end">
                <NButton type="primary" :loading="submitLoading" @click="submitNewTask">
                  <span v-if="!submitLoading">开始审查</span>
                </NButton>
              </div>
            </NForm>
          </div>
        </div>
      </div>

      <!-- 右侧：审查结果 -->
      <Transition name="slide-fade" mode="out-in">
        <div v-if="currentTask" class="review-panel">
          <div class="panel-header flex-y-center justify-between">
            <h3>审查结果</h3>
            <div class="flex-y-center gap-x-10px" v-if="currentTask.taskId">
              <NPopconfirm @positive-click="handleRecognizeAgain">
                确认重新执行审查识别吗？
                <template #trigger>
                  <NButton :disabled="currentTask.status === 2" size="small" type="success">重新审查识别</NButton>
                </template>
              </NPopconfirm>
              <NButton size="small" type="primary" @click="getReviewResults(currentTask.taskId)">刷新审查识别</NButton>
            </div>
          </div>
          <div class="stats-info">
            <div
              class="stat-item"
              :class="{ '!bg-primary-50 shadow-[0_4px_12px_rgba(0,0,0,0.05)]': showType === 0 }"
              @click="showType = 0"
            >
              <span class="stat-label">总计</span>
              <span class="stat-value total">{{ reviewResults.length }}</span>
            </div>
            <div
              class="stat-item"
              :class="{ '!bg-primary-50 shadow-[0_4px_12px_rgba(0,0,0,0.05)]': showType === 1 }"
              @click="showType = 1"
            >
              <span class="stat-label">规则</span>
              <span class="stat-value text-#faad14">{{ getReviewResultsByType(1).length }}</span>
            </div>
            <div
              class="stat-item"
              :class="{ '!bg-primary-50 shadow-[0_4px_12px_rgba(0,0,0,0.05)]': showType === 2 }"
              @click="showType = 2"
            >
              <span class="stat-label">要素</span>
              <span class="stat-value text-#52c41a">{{ getReviewResultsByType(2).length }}</span>
            </div>
          </div>
          <div class="panel-content">
            <NSpin :show="resultsLoading" description="加载审查结果中..." class="h-full" content-class="h-full">
              <div v-if="getCheckList.length > 0" class="result-section">
                <div
                  v-for="result in getCheckList"
                  :key="result.resultId"
                  class="result-item cursor-pointer"
                  :class="{ '!b-#faad14': result.specType === 1, '!b-#52c41a': result.specType === 2 }"
                  @click="currentPage = result.pageNum || 1"
                >
                  <div class="mb-10px flex-y-center justify-between b-b-1px pb-10px">
                    <span class="font-700" :class="result.specType === 1 ? 'text-#faad14' : 'text-#52c41a'">
                      {{ result.specType === 1 ? '规则' : '要素' }}
                    </span>
                    <span class="text-#64748b">页码：{{ result.pageNum }}</span>
                  </div>
                  <div class="result-section-title">原文内容</div>
                  <div class="result-content">{{ result.contractContent }}</div>

                  <div class="result-section-title">风险等级</div>
                  <div
                    class="result-content risk"
                    :class="{
                      '!b-l-#faad14': ((result.riskLevel as string) ?? '').includes('中'),
                      '!b-l-#52c41a': ((result.riskLevel as string) ?? '').includes('低')
                    }"
                  >
                    {{ result.riskLevel || '/' }}
                  </div>

                  <div class="result-section-title">风险提示</div>
                  <div class="result-content risk">{{ result.riskTips }}</div>

                  <div class="result-section-title">审查依据</div>
                  <div class="result-content">{{ result.reviewBasis }}</div>

                  <div class="result-section-title">修改建议</div>
                  <div class="result-content modify">{{ result.modifyExample }}</div>
                </div>
              </div>

              <NEmpty
                v-show="reviewResults.length === 0"
                :description="currentTask.status === 3 ? '合同无风险' : '暂无审查结果'"
                class="h-full flex-center"
              ></NEmpty>
            </NSpin>
          </div>
        </div>
      </Transition>

      <!--<div v-else class="review-panel">-->
      <!--  <div class="panel-header">-->
      <!--    <h3>审查结果</h3>-->
      <!--  </div>-->
      <!--  <div class="panel-content">-->
      <!--    <div class="empty-records">-->
      <!--      <p>选择合同查看审差结果</p>-->
      <!--    </div>-->
      <!--  </div>-->
      <!--</div>-->
    </div>
  </div>
</template>

<style lang="scss" scoped>
.contract-review {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.main-content {
  flex: 1;
  display: flex;
  gap: 16px;
  padding: 16px;
  overflow: hidden;
}

/* 文件列表样式 */
.file-list {
  width: 300px;
  flex-shrink: 0;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.create-review-btn {
  margin: 16px;
  padding: 10px 0;
  background-color: #6366f1;
  color: white;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
  transition: background-color 0.3s;

  &:hover {
    background-color: #4f46e5;
  }

  .plus-icon {
    font-size: 16px;
    margin-right: 4px;
  }
}

.search-box {
  margin: 0 16px 16px;
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  display: flex;
  align-items: center;

  input {
    flex: 1;
    border: none;
    outline: none;
    padding: 0;
    margin-left: 6px;
    font-size: 14px;

    &::placeholder {
      color: #94a3b8;
    }
  }

  .search-icon {
    color: #94a3b8;
    font-size: 14px;
  }
}

.files-container {
  flex: 1;
  overflow-y: auto;
}

.date-group {
  padding: 8px 16px;
  font-size: 13px;
  color: #64748b;
  font-weight: 500;
}

.contract-item {
  padding: 10px 16px;
  border-bottom: 1px solid #f1f5f9;
  cursor: pointer;

  &:hover {
    background-color: #f8fafc;
  }

  &.active {
    background-color: #eff6ff;
  }
}

.file-row {
  display: flex;
  align-items: center;
  margin-bottom: 4px;

  .file-name {
    font-size: 13px;
    color: #334155;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.file-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 6px;
  font-size: 12px;

  .file-time {
    color: #64748b;
  }
}

.status {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;

  &.status-pass {
    background-color: #d1fae5;
    color: #059669;
  }

  &.status-reject {
    background-color: #fee2e2;
    color: #ef4444;
  }

  &.status-review {
    background-color: #e0f2fe;
    color: #0284c7;
  }

  &.status-waiting {
    background-color: #fef3c7;
    color: #d97706;
  }
}

.loading-state {
  padding: 20px;
  text-align: center;
  color: #64748b;
}

.empty-state-small {
  padding: 20px;
  text-align: center;
  color: #94a3b8;
  font-size: 13px;
}

/* 合同预览区域 */
.contract-preview {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.preview-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.preview-header {
  padding: 16px;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  h2 {
    font-size: 16px;
    font-weight: 600;
    color: #334155;
    margin: 0;
  }
}

.preview-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

/* PDF预览样式 */
.pdf-viewer {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.pdf-document {
  width: 100%;
  border-radius: 8px;
}

/* PDF 嵌入组件样式 */
:deep(.vue-pdf-embed) {
  width: auto !important; /* 让缩放影响实际可视宽度 */
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

:deep(.vue-pdf-embed__page) {
  position: relative !important;
  width: auto !important; /* 由 scale 控制显示宽度 */
  max-width: none; /* 取消固定 800px 限制 */
  height: auto !important;
  margin-bottom: 24px !important;
  display: block !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 4px;
}

.loading-state,
.error-state {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #64748b;
  font-size: 16px;
}

.error-state {
  color: #ef4444;
}

.pdf-placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f8fafc;
  border-radius: 8px;

  span {
    font-size: 18px;
    color: #64748b;
    margin-bottom: 8px;
  }

  p {
    color: #94a3b8;
    margin: 0 0 8px 0;
  }

  .pdf-url {
    font-size: 12px;
    color: #94a3b8;
    word-break: break-all;
    max-width: 90%;
    text-align: center;
  }
}

.pages-container {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  overflow-x: auto; /* 避免超大屏或缩放后横向溢出 */
  gap: 24px;
}
.page-item {
  display: flex;
  flex-direction: column;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  overflow: hidden;
  flex-shrink: 0;
}
.page-container {
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #fafafa;
  position: relative;
  width: 100%;
  box-sizing: border-box;
  min-height: 500px;
}
.page-number {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  z-index: 10;
}

.new-review-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background-color: #f8fafc;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .new-review-header {
    text-align: center;
    margin-bottom: 20px;

    .title {
      font-size: 24px;
      font-weight: 700;
      color: #334155;
      margin-bottom: 8px;
    }

    .description {
      font-size: 14px;
      color: #64748b;
      line-height: 1.5;
    }
  }

  .new-review-content {
    width: 100%;
    max-width: 500px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 24px;
    display: flex;
    flex-direction: column;
  }
}

.empty-state {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
    color: #cbd5e1;
  }

  p {
    color: #94a3b8;
  }
}

/* 审查结果面板 */
.review-panel {
  width: 600px;
  flex-shrink: 0;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.panel-header {
  padding: 16px;
  border-bottom: 1px solid #e2e8f0;

  h3 {
    font-size: 16px;
    font-weight: 600;
    color: #334155;
    margin: 0;
  }
}

.panel-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

/* 审查结果样式 */
.result-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #334155;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e2e8f0;
}

.result-item {
  padding: 16px;
  background-color: #f8fafc;
  border-radius: 8px;
  margin-bottom: 16px;
  border-left: 3px solid #6366f1;
}

.result-section-title {
  font-weight: 500;
  color: #334155;
  margin-bottom: 4px;
  font-size: 14px;
}

.result-content {
  font-size: 13px;
  color: #334155;
  line-height: 1.6;
  margin-bottom: 12px;
  padding: 8px 12px;
  background-color: white;
  border-radius: 4px;
  border: 1px solid #e2e8f0;
  white-space: pre-line;

  &.risk {
    border-left: 3px solid #f43f5e;
  }

  &.modify {
    border-left: 3px solid #10b981;
  }
}

.empty-records {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  p {
    color: #94a3b8;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    gap: 12px;
    padding: 12px;
  }

  .review-panel {
    width: 350px;
  }
}

@media (max-width: 992px) {
  .review-panel {
    display: none;
  }
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
    gap: 12px;
  }

  .file-list {
    width: 100%;
    max-height: 200px;
  }

  .contract-preview {
    flex: 1;
  }
}

.stats-info {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin: 12px 10px 16px;
  padding: 12px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.stat-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  cursor: pointer;
}

.stat-label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.stat-value {
  font-size: 16px;
  font-weight: 700;
  &.total {
    color: #1890ff;
  }
  &.insert {
    color: #52c41a;
  }
  &.delete {
    color: #ff4d4f;
  }
  &.modify {
    color: #faad14;
  }
}
</style>
