index.vue 25 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
<template>
    <div class="p-4">
      <BasicTable @register="registerTable">
        <template #toolbar>
          <a-button
            type="primary"
            @click="handleCreate"
            :style="{ borderRadius: '5px 5px 5px 5px' }"
          >
            新增申请
          </a-button>
          <a-button
            type="default"
            @click="handleOpenFileTypeDrawer"
            :style="{ borderRadius: '5px 5px 5px 5px', marginLeft: '8px' }"
          >
            新增文件分类
          </a-button>
          <a-button
            type="default"
            @click="handleOpenStampDrawer"
            :style="{ borderRadius: '5px 5px 5px 5px', marginLeft: '8px' }"
          >
            新增盖章
          </a-button>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <TableAction
              :actions="[
                {
                  label: '编辑',
                  onClick: handleEdit.bind(null, record),
                },
              ]"
              :dropDownActions="getDropDownActions(record)"
            />
          </template>
          <template v-if="column.dataIndex === 'file'">
            <div 
              @click="handleDownloadFiles(record)" 
              style="cursor: pointer; color: #1890ff; text-align: center;"
              title="点击下载用印文件"
            >
              <FileOutlined style="font-size: 20px;" />
            </div>
          </template>
        </template>
      </BasicTable>
  
      <!-- 新增申请抽屉 -->
      <SealCreateDrawer @register="registerCreateDrawer" @success="handleCreateSuccess" />
      
      <!-- 文件分类管理抽屉 -->
      <FileTypeDrawer @register="registerFileTypeDrawer" @success="handleFileTypeSuccess" />
      
      <!-- 印章管理抽屉 -->
      <SealStampDrawer @register="registerStampDrawer" @success="handleStampSuccess" />
    </div>
  </template>
  
  <script lang="ts" setup>
    import { computed, onMounted } from 'vue';
    import { BasicTable, useTable, TableAction } from '/@/components/Table';
    import { searchFormSchema, columns } from './seal.data';
    import { getSealList, getFileTypeOptions, getCompanyOptions, deleteSeal, setSealStatus } from '/@/api/project/seal';
    import { useMessage } from '/@/hooks/web/useMessage';
    import { useUserStoreWithOut } from '/@/store/modules/user';
    import { useDrawer } from '/@/components/Drawer';
    import SealCreateDrawer from './SealCreateDrawer.vue';
    import FileTypeDrawer from './FileTypeDrawer.vue';
    import SealStampDrawer from './SealStampDrawer.vue';
    import { FileOutlined } from '@ant-design/icons-vue';
    import { defHttp } from '/@/utils/http/axios';
  
    const { createMessage } = useMessage();
    const userStore = useUserStoreWithOut();
  
    // 获取当前用户角色
    const user = userStore.getUserInfo;
    const role = computed(() => {
      return user?.roleSmallVO?.code;
    });
  
    const [registerTable, { reload: reloadTable, getForm }] = useTable({
      title: '印章申请列表',
      api: getSealList,
      columns: columns,
      bordered: true,
      clickToRowSelect: false,
      rowKey: 'id',
      formConfig: {
        labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
      },
      useSearchForm: true,
      showTableSetting: true,
      showIndexColumn: true,
      tableSetting: {
        setting: false,
      },
      actionColumn: {
        width: 200,
        title: '操作',
        dataIndex: 'action',
      },
      beforeFetch: (params: any) => {
        // 转换查询参数格式
        const searchParams = { ...params };
        
        // 处理分页参数
        const finalParams: any = {
          page: searchParams.page || 1,
          pageSize: searchParams.size || 10,
        };
        
        // 添加搜索条件
        if (searchParams.fileName) finalParams.fileName = searchParams.fileName;
        if (searchParams.fileType) finalParams.fileType = searchParams.fileType;
        if (searchParams.signType) finalParams.signType = searchParams.signType;
        if (searchParams.company) finalParams.company = searchParams.company;
        if (searchParams.createBy) finalParams.createBy = searchParams.createBy;
        if (searchParams.status !== undefined) finalParams.status = searchParams.status;
        
        // 添加时间搜索条件,确保为字符串类型
        if (searchParams.startTime) {
          finalParams.startTime = String(searchParams.startTime);
          console.log('[beforeFetch] startTime 类型:', typeof finalParams.startTime, '值:', finalParams.startTime);
        }
        if (searchParams.endTime) {
          finalParams.endTime = String(searchParams.endTime);
          console.log('[beforeFetch] endTime 类型:', typeof finalParams.endTime, '值:', finalParams.endTime);
        }
        
        console.log('[beforeFetch] 最终请求参数:', finalParams);
        return finalParams;
      },
    });
  
    const [registerCreateDrawer, { openDrawer: openCreateDrawer }] = useDrawer();
    const [registerFileTypeDrawer, { openDrawer: openFileTypeDrawer }] = useDrawer();
    const [registerStampDrawer, { openDrawer: openStampDrawer }] = useDrawer();
  
    onMounted(async () => {
      console.log('印章申请页面已加载');
      console.log('当前用户角色:', role.value);
      
      // 加载文件分类选项
      try {
        const fileTypeOptions = await getFileTypeOptions();
        console.log('文件分类选项:', fileTypeOptions);
        
        if (fileTypeOptions.length > 0) {
          // 使用getForm获取搜索表单实例,然后更新schema
          const formInstance = getForm();
          if (formInstance && formInstance.updateSchema) {
            formInstance.updateSchema({
              field: 'fileType',
              componentProps: {
                options: fileTypeOptions,
              },
            });
            console.log('文件分类选项更新完成');
          }
        }
      } catch (error) {
        console.error('获取文件分类选项失败:', error);
      }
      
      // 加载公司选项
      try {
        const companyOptions = await getCompanyOptions();
        console.log('公司选项:', companyOptions);
        
        if (companyOptions.length > 0) {
          console.log('准备更新公司选项到下拉框');
          // 使用getForm获取搜索表单实例,然后更新schema
          const formInstance = getForm();
          if (formInstance && formInstance.updateSchema) {
            formInstance.updateSchema({
              field: 'company',
              componentProps: {
                options: companyOptions,
              },
            });
            console.log('公司选项更新完成');
          } else {
            console.log('无法获取表单实例或updateSchema方法');
          }
        } else {
          console.log('公司选项为空,无法更新下拉框');
        }
      } catch (error) {
        console.error('获取公司选项失败:', error);
      }
    });
  
    // 新增申请
    const handleCreate = () => {
      openCreateDrawer(true, {});
    };
  
    // 处理新增成功回调
    const handleCreateSuccess = async () => {
      // 重新加载文件分类选项,确保新增的文件分类能在搜索中使用
      try {
        const fileTypeOptions = await getFileTypeOptions();
        const formInstance = getForm();
        if (formInstance && formInstance.updateSchema) {
          formInstance.updateSchema({
            field: 'fileType',
            componentProps: {
              options: fileTypeOptions,
            },
          });
        }
      } catch (error) {
        console.error('重新加载文件分类选项失败:', error);
      }
      
      reloadTable();
    };
  
    function handleEdit(record: any) {
      console.log('编辑记录:', record);
      openCreateDrawer(true, { record });
    }
  
    async function handleDelete(record: any) {
      try {
        console.log('准备删除记录:', record);
        const response = await deleteSeal(record.id);
        console.log('删除响应:', response);
        
        createMessage.success('删除成功');
        // 刷新表格数据
        setTimeout(() => {
          reloadTable();
        }, 100);
      } catch (error) {
        console.error('删除失败:', error);
        createMessage.error('删除失败,请重试');
      }
    }
  
    // 经理审核通过
    async function handleManagerApprove(record: any) {
      try {
        console.log('经理审核通过:', record);
        await setSealStatus({
          id: record.id,
          managerStatus: 10
        });
        createMessage.success('经理审核通过成功');
        setTimeout(() => {
          reloadTable();
        }, 100);
      } catch (error) {
        console.error('经理审核通过失败:', error);
        createMessage.error('经理审核通过失败,请重试');
      }
    }
  
    // 经理审核驳回
    async function handleManagerReject(record: any) {
      try {
        console.log('经理审核驳回:', record);
        await setSealStatus({
          id: record.id,
          managerStatus: 20
        });
        createMessage.success('经理审核驳回成功');
        setTimeout(() => {
          reloadTable();
        }, 100);
      } catch (error) {
        console.error('经理审核驳回失败:', error);
        createMessage.error('经理审核驳回失败,请重试');
      }
    }
  
    // 财务审核通过
    async function handleFinanceApprove(record: any) {
      try {
        console.log('财务审核通过:', record);
        await setSealStatus({
          id: record.id,
          financeStatus: 10
        });
        createMessage.success('财务审核通过成功');
        setTimeout(() => {
          reloadTable();
        }, 100);
      } catch (error) {
        console.error('财务审核通过失败:', error);
        createMessage.error('财务审核通过失败,请重试');
      }
    }
  
    // 财务审核驳回
    async function handleFinanceReject(record: any) {
      try {
        console.log('财务审核驳回:', record);
        await setSealStatus({
          id: record.id,
          financeStatus: 20
        });
        createMessage.success('财务审核驳回成功');
        setTimeout(() => {
          reloadTable();
        }, 100);
      } catch (error) {
        console.error('财务审核驳回失败:', error);
        createMessage.error('财务审核驳回失败,请重试');
      }
    }
  
    // 计算下拉操作按钮
    const getDropDownActions = (record: any) => {
      console.log('计算dropDownActions,当前角色:', role.value);
      const actions = [
        {
          label: '删除',
          popConfirm: {
            title: '是否确认删除',
            placement: 'left',
            confirm: handleDelete.bind(null, record),
          },
        },
      ];
      
      // 经理审核只有管理员能看到
      if (role.value === 'admin') {
        console.log('添加管理员审核按钮');
        actions.push(
          {
            label: '经理审核通过',
            popConfirm: {
              title: '是否确认通过经理审核?',
              placement: 'leftTop',
              confirm: handleManagerApprove.bind(null, record),
            },
          },
          {
            label: '经理审核驳回',
            popConfirm: {
              title: '是否确认驳回经理审核?',
              placement: 'leftTop',
              confirm: handleManagerReject.bind(null, record),
            },
          }
        );
      }
      
      // 财务审核只有财务人员能看到
      if (role.value === 'finance_user') {
        console.log('添加财务审核按钮');
        actions.push(
          {
            label: '财务审核通过',
            popConfirm: {
              title: '是否确认通过财务审核?',
              placement: 'leftTop',
              confirm: handleFinanceApprove.bind(null, record),
            },
          },
          {
            label: '财务审核驳回',
            popConfirm: {
              title: '是否确认驳回财务审核?',
              placement: 'leftTop',
              confirm: handleFinanceReject.bind(null, record),
            },
          }
        );
      }
      
      console.log('最终actions:', actions);
      return actions;
    };
  
    const handleOpenFileTypeDrawer = () => {
      openFileTypeDrawer(true, {});
    };
  
    const handleFileTypeSuccess = async () => {
      // 重新加载文件分类选项
      try {
        const fileTypeOptions = await getFileTypeOptions();
        console.log('文件分类管理成功后,重新加载文件分类选项:', fileTypeOptions);
        
        // 更新搜索表单中的文件分类选项
        const formInstance = getForm();
        if (formInstance && formInstance.updateSchema) {
          formInstance.updateSchema({
            field: 'fileType',
            componentProps: {
              options: fileTypeOptions,
            },
          });
          console.log('搜索表单文件分类选项更新完成');
        }
      } catch (error) {
        console.error('重新加载文件分类选项失败:', error);
      }
      
      // 刷新表格数据
      reloadTable();
    };
  
    const handleOpenStampDrawer = () => {
      openStampDrawer(true, {});
    };
  
    const handleStampSuccess = async () => {
      // 刷新表格数据
      reloadTable();
    };
  
    const handleDownloadFiles = async (record: any) => {
      console.log('开始下载文件,record数据:', record);
      console.log('record.files:', record.files);
      console.log('record.file:', record.file);
      console.log('经理审核状态:', record.managerStatus);
      console.log('财务审核状态:', record.financeStatus);
      
      // 尝试多种可能的文件字段名称
      let fileList = record.files || record.file || [];
      
      // 如果是字符串,尝试解析为数组
      if (typeof fileList === 'string') {
        try {
          fileList = JSON.parse(fileList);
        } catch (e) {
          // 如果解析失败,将字符串作为单个文件处理
          fileList = [fileList];
        }
      }
      
      // 确保是数组
      if (!Array.isArray(fileList)) {
        fileList = fileList ? [fileList] : [];
      }
      
      console.log('处理后的文件列表:', fileList);
      
      if (!fileList || fileList.length === 0) {
        createMessage.warning('该记录没有可下载的文件');
        return;
      }
  
      // 检查审核状态:如果经理审核和财务审核都未通过(状态不是10),直接下载OSS链接
      const managerApproved = record.managerStatus === 10;
      const financeApproved = record.financeStatus === 10;
      const shouldUseDirectDownload = !managerApproved && !financeApproved;
      
      console.log('经理审核已通过:', managerApproved);
      console.log('财务审核已通过:', financeApproved);
      console.log('使用直接下载:', shouldUseDirectDownload);
  
      createMessage.loading('正在准备下载文件...', 1);
  
      try {
        // 遍历所有文件进行下载
        for (let i = 0; i < fileList.length; i++) {
          const fileUrl = fileList[i];
          
          try {
            if (shouldUseDirectDownload) {
              // 直接下载OSS链接,不调用后端接口
              console.log('直接下载OSS文件:', fileUrl);
              
              // 从原始文件URL中提取文件名和扩展名
              const fileName = extractFileName(fileUrl, i + 1);
              
              // 创建下载链接
              const link = document.createElement('a');
              link.href = fileUrl;
              link.download = fileName;
              link.style.display = 'none';
              link.target = '_blank'; // 在新窗口打开,避免跨域问题
              link.setAttribute('download', fileName);
              
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
              
              console.log(`文件 ${i + 1} 直接下载成功:`, fileName);
            } else {
              // 调用后端接口获取文件
              console.log('通过后端接口下载文件,请求参数:', { id: record.id, file: fileUrl });
              
              // 获取API基础URL
              const baseURL = import.meta.env.VITE_GLOB_API_URL || '/api';
              const apiUrl = `${baseURL}/order/erp/seal/getSealFile`;
              
              // 获取认证token
              const token = localStorage.getItem('ACCESS_TOKEN') || sessionStorage.getItem('ACCESS_TOKEN');
              
              // 使用原生fetch避免axios响应拦截器问题
              const fetchResponse = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                  ...(token ? { 'Authorization': `Bearer ${token}` } : {})
                },
                body: JSON.stringify({
                  id: record.id,
                  file: fileUrl
                })
              });
  
              console.log('请求URL:', apiUrl);
              console.log('响应状态:', fetchResponse.status, fetchResponse.statusText);
  
              if (!fetchResponse.ok) {
                throw new Error(`HTTP error! status: ${fetchResponse.status} ${fetchResponse.statusText}`);
              }
  
              // 检查响应的Content-Type
              const contentType = fetchResponse.headers.get('content-type');
              console.log('响应Content-Type:', contentType);
              
              // 如果是二进制文件数据,直接处理为blob
              if (contentType && (contentType.includes('application/') || contentType.includes('binary'))) {
                const blob = await fetchResponse.blob();
                console.log('获取到blob数据,大小:', blob.size);
                
                // 从原始文件URL中提取文件名和扩展名
                const fileName = extractFileName(fileUrl, i + 1);
                
                // 创建blob URL并下载
                const blobUrl = window.URL.createObjectURL(blob);
                
                // 尝试使用更现代的下载方式
                if (window.navigator && (window.navigator as any).msSaveOrOpenBlob) {
                  // IE浏览器
                  (window.navigator as any).msSaveOrOpenBlob(blob, fileName);
                } else {
                  // 现代浏览器
                  const link = document.createElement('a');
                  link.href = blobUrl;
                  link.download = fileName;
                  link.style.display = 'none';
                  
                  // 设置文件名的编码
                  link.setAttribute('download', fileName);
                  
                  document.body.appendChild(link);
                  
                  // 触发下载
                  if (link.click) {
                    link.click();
                  } else {
                    // 备用方案
                    const event = new MouseEvent('click', {
                      view: window,
                      bubbles: true,
                      cancelable: true
                    });
                    link.dispatchEvent(event);
                  }
                  
                  document.body.removeChild(link);
                }
                
                // 释放blob URL
                setTimeout(() => {
                  window.URL.revokeObjectURL(blobUrl);
                }, 100);
                
                console.log(`文件 ${i + 1} 下载成功:`, fileName);
              } else {
                // 如果是文本响应,按原来的逻辑处理
                const responseText = await fetchResponse.text();
                console.log('原始响应文本:', responseText);
                
                let response;
                try {
                  response = JSON.parse(responseText);
                } catch (e) {
                  // 如果不是JSON格式,直接使用文本作为URL
                  response = responseText;
                }
                
                console.log('解析后的响应:', response);
  
                // 处理不同的响应格式
                let downloadUrl = '';
                if (typeof response === 'string') {
                  // 如果直接返回字符串URL
                  downloadUrl = response;
                } else if (response && response.data) {
                  // 如果返回对象格式
                  downloadUrl = response.data;
                } else if (response && typeof response === 'object') {
                  // 如果响应本身就是包含URL的对象
                  downloadUrl = response.url || response.downloadUrl || response.fileUrl || '';
                }
  
                if (downloadUrl) {
                  // 从原始文件URL中提取文件名和扩展名
                  const fileName = extractFileName(fileUrl, i + 1);
                  
                  // 创建下载链接
                  const link = document.createElement('a');
                  link.href = downloadUrl;
                  link.download = fileName;
                  link.style.display = 'none';
                  link.target = '_blank'; // 在新窗口打开,避免跨域问题
                  document.body.appendChild(link);
                  link.click();
                  document.body.removeChild(link);
                  
                  console.log(`文件 ${i + 1} 下载成功:`, fileName);
                } else {
                  console.warn(`文件 ${i + 1} 未获取到有效的下载链接`, response);
                  createMessage.warning(`文件 ${i + 1} 下载链接获取失败`);
                }
              }
            }
            
            // 延迟一下,避免同时下载太多文件
            if (i < fileList.length - 1) {
              await new Promise(resolve => setTimeout(resolve, 500));
            }
          } catch (fileError) {
            console.error(`文件 ${i + 1} 下载失败:`, fileError);
            createMessage.error(`文件 ${i + 1} 下载失败: ${fileError.message || '未知错误'}`);
            // 继续处理下一个文件
            continue;
          }
        }
        
        createMessage.success(`文件下载处理完成`);
      } catch (error) {
        console.error('批量下载文件失败:', error);
        createMessage.error('批量下载文件失败,请重试');
      }
    };
  
    // 提取文件名的辅助函数
    const extractFileName = (fileUrl: string, index: number): string => {
      try {
        // 从URL中提取文件名
        const urlParts = fileUrl.split('/');
        let fileName = urlParts[urlParts.length - 1];
        
        // 去掉URL参数
        fileName = fileName.split('?')[0];
        
        // 处理URL编码的中文文件名
        try {
          fileName = decodeURIComponent(fileName);
        } catch (e) {
          console.log('文件名解码失败,使用原始文件名:', fileName);
        }
        
        // 如果文件名为空或无效,使用默认命名
        if (!fileName || fileName.length < 3) {
          // 尝试从URL中推断文件类型
          const extension = getFileExtensionFromUrl(fileUrl);
          fileName = `用印文件_${index}${extension}`;
        }
        
        // 确保文件名是有效的
        fileName = sanitizeFileName(fileName, index);
        
        console.log('最终文件名:', fileName);
        return fileName;
      } catch (error) {
        // 如果提取失败,使用默认文件名
        const extension = getFileExtensionFromUrl(fileUrl);
        return `用印文件_${index}${extension}`;
      }
    };
  
    // 清理文件名,移除非法字符
    const sanitizeFileName = (fileName: string, index: number): string => {
      // 移除或替换非法字符
      let cleanName = fileName.replace(/[<>:"/\\|?*]/g, '_');
      
      // 如果文件名太短或只包含非法字符,使用默认名称
      if (cleanName.length < 2 || cleanName.trim() === '') {
        const extension = getFileExtensionFromUrl(fileName);
        cleanName = `用印文件_${index}${extension}`;
      }
      
      // 确保文件名不会太长
      if (cleanName.length > 200) {
        const extension = cleanName.substring(cleanName.lastIndexOf('.'));
        cleanName = cleanName.substring(0, 200 - extension.length) + extension;
      }
      
      return cleanName;
    };
  
    // 从URL中获取文件扩展名的辅助函数
    const getFileExtensionFromUrl = (url: string): string => {
      const supportedExtensions = ['.pdf', '.docx', '.doc', '.xlsx', '.xls'];
      
      for (const ext of supportedExtensions) {
        if (url.toLowerCase().includes(ext)) {
          return ext;
        }
      }
      
      // 默认返回.pdf
      return '.pdf';
    };
  </script>