<script lang="ts">
import { defineComponent } from 'vue';
import { NButton, NInput, NModal } from 'naive-ui';
import ContractViewer from '@/components/contract-compare/ContractViewer.vue';
import DiffResultPanel from '@/components/contract-compare/DiffResultPanel.vue';
import FileUpload from '@/components/common/file-upload.vue';
import {
  type CompareResultItemApi,
  createCompareTask,
  deleteCompareTask,
  fetchCompareResult,
  fetchContractTaskList
} from '@/service/api/compareTask';
import { getReviewStatusText, getReviewStatusType } from '@/service/api/reviewTask';
import { pollManager } from '@/utils/pollManager';

interface CompareResult {
  baseBoxArea: string;
  baseDiffContent: string;
  baseDiffType: 'modify' | 'insert' | 'delete';
  basePageNum: number;
  compareBoxArea: string;
  compareDiffContent: string;
  compareDiffType: 'modify' | 'insert' | 'delete';
  comparePageNum: number;
  firstPageNum: number;
  secondPageNum: number;
  id: number;
}

interface ContractTask {
  taskId: string | null;
  compareRule: string | null;
  firstContractUrl: string;
  secondContractUrl: string;
  firstContractContent?: string;
  secondContractContent?: string;
  status: number;
  deptId: string | null;
  userId: string | null;
  creator: string | null;
  createTime?: string;
  firstPageNum?: number;
  secondPageNum?: number;
}

