index.vue 20.7 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
<template>
  <div>
    <BasicTable @register="registerTable" :bordered="true" @field-value-change="handleFieldValueChange">
      <template #headerTop>
        <a-alert type="info" show-icon>
          <template #message>
            <template v-if="checkedKeys.length > 0">
              <span>已选中{{ checkedKeys.length }}条记录(可跨页)</span>
              <a-button
                :style="{ borderRadius: '5px 5px 5px 5px' }"
                type="link"
                @click="handleClearChoose"
                size="small"
                >清空</a-button
              >
            </template>
            <template v-else>
              <span>未选中任何订单</span>
            </template>
          </template>
        </a-alert>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'picUrl'">
          <img :z-index="100000" :width="50" :height="50" :src="record?.picUrl" />
        </template>
        <template v-if="column.key === 'action'">
          <TableAction 
            :actions="createActions(record)" 
            :dropDownActions="createDropActions(record)" 
           />
        </template>
      </template>
      <template #toolbar>
        <a-dropdown
          v-if="role == ROLE.ADMIN || role == ROLE.FINANCE"
          :style="{ borderRadius: '5px 5px 5px 5px' }"
        >
          <a-button type="primary">
            导出
            <DownOutlined />
          </a-button>
          <template #overlay>
            <a-menu @click="handleExportWithTeam">
              <a-menu-item key="0">中国团队</a-menu-item>
              <a-menu-item key="1">西班牙团队</a-menu-item>
              <a-menu-item key="2">所有团队</a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
        <a-button
          type="primary"
          @click="handleAllProjectNoQuery"
          style="margin-left: 8px;position: fixed;right: 29%;top: 107.5px;"
        >全选</a-button>
      </template>
    </BasicTable>
    <CheckDetail @register="checkModalRegister" />
    <FinanceEdit @register="registerFinanceEdit" @success="handleSuccess" />
    <HistoryDetail @register="registerHistoryDetail" />
    <InvoiceDetail @register="registerOrderDetail" />
  </div>