export default defineComponent({
  name: 'IndexView',
  components: {
    ContractViewer,
    DiffResultPanel,
    FileUpload,
    NModal,
    NButton,
    NInput
  },
  data() {
    return {
      // 新建任务相关数据
      showCreateModal: false,
      createTaskForm: {
        firstContractUrl: '',
        firstContractName: '',
        secondContractUrl: '',
        secondContractName: ''
      },
      // 添加文件类型跟踪
      firstFileType: '',
      secondFileType: '',
      submittingTask: false,

      // 分页控制
      originalPageNum: 1,
      comparePageNum: 1,
      originalTotalPages: 1,
      compareTotalPages: 1,

      // 当前选中的差异项
      selectedDiff: null as CompareResult | null,

      // 对比结果数据
      compareResults: [] as CompareResult[],

      // 合同任务数据
      contractTasks: [] as ContractTask[],

      // 分页参数
      pageParams: {
        // pageNum: 1,
        // pageSize: 10
      },
      total: 0,

      searchKeyword: '',
      selectedTaskId: '' as string,
      groupedTasks: {} as Record<string, ContractTask[]>,

      // 服务器基础URL
      baseUrl: 'http://192.168.1.64:8080',

      // 当前选中的任务
      currentTask: null as ContractTask | null,

      // 加载状态
      loading: false,
      isLoadingResults: false,
      isLoadingPdf: false,
      pdfLoadError: null as string | null,
      originalPdfUrl: '',
      comparePdfUrl: '',

      // 轮询状态
      pollingTaskIds: [] as (string | number)[]
    };
  },
  computed: {
    // 计算第二个文件上传组件应该接受的文件类型
    secondFileAccept() {
      // 如果第一个文件已上传，则第二个只能上传同类型
      if (this.firstFileType) {
        return [this.firstFileType];
      }
      // 如果第二个文件已上传，则第一个只能上传同类型
      if (this.secondFileType) {
        return [this.secondFileType];
      }
      // 默认支持所有类型
      return ['pdf', 'docx', 'jpg', 'png'];
    },

    // 计算第一个文件上传组件应该接受的文件类型
    firstFileAccept() {
      // 如果第二个文件已上传，则第一个只能上传同类型
      if (this.secondFileType) {
        return [this.secondFileType];
      }
      // 如果第一个文件已上传，则第二个只能上传同类型
      if (this.firstFileType) {
        return [this.firstFileType];
      }
      // 默认支持所有类型
      return ['pdf', 'docx', 'jpg', 'png'];
    },

    // 检查当前任务是否正在轮询
    isCurrentTaskPolling(): boolean {
      return Boolean(this.currentTask?.taskId && this.pollingTaskIds.includes(this.currentTask.taskId));
    }
  },
  mounted() {
    this.fetchContractTasks();
  },
  beforeUnmount() {
    // 页面卸载时清理所有轮询
    pollManager.stopAllPolling();
  },
  methods: {
    getReviewStatusText,
    getReviewStatusType,
    // 创建新任务
    onCreateTask() {
      this.showCreateModal = true;
      this.createTaskForm = {
        firstContractUrl: '',
        firstContractName: '',
        secondContractUrl: '',
        secondContractName: ''
      };
      // 重置文件类型
      this.firstFileType = '';
      this.secondFileType = '';
    },

    // 关闭新建任务对话框
    closeCreateModal() {
      this.showCreateModal = false;
    },

    // 提交新建任务
    async submitCreateTask() {
      // 验证表单
      if (!this.createTaskForm.firstContractUrl) {
        window.$message?.error('请上传第一份合同');
        return;
      }
      if (!this.createTaskForm.firstContractName) {
        window.$message?.error('请输入第一份合同名称');
        return;
      }
      if (!this.createTaskForm.secondContractUrl) {
        window.$message?.error('请上传第二份合同');
        return;
      }
      if (!this.createTaskForm.secondContractName) {
        window.$message?.error('请输入第二份合同名称');
        return;
      }

      try {
        this.submittingTask = true;

        // 处理URL，删除域名和端口，只保留路径部分
        const formData = { ...this.createTaskForm };

        // 处理第一个URL
        if (formData.firstContractUrl) {
          try {
            const url = new URL(formData.firstContractUrl);
            formData.firstContractUrl = url.pathname;
          } catch (e) {
            console.warn('处理第一个URL时出错:', e);
            // 如果不是完整URL格式，保持原样
          }
        }

        // 处理第二个URL
        if (formData.secondContractUrl) {
          try {
            const url = new URL(formData.secondContractUrl);
            formData.secondContractUrl = url.pathname;
          } catch (e) {
            console.warn('处理第二个URL时出错:', e);
            // 如果不是完整URL格式，保持原样
          }
        }

        await createCompareTask(formData).then(res => {
          if (!res.error) {
            // 不再检查响应的具体结构，简化处理
            window.$message?.success('任务创建成功');
            this.closeCreateModal();
            this.fetchContractTasks(); // 刷新任务列表
          }
        });
      } catch (error) {
        console.error('创建任务失败:', error);
        window.$message?.error('创建任务失败，请稍后重试');
      } finally {
        this.submittingTask = false;
      }
    },

    // 高亮显示差异
    highlightDiff(item: CompareResult): void {
      this.selectedDiff = item;

      // 跳转到对应页面
      this.originalPageNum = item.basePageNum;
      this.comparePageNum = item.comparePageNum;
    },

    // 获取合同任务列表
    async fetchContractTasks(firstLoad = true) {
      this.loading = true;
      try {
        console.log('发起请求，参数:', this.pageParams);
        const response = await fetchContractTaskList(this.pageParams);

        if (!response.error) {
          console.log('API响应数据:', response);
          // 处理API返回的数据
          this.processApiResponse(response, firstLoad);
        } else {
          this.useExampleData();
        }
      } catch (error) {
        console.error('获取合同任务异常:', error);
        this.useExampleData();
      } finally {
        this.loading = false;
      }
    },

    // 处理API响应数据
    processApiResponse(response: any, firstLoad = true) {
      console.log('---------response', response);
      // 实际返回的结构是嵌套的，需要提取正确的数据
      // 检查是否有效响应
      if (!response || !response.data) {
        console.error('无效的API响应:', response);
        this.useExampleData();
        return;
      }

      // 提取实际数据，可能在data.data或response.data.rows中
      let responseData = null;
      let totalCount = 0;
      if (response.data && response.data.data && Array.isArray(response.data.data)) {
        responseData = response.data.data;
        totalCount = response.data.total || 0;
      }
      // 没有找到数据
      else {
        console.warn('找不到有效的数据数组:', response);
        this.useExampleData();
        return;
      }

      console.log('获取到的合同任务数据:', responseData);

      // 检查是否有数据
      if (!responseData || responseData.length === 0) {
        console.warn('API返回的任务列表为空');
        this.useExampleData();
        return;
      }
      if (this.currentTask) {
        const index = responseData.findIndex(task => task.taskId === this.currentTask!.taskId);
        if (index !== -1) {
          this.originalTotalPages = responseData[index].firstPageNum;
          this.compareTotalPages = responseData[index].secondPageNum;
        } else {
          console.warn('当前任务在API返回的数据中未找到');
        }
      } else {
        this.originalTotalPages = responseData[0].firstPageNum;
        this.compareTotalPages = responseData[0].secondPageNum;
      }

      // 处理数据
      this.contractTasks = responseData.map((item: any) => ({
        ...item,
        taskId: item.taskId ? String(item.taskId) : ''
      }));

      this.total = totalCount;

      console.log('处理后的任务数据:', this.contractTasks);
      console.log('总任务数量:', this.total);
      console.log('获取合同任务成功, 任务数量:', this.contractTasks.length);

      // 按日期分组数据
      this.groupTasksByDate();
      console.log('分组后的数据:', this.groupedTasks);

      // 默认选择第一条数据
      if (this.contractTasks.length > 0 && firstLoad) {
        this.selectFirstContract();
      }
    },

    // 选择第一条合同
    selectFirstContract() {
      // 找到第一个可用的任务
      const firstGroupKey = Object.keys(this.groupedTasks)[0];
      if (firstGroupKey && this.groupedTasks[firstGroupKey] && this.groupedTasks[firstGroupKey].length > 0) {
        const firstTask = this.groupedTasks[firstGroupKey][0];
        console.log('默认选中第一条合同:', firstTask);
        this.handleContractClick(firstTask);
      }
    },

    // 使用示例数据填充
    useExampleData() {
      console.log('使用示例数据填充');
      this.contractTasks = [];

      // 分组数据并选择第一条
      this.groupTasksByDate();
      if (this.contractTasks.length > 0) {
        this.selectFirstContract();
      }
    },

    // // 切换页码
    // handlePageChange(page: number) {
    //   this.pageParams.pageNum = page;
    //   this.fetchContractTasks();
    // },
    //
    // // 切换每页显示数量
    // handleSizeChange(size: number) {
    //   this.pageParams.pageSize = size;
    //   this.pageParams.pageNum = 1;
    //   this.fetchContractTasks();
    // },

    getFileName(url: string) {
      if (!url) return '-';
      try {
        return decodeURIComponent(url.split('/').pop() || '-');
      } catch {
        return url;
      }
    },

    statusText(status: number) {
      switch (status) {
        case 0:
          return '未开始';
        case 1:
          return '获取原文中';
        case 2:
          return '对比中';
        case 3:
          return '已完成';
        case 4:
          return '失败';
        default:
          return '-';
      }
    },

    groupTasksByDate() {
      // 按日期分组合同任务
      this.groupedTasks = {};

      // 如果有API返回的数据，优先使用
      if (this.contractTasks.length > 0) {
        const byDateGroup: Record<string, ContractTask[]> = {};

        // 根据任务的创建时间进行分组
        this.contractTasks.forEach(task => {
          let groupName: string;

          // 根据createTime生成分组名称
          if (task.createTime) {
            const createDate = new Date(task.createTime);
            const now = new Date();
            const diffTime = Math.abs(now.getTime() - createDate.getTime());
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

            if (diffDays <= 7) {
              groupName = '七天内';
            } else {
              const year = createDate.getFullYear();
              const month = createDate.getMonth() + 1;
              groupName = `${year}年${month}月`;
            }
          } else {
            // 如果没有createTime，使用默认分组
            groupName = '其他';
          }

          if (!byDateGroup[groupName]) {
            byDateGroup[groupName] = [];
          }

          byDateGroup[groupName].push(task);
        });

        // 排序日期分组，确保"七天内"在最前面
        const groupNames = Object.keys(byDateGroup);
        const sortOrder = ['七天内'];

        // 将其他分组按时间倒序排列（最新的在前面）
        const otherGroups = groupNames.filter(name => name !== '七天内');
        otherGroups.sort((a, b) => {
          const aMatch = a.match(/(\d{4})年(\d{1,2})月/);
          const bMatch = b.match(/(\d{4})年(\d{1,2})月/);

          if (aMatch && bMatch) {
            const aYear = Number.parseInt(aMatch[1], 10);
            const aMonth = Number.parseInt(aMatch[2], 10);
            const bYear = Number.parseInt(bMatch[1], 10);
            const bMonth = Number.parseInt(bMatch[2], 10);

            if (aYear !== bYear) {
              return bYear - aYear; // 年份倒序
            }
            return bMonth - aMonth; // 月份倒序
          }
          return 0;
        });

        sortOrder.push(...otherGroups);

        sortOrder.forEach(groupName => {
          if (byDateGroup[groupName] && byDateGroup[groupName].length > 0) {
            this.groupedTasks[groupName] = byDateGroup[groupName];
          }
        });

        return;
      }

      // 以下是示例数据，如果没有API数据则使用
      const sevenDaysGroup: ContractTask[] = [];

      // 2025年7月
      const july2025Group: ContractTask[] = [];

      // 分组数据
      if (sevenDaysGroup.length > 0) {
        this.groupedTasks['七天内'] = sevenDaysGroup;
      }
    },

    handleContractClick(task: ContractTask) {
      // 设置选中的任务
      this.selectedTaskId = task.taskId || '';
      this.currentTask = task;
      console.log('选择合同任务:', task);

      // 构建PDF URL
      try {
        // 设置PDF加载状态
        this.isLoadingPdf = true;
        this.pdfLoadError = null;

        // 构建完整PDF URL
        // 检查URL是否已经包含基础URL前缀
        const baseUrl = import.meta.env.VITE_SERVICE_BASE_URL;
        const originalUrl = task.firstContractUrl;
        const compareUrl = task.secondContractUrl;

        this.originalPdfUrl = originalUrl.startsWith('http') ? originalUrl : `${baseUrl}${originalUrl}`;
        this.comparePdfUrl = compareUrl.startsWith('http') ? compareUrl : `${baseUrl}${compareUrl}`;

        // 临时设置为较大值，以避免PDF检测前页面不显示
        // 之后PDF组件会自动更新为实际页数
        this.originalTotalPages = task.firstPageNum || 1;
        this.compareTotalPages = task.secondPageNum || 1;

        // 获取对比分析结果
        if (task.taskId) {
          this.fetchCompareResults(task.taskId);
        }

        // 延时设置加载完成
        setTimeout(() => {
          this.isLoadingPdf = false;
        }, 1000);
      } catch (error) {
        console.error('加载合同PDF失败:', error);
        this.pdfLoadError = '无法加载PDF文件';
        this.isLoadingPdf = false;
      }
    },

    // 获取合同对比分析结果
    async fetchCompareResults(taskId: string | number) {
      try {
        this.isLoadingResults = true;

        const response = await fetchCompareResult(taskId);

        if (!response || response.error) {
          this.compareResults = [];
          return;
        }

        // 提取数据，API返回结构是有data数组的格式
        let apiResults: CompareResultItemApi[] = [];

        if (Array.isArray(response.data)) {
          apiResults = response.data;
        }

        if (apiResults.length === 0) {
          console.warn('对比分析结果数据为空');
          this.compareResults = [];
          return;
        }

        // 将API返回的数据转换为CompareResult[]类型

        this.compareResults = apiResults.map(item => {
          // 转换baseDiffType: "change" => "modify"
          const baseDiffType = item.baseDiffType === 'change' ? 'modify' : item.baseDiffType;
          // 转换compareDiffType: "change" => "modify"
          const compareDiffType = item.compareDiffType === 'change' ? 'modify' : item.compareDiffType;
          return {
            baseBoxArea: item.baseBoxArea || '',
            baseDiffContent: item.baseDiffContent || '',
            baseDiffType: baseDiffType as CompareResult['baseDiffType'],
            basePageNum: item.basePageNum || 1,
            compareBoxArea: item.compareBoxArea || '',
            compareDiffContent: item.compareDiffContent || '',
            compareDiffType: compareDiffType as CompareResult['compareDiffType'],
            comparePageNum: item.comparePageNum || 1,
            firstPageNum: item.basePageNum || 1,
            secondPageNum: item.comparePageNum || 1,
            id: item.resultId || 0
          };
        });

        console.log('转换后的对比结果数据:', this.compareResults);

        // 重置选中的差异项
        this.selectedDiff = null;
      } catch (error) {
        console.error('获取对比分析结果异常:', error);
        // 清空对比结果
        this.compareResults = [];
      } finally {
        this.isLoadingResults = false;
      }
    },

    redrawDiffBoxes() {
      console.log('手动触发重绘差异框');
      // 获取引用
      const originalViewer = this.$refs.originalViewer as any;
      const compareViewer = this.$refs.compareViewer as any;

      // 调用重绘方法
      if (originalViewer && typeof originalViewer.redrawBoxes === 'function') {
        originalViewer.redrawBoxes();
      }

      if (compareViewer && typeof compareViewer.redrawBoxes === 'function') {
        compareViewer.redrawBoxes();
      }
    },

    // 文件上传成功后，更新文件列表
    handleUploadSuccess(value: { name: string; url: string }, key: 'firstContractName' | 'secondContractName') {
      console.log(value, key);
      if (!this.createTaskForm[key]) {
        try {
          const name = value.name.split('/').pop();
          this.createTaskForm[key] = name || '';
        } catch (e) {}
      }

      // 检测文件类型
      const fileName = value.name;
      const fileExt = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();

      // 更新对应的文件类型
      if (key === 'firstContractName') {
        this.firstFileType = fileExt;
      } else if (key === 'secondContractName') {
        this.secondFileType = fileExt;
      }
    },

    // 处理文件删除
    handleFileRemove(key: 'firstContractName' | 'secondContractName') {
      // 清除对应的文件类型
      if (key === 'firstContractName') {
        this.firstFileType = '';
        this.createTaskForm.firstContractName = '';
      } else if (key === 'secondContractName') {
        this.secondFileType = '';
        this.createTaskForm.secondContractName = '';
      }
    },

    // 重新执行差异识别
    recognizeAgain(taskId: string | number) {
      // 添加到轮询列表
      if (!this.pollingTaskIds.includes(taskId)) {
        this.pollingTaskIds.push(taskId);
      }

      // 开始轮询
      pollManager.retryCompareAndPoll(
        taskId,
        async () => {
          await this.fetchContractTasks(false);
        },
        // 成功回调
        completedTaskId => {
          window.$message?.success(`任务-${completedTaskId} 完成`);
          console.log(`任务 ${completedTaskId} 完成`);
          // 从轮询列表中移除
          this.pollingTaskIds = this.pollingTaskIds.filter(id => id !== completedTaskId);
          // 刷新任务列表
          this.fetchContractTasks(false);
          // 如果是当前任务，重新获取对比结果
          if (this.currentTask?.taskId === completedTaskId) {
            this.fetchCompareResults(completedTaskId);
          }
        },
        // 错误回调
        (errorTaskId) => {
          console.error(`任务 ${errorTaskId} 失败或超时`);
          // 从轮询列表中移除
          this.pollingTaskIds = this.pollingTaskIds.filter(id => id !== errorTaskId);
          window.$message?.error('差异识别失败或超时，请稍后重试');
        }
      );
    },

    handleDeleteTask(taskId: string | number) {
      deleteCompareTask([taskId]).then(res => {
        if (!res.error) {
          window.$message?.success('删除成功');
          this.fetchContractTasks();
        }
      });
    }
  }
});
</script>

<template>
  <div class="contract-compare">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧：文件列表 -->
      <div class="file-list">
        <!-- 新建任务按钮 -->
        <div class="create-task-btn" @click="onCreateTask">
          <i class="plus-icon">+</i>
          <span>新建任务</span>
        </div>

        <!-- 重绘差异按钮 -->
        <!--<div class="redraw-btn" @click="redrawDiffBoxes">-->
        <!--  <i class="refresh-icon">↻</i>-->
        <!--  <span>重绘差异</span>-->
        <!--</div>-->

        <!-- 搜索框 -->
        <!--        <div class="search-box">-->
        <!--          <i class="search-icon">🔍</i>-->
        <!--          <input v-model="searchKeyword" type="text" placeholder="输入要检索的合同名称" />-->
        <!--        </div>-->

        <!-- 文件列表 -->
        <div class="files-container">
          <NSpin :show="loading" class="h-full" content-class="h-full">
            <!-- 按日期分组的文件列表 -->
            <template v-for="(tasks, dateGroup) in groupedTasks" :key="dateGroup">
              <!-- 日期分组标题 -->
              <div class="date-group">{{ dateGroup }}</div>

              <!-- 该分组下的文件列表 -->
              <div
                v-for="(task, index) in tasks"
                :key="task.taskId || `task-${index}`"
                class="contract-item group"
                :class="{ active: selectedTaskId === (task.taskId || '') }"
                @click="handleContractClick(task)"
              >
                <!-- 原合同文件 -->
                <div class="file-row">
                  <!--                <i class="file-icon pdf-icon"></i>-->
                  <span class="file-name">{{ getFileName(task.firstContractUrl) }}</span>
                </div>

                <!-- 对比合同文件 -->
                <div class="file-row">
                  <!--                <i class="file-icon pdf-icon"></i>-->
                  <span class="file-name">{{ getFileName(task.secondContractUrl) }}</span>
                </div>

                <!-- 时间和操作 -->
                <div class="file-info">
                  <span class="file-time">{{ task.createTime }}</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>
            </template>

            <NEmpty v-if="Object.keys(groupedTasks).length === 0 && !loading" class="h-full flex-center" />
          </NSpin>
        </div>
      </div>

      <!-- 中间：原合同 -->
      <ContractViewer
        ref="originalViewer"
        type="original"
        :current-page="originalPageNum"
        :total-pages="originalTotalPages || 0"
        :compare-results="compareResults"
        :selected-diff="selectedDiff"
        :pdf-url="originalPdfUrl"
        :is-loading="isLoadingPdf"
        :load-error="pdfLoadError"
        @update:current-page="originalPageNum = $event"
        @select-diff="highlightDiff"
      />

      <!-- 右侧：对比合同 -->
      <ContractViewer
        ref="compareViewer"
        type="compare"
        :current-page="comparePageNum"
        :total-pages="compareTotalPages || 0"
        :compare-results="compareResults"
        :selected-diff="selectedDiff"
        :pdf-url="comparePdfUrl"
        :is-loading="isLoadingPdf"
        :load-error="pdfLoadError"
        @update:current-page="comparePageNum = $event"
        @select-diff="highlightDiff"
      />

      <!-- 最右侧：对比结果 -->
      <DiffResultPanel
        :compare-results="compareResults"
        :task-id="currentTask?.taskId || ''"
        :selected-diff="selectedDiff"
        :is-polling="isCurrentTaskPolling"
        :status="currentTask?.status || 0"
        @select-diff="highlightDiff"
        @recognize-again="recognizeAgain"
      />
    </div>

    <!-- 调试信息：页数显示 -->
    <!--<div v-if="true" class="debug-info">-->
    <!--  原合同页数: {{ originalTotalPages }} | 对比合同页数: {{ compareTotalPages }}-->
    <!--</div>-->

    <!-- 新建任务对话框 -->
    <NModal v-model:show="showCreateModal" preset="card" title="新建对比任务" :mask-closable="false" class="w-800px">
      <div class="create-task-form">
        <div class="box">
          <div class="form-item">
            <div class="form-label !text-primary">原合同文件</div>
            <div class="form-control">
              <FileUpload
                v-model:model-value="createTaskForm.firstContractUrl"
                :max-count="1"
                :accept="firstFileAccept"
                draggable
                :multiple="false"
                @success="handleUploadSuccess($event, 'firstContractName')"
                @remove="handleFileRemove('firstContractName')"
              />
            </div>
          </div>

          <div v-show="createTaskForm.firstContractUrl" class="form-item">
            <div class="form-label text-primary">原合同名称</div>
            <div class="form-control">
              <NInput v-model:value="createTaskForm.firstContractName" placeholder="请输入第一份合同名称" />
            </div>
          </div>
        </div>

        <NDivider vertical class="h-300px" />

        <div class="box">
          <div class="form-item">
            <div class="form-label !text-success">对比合同文件</div>
            <div class="form-control">
              <FileUpload
                v-model:model-value="createTaskForm.secondContractUrl"
                :max-count="1"
                :accept="secondFileAccept"
                draggable
                :multiple="false"
                @success="handleUploadSuccess($event, 'secondContractName')"
                @remove="handleFileRemove('secondContractName')"
              />
            </div>
          </div>

          <div v-show="createTaskForm.secondContractUrl" class="form-item">
            <div class="form-label text-success">对比合同名称</div>
            <div class="form-control">
              <NInput v-model:value="createTaskForm.secondContractName" placeholder="请输入第二份合同名称" />
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <NSpace justify="end" :size="16">
          <NButton @click="closeCreateModal">取消</NButton>
          <NButton type="primary" :loading="submittingTask" @click="submitCreateTask">创建任务</NButton>
        </NSpace>
      </template>
    </NModal>
  </div>
</template>

<style lang="scss" scoped>
.contract-compare {
  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: 200px;
  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-task-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;
  }
}

.redraw-btn {
  margin: 0 16px 16px;
  padding: 8px 0;
  background-color: #10b981;
  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: #059669;
  }

  .refresh-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-icon {
    width: 20px;
    height: 20px;
    margin-right: 6px;
    background-color: #ef4444;
    border-radius: 2px;
    display: inline-block;
  }

  .pdf-icon {
    background-color: #ef4444;
  }

  .scan-icon {
    background-color: #3b82f6;
  }

  .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;
  }

  .file-operation {
    color: #64748b;
    cursor: pointer;

    &:hover {
      color: #334155;
    }

    .dropdown-icon {
      font-size: 10px;
      margin-left: 2px;
    }
  }
}

/* 创建任务表单样式 */
.create-task-form {
  display: flex;
  gap: 30px;
  padding: 0 20px;

  .box {
    flex: 1;
  }

  .form-item {
    margin-bottom: 24px;

    .form-label {
      font-size: 14px;
      color: #334155;
      margin-bottom: 8px;
      font-weight: 500;
    }

    .form-control {
      width: 100%;
    }
  }
}

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

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

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

.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;
  }
}
</style>