</template>
<script setup lang="ts">
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { getBusinessDevelopmentDetail, setBusinessDevelopmentStatus, setBusinessDevStatusSend } from '@/api/project/invoice';
  import { saveConfig } from '@/api/sys/config';
  import { searchFormSchema, COLUMNS, allProjectNoOptions } from './data';
  import axios from 'axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { onMounted, ref, computed, unref, h } from 'vue';
  import { Modal } from 'ant-design-vue';
  import { DownOutlined } from '@ant-design/icons-vue';
  import { useDrawer } from '/@/components/Drawer';
  import FinanceEdit from './FinanceEdit.vue';
  import HistoryDetail from './HistoryDetail.vue';
  import CheckDetail from './CheckDetail.vue';
  import InvoiceDetail from './InvoiceDetail.vue';
  import { useUserStoreWithOut } from '/@/store/modules/user';
  import { ROLE } from '../../../type.d';
  import { useOrderStoreWithOut } from '/@/store/modules/order';

  const { createMessage } = useMessage();
  const projectNoPrefixs = ref<string[]>([]);
  const checkedKeys = ref<string[]>([]);
  const invoiceIdKeys = ref<string[]>([]);
  const checkIdKeys = ref<string[]>([]);
  const detailProjectNoKeys = ref<string[]>([]);
  const orderStore = useOrderStoreWithOut();
  const [checkModalRegister, { openDrawer: openCheckDetailDrawer }] = useDrawer();
  const [registerFinanceEdit, { openDrawer: openFinanceEdit }] = useDrawer();
  const [registerHistoryDetail, { openDrawer: openHistoryDetail }] = useDrawer();
  const [registerOrderDetail, { openDrawer: openOrderDetail }] = useDrawer();
  const userStore = useUserStoreWithOut();
  const user = userStore.getUserInfo;
  const role = computed(() => {
    return user?.roleSmallVO?.code;
  });
  const [registerTable, { reload, getSelectRowKeys, getDataSource, setSelectedRowKeys, setProps, getForm }] = useTable({
    title: '',
    api: getBusinessDevelopmentDetail,
    bordered: true,
    columns: COLUMNS,
    clickToRowSelect: false,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      resetFunc: async () => {
        localStorage.removeItem('isAllSelected');
        setProps({
          searchInfo: {
            projectNo: []
          }
        });
      },
    },
    handleSearchInfoFn: (searchInfo) => {
      
      // 获取表单实例
      const formInstance = getForm();
      if (formInstance) {
        const formValues = formInstance.getFieldsValue();
        
        // 强制覆盖searchInfo,确保使用表单中的值
        if (formValues.projectNo && formValues.projectNo.length > 0) {
          // 确保传递的是数组而不是Proxy对象,并去重
          const projectNoArray = [...new Set(formValues.projectNo)];
          // 强制覆盖,不使用原始值
          searchInfo = {
            ...searchInfo,
            projectNo: projectNoArray
          };
        } else {
          // 如果表单中没有项目号,清空查询条件
          searchInfo = {
            ...searchInfo,
            projectNo: []
          };
        }
      }
      
      
      return searchInfo;
    },
    rowKey: (record) => record.projectNoPrefix,
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys as any,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
    useSearchForm: true,
    showTableSetting: true,
    showIndexColumn: false,
    tableSetting: {
      setting: false,
    },
    actionColumn: {
      width: 260,
      title: 'Action',
      dataIndex: 'action',
    },
  });

  function createActions(record: any): any[] {
    if (!record.editable) {
      const actions = [
        {
          label: '财务编辑',
          onClick: handleFinanceEdit.bind(null, record),
        },
        {
          label: '申请权限',
          onClick: handleFalse.bind(null, record),
        },
        ...(role.value === ROLE.ADMIN ? [
                  {
          label: '审核通过',
                      onClick: () => {
              // 如果状态为未完成(-1),则不响应
              if (record.detailDevelopmentStatus === -1) {
                createMessage.warning('订单状态未完成');
                return;
              }
              else{
                showAuditOptions(record);
              }
            },
        },
        ] : []),
      ];
      return actions;
    }
    return [
      {
        label: '保存',
        onClick: handleSave.bind(null, record),
      },
      {
        label: '取消',
        popConfirm: {
          title: '是否取消编辑',
          confirm: handleCancel.bind(null, record),
        },
      },
    ];
  }
  function createDropActions(record: any) {
    if (!record.editable) {
      const actions = [
        {
          label: '订单信息',
          onClick: handleOrderDetail.bind(null, record),
        },
        {
          label: '历史记录',
          onClick: handleHistoryDetail.bind(null, record),
        },
        // {
        //   label: '设置为应发但不发',
        //   onClick: handleSetStatus.bind(null, record),
        // }
      ];
      return actions;
    }
  }

  onMounted(async () => {
    await orderStore.getDict();
  });

  // 监听表单字段变化
  function handleFieldValueChange(field: string, value: any) {
    // 如果是项目号字段变化且处于全选状态,同步更新查询条件
    if (field === 'projectNo' && localStorage.getItem('isAllSelected') === 'true') {
      
      // 确保value是数组格式,并去重
      const projectNoArray = Array.isArray(value) ? [...new Set(value)] : [];
       
      // 强制重新加载表格,使用新的查询条件
      reload({
        searchInfo: {
          projectNo: projectNoArray
        }
      });
      
      // 同时更新detailProjectNoKeys数组
      detailProjectNoKeys.value = projectNoArray;
      
    }
  }

  function handleFinanceEdit(record) {
    openFinanceEdit(true, {
      data: record,
    });
  }

  function handleFalse(record, e) {
    openCheckDetailDrawer(true, record);
    e?.stopPropagation();
    return false;
  }

  function handleSuccess() {
    setTimeout(() => {
      reload();
    }, 50);
  }

  async function handleSave(record) {
    await saveConfig({ projectNo: record.projectNoPrefix, relationValue: record.relationValue });
    handleCancel(record);
    reload();
  }

  function handleCancel(record) {
    record.onEdit?.(false, false);
  }

  async function handleStatus(record, status) {
    try {
      // 检查必要参数是否存在
      if (!record.projectNoPrefix) {
        createMessage.error('缺少必要的参数:projectNoPrefix');
        return;
      }
      
      // 根据不同的状态调用不同的接口
      if (status === 'approved') {
        await setBusinessDevelopmentStatus({ 
          projectNo: record.projectNoPrefix,
          customerCode: record.customerCode,
          detailDevelopmentStatus: 1  // 审核通过状态
        });
        createMessage.success('审核通过成功!');
      } else if (status === 'completed') {
        await setBusinessDevelopmentStatus({ 
          projectNo: record.projectNoPrefix,
          customerCode: record.customerCode,
          detailDevelopmentStatus: 1  // 已完成状态
        });
        createMessage.success('设置为已发放成功!');
      } else {
        // 默认审核通过
        await setBusinessDevelopmentStatus({ 
          projectNo: record.projectNoPrefix,
          customerCode: record.customerCode,
          detailDevelopmentStatus: 1  // 默认审核通过状态
        });
        createMessage.success('状态更新成功!');
      }
      
      reload();
    } catch (error) {
      console.error('Error updating status:', error);
      createMessage.error('状态更新失败:' + (error.message || '未知错误'));
    }
  }

  async function handleHistoryDetail(record) {
    openHistoryDetail(true, {
      data: record,
    });
  }

  async function handleSetStatus(record) {
    await setBusinessDevStatusSend({
      projectNo: record.projectNoPrefix,
      customerCode: record.customerCode,
      detailDevelopmentStatus: 2  // 应发但不发状态
    });
    // 重新加载
    reload();
  }

  // 显示审核选项
  function showAuditOptions(record) {
    // 检查当前状态
    const isReviewed = record.detailDevelopmentStatus === 1; // 已发放状态
    const isSentButNotPaid = record.detailDevelopmentStatus === 2; // 应发但不发状态
    
    // 使用 Modal 显示选项
    Modal.confirm({
      title: '选择审核结果',
      content: h('div', [
        h('div', { style: 'margin-top: 16px;' }, [
          h('button', {
            style: isReviewed 
              ? 'margin-right: 8px; padding: 4px 8px; color: #666; background-color: #f5f5f5; border-radius: 2px; cursor: not-allowed; border: 1px solid #d9d9d9;' 
              : 'margin-right: 8px; padding: 4px 8px; color: white; background-color: #40a9ff; border-radius: 2px; cursor: pointer;',
            disabled: isReviewed, // 如果已发放则禁用
            onClick: () => {
              if (!isReviewed) {
                Modal.destroyAll();
                handleStatus(record, 'approved'); // 审核通过
              }
            }
          }, isReviewed ? '已发放' : '已发放'),
          h('button', {
            style: (isReviewed || isSentButNotPaid)
              ? 'margin-right: 8px; padding: 4px 8px; color: #666; background-color: #f5f5f5; border-radius: 2px; cursor: not-allowed; border: 1px solid #d9d9d9;' 
              : 'margin-right: 8px; padding: 4px 8px; color: white; background-color: #40a9ff; border-radius: 2px; cursor: pointer;',
            disabled: isReviewed || isSentButNotPaid, // 如果已发放或应发但不发则禁用
            onClick: () => {
              if (!isReviewed && !isSentButNotPaid) {
                Modal.destroyAll();
                handleSetStatus(record); // 应发但不发
              }
            }
          }, (isReviewed || isSentButNotPaid) ? '应发但不发' : '应发但不发'),
        ])
      ]),
      onCancel: () => {
        Modal.destroyAll();
      }
    });
  }

  function handleExportWithTeam({ key }: { key: string }) {
    // Get current search parameters from the form
    const values = getForm().getFieldsValue();
    
    // Create export parameters based on whether projectNoPrefixs are selected
    let exportParams;
    
    // If projectNoPrefixs are selected, only use those and ignore search params
    if (projectNoPrefixs.value.length > 0) {
      exportParams = {
        projectNos: projectNoPrefixs.value,  // 复选选中的项目号使用 projectNos
        selectExcel: parseInt(key)  // 添加团队选择参数
      };
    } 
    // Otherwise use the search parameters
    else {
      exportParams = {
        ...values,
        projectNo: values.projectNo || undefined,  // 搜索框的项目号使用 projectNo
        customerCode: values.customerCode || undefined,
        innerNo: values.innerNo || undefined,
        productionDepartment: values.productionDepartment || undefined,
        selectExcel: parseInt(key)  // 添加团队选择参数
      };
    }
    
    
    const token = userStore.getToken;
    axios
      .post(
        '/basic-api/project/detailBusinessProfit/exportExcel',
        exportParams,
        {
          headers: {
            Authorization: `${token}`, // 去掉引号
          },
          responseType: 'blob', // 设置响应类型为 'blob'
        },
      )
      .then((response) => {
        // 创建一个 Blob 对象来保存二进制数据
        const blob = new Blob([response.data], { type: 'application/zip' });
        const getFormattedDate = (): string => {
          const date = new Date();

          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');

          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          const seconds = String(date.getSeconds()).padStart(2, '0');

          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        };
        const date = getFormattedDate();
        // 创建一个链接元素用于下载
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = `业务研发明细表${date}.xlsx`; // 你可以为文件命名
        document.body.appendChild(link);
        link.click(); // 自动点击链接,触发下载
        document.body.removeChild(link); // 下载完成后移除链接
      })
      .catch((error) => {
        console.error(error);
      });
    handleClearChoose();
    reload();
  }

  function handleExport() {
    // Get current search parameters from the form
    const values = getForm().getFieldsValue();
    
    // Create export parameters based on whether projectNoPrefixs are selected
    let exportParams;
    
    // If projectNoPrefixs are selected, only use those and ignore search params
    if (projectNoPrefixs.value.length > 0) {
      exportParams = {
        projectNos: projectNoPrefixs.value  // 复选选中的项目号使用 projectNos
      };
    } 
    // Otherwise use the search parameters
    else {
      exportParams = {
        ...values,
        projectNo: values.projectNo || undefined,  // 搜索框的项目号使用 projectNo
        customerCode: values.customerCode || undefined,
        innerNo: values.innerNo || undefined,
        productionDepartment: values.productionDepartment || undefined
      };
    }
    
    
    const token = userStore.getToken;
    axios
      .post(
        '/basic-api/project/detailBusinessProfit/exportExcel',
        exportParams,
        {
          headers: {
            Authorization: `${token}`, // 去掉引号
          },
          responseType: 'blob', // 设置响应类型为 'blob'
        },
      )
      .then((response) => {
        // 创建一个 Blob 对象来保存二进制数据
        const blob = new Blob([response.data], { type: 'application/zip' });
        const getFormattedDate = (): string => {
          const date = new Date();

          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');

          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          const seconds = String(date.getSeconds()).padStart(2, '0');

          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        };
        const date = getFormattedDate();
        // 创建一个链接元素用于下载
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = `业务研发明细表${date}.xlsx`; // 你可以为文件命名
        document.body.appendChild(link);
        link.click(); // 自动点击链接,触发下载
        document.body.removeChild(link); // 下载完成后移除链接
      })
      .catch((error) => {
        console.error(error);
      });
    handleClearChoose();
    reload();
  }

  function handleClearChoose() {
    checkedKeys.value = [];
    projectNoPrefixs.value = [];
    detailProjectNoKeys.value = [];
    invoiceIdKeys.value = [];
    checkIdKeys.value = [];
  }

  async function onSelect(record, selected: boolean) {
    const rowKey = record.projectNoPrefix;
    if (selected) {
      if (!checkedKeys.value.includes(rowKey)) {
        checkedKeys.value.push(rowKey);
      }
      if (record.projectNoPrefix !== undefined && !projectNoPrefixs.value.includes(record.projectNoPrefix)) {
        projectNoPrefixs.value.push(record.projectNoPrefix);
      }
    } else {
      checkedKeys.value = checkedKeys.value.filter((key) => key !== rowKey);
      if (record.projectNoPrefix !== undefined) {
        projectNoPrefixs.value = projectNoPrefixs.value.filter(projectNo => projectNo !== record.projectNoPrefix);
      }
    }
    setSelectedRowKeys(checkedKeys.value as any);
  }

  function onSelectAll(selected: boolean, selectedRows: any[]) {
    if (selected) {
      checkedKeys.value = selectedRows
        .map(row => row && row.projectNoPrefix)
        .filter((key, idx, arr) => key !== undefined && arr.indexOf(key) === idx);
      projectNoPrefixs.value = checkedKeys.value.slice();
    } else {
      checkedKeys.value = [];
      projectNoPrefixs.value = [];
    }
    setSelectedRowKeys(checkedKeys.value as any);
  }
  // 6/25未完成工作:全选查询
  function handleAllProjectNoQuery() {
    // 检查是否有项目号选项
    if (!allProjectNoOptions.value || allProjectNoOptions.value.length === 0) {
      createMessage.warn('没有可查询的项目号!');
      return;
    }
    
          // 获取所有项目号的value值
      const allProjectNos = allProjectNoOptions.value.map((item: any) => {
        // 处理不同的数据结构
        if (typeof item === 'string') {
          return item;
        } else if (item && typeof item === 'object' && 'value' in item) {
          return item.value;
        } else if (item && typeof item === 'object' && 'label' in item) {
          return item.label;
        }
        return item;
      }).filter(Boolean); // 过滤掉空值
    
    if (allProjectNos.length === 0) {
      createMessage.warn('没有有效的项目号!');
      return;
    }
    
    try {
      // 提示用户全选成功
      createMessage.success(`已全选 ${allProjectNos.length} 个项目号`);
      
      // 获取表单实例并设置表单值,将项目号填入搜索框
      const formInstance = getForm();
      if (formInstance && formInstance.setFieldsValue) {
        formInstance.setFieldsValue({
          projectNo: allProjectNos
        });
      }
      
      // 将allProjectNoOptions更新为已勾选的项目号数组,这样用户取消勾选时数组会同步更新
      allProjectNoOptions.value = allProjectNos.map((projectNo: any) => ({
        label: projectNo,
        value: projectNo
      }));
      
      // 标记为全选状态
      localStorage.setItem('isAllSelected', 'true');
    } catch (error) {
      console.error('全选失败:', error);
      createMessage.error('全选失败,请检查网络连接!');
    }
  }

  async function handleOrderDetail(record) {
    // 打开订单信息抽屉
    openOrderDetail(true, {
      data: {
        projectNo: record.projectNoPrefix || record.projectNo
      },
    });
  }
</script>
<style></style>