index.vue 19.1 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
<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <!-- <DeptTree class="w-1/4 xl:w-1/5" @select="handleSelect" /> -->
    <div class="w-full">
      <!-- 添加标签页切换 -->
      <div class="mb-4">
        <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
          <a-tab-pane key="employee" tab="员工列表"></a-tab-pane>
          <a-tab-pane key="production" tab="生产科列表"></a-tab-pane>
        </a-tabs>
      </div>
      <!-- 添加顶部选中提示信息 -->
      <a-alert type="info" show-icon class="mb-4">
        <template #message>
          <template v-if="checkedKeys.length > 0">
          <span>已选中{{ checkedKeys.length }}条记录(可跨页)</span>
          <a-button type="link" @click="handleClearSelection" size="small">清空</a-button>
        </template>
        <template v-else>
            <span>未选中任何项目</span>
          </template>
        </template>
      </a-alert>
      <BasicTable @register="registerTable" :rowSelection="rowSelection" :searchInfo="searchInfo">
      <template #toolbar>
          <!-- 导出劳务合同按钮 -->
          <a-button class="mr-2" @click="handleExportContract">
            导出劳务合同
          </a-button>
                 
        <!-- 新增配置下拉菜单 -->
        <a-dropdown class="mr-2">
            <a-button>
              新增配置
              <DownOutlined />
            </a-button>
            <template #overlay>
              <a-menu>
                <a-menu-item key="company" @click="openCompanyDrawer">
                  公司管理
                </a-menu-item>
                <a-menu-item key="dept" @click="openDeptDrawer">
                  部门管理
                </a-menu-item>
                <a-menu-item key="role" @click="openRoleDrawer">
                  角色岗位管理
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
          
          <!-- 新增账号下拉菜单 -->
          <a-dropdown>
            <a-button type="primary">
              新增账号
              <DownOutlined />
            </a-button>
            <template #overlay>
              <a-menu>
                <a-menu-item key="1" @click="handleCreate('employee')">
                  新增员工账号
                </a-menu-item>
                <a-menu-item key="2" @click="handleCreate('production')">
                  新增生产科账号
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
      </template>
      <!-- 移除自定义表头 -->  
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
          :actions="getActionButtons(record)"
          />
        </template>
      </template>
    </BasicTable>
  </div>
    <AccountModal @register="registerModal" @success="handleSuccess" />
    <!-- 添加部门和角色管理抽屉 -->
    <DeptDrawer @register="registerDeptDrawer" @success="handleDrawerSuccess" />
    <RoleDrawer @register="registerRoleDrawer" @success="handleDrawerSuccess" />
    <CompanyDrawer @register="registerCompanyDrawer" @success="handleDrawerSuccess" />
    <!-- 添加分配比例抽屉 -->
    <AllocationDrawer @register="registerAllocationDrawer" @success="handleDrawerSuccess" />
    <!-- 添加申请权限抽屉 -->
    <EmployeeFieldApplyDrawer @register="registerApplyDrawer" @success="handleApplySuccess" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, reactive, ref, computed, onActivated, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import {
    getUserList,
    userAdd,
    userEdit,
    userOpt,
    userResetPassword,
    getCompanyList,
  } from '/@/api/project/account';
  import { PageWrapper } from '/@/components/Page';
  import DeptTree from './DeptTree.vue';
  import { DownOutlined, EditOutlined } from '@ant-design/icons-vue';
  import { useModal } from '/@/components/Modal';
  import { useDrawer } from '/@/components/Drawer';
  import AccountModal from './AccountModal.vue';
  import DeptDrawer from './DeptDrawer.vue';
  import RoleDrawer from './RoleDrawer.vue';
  import CompanyDrawer from './CompanyDrawer.vue';
  import AllocationDrawer from './AllocationDrawer.vue';
  import EmployeeFieldApplyDrawer from './EmployeeFieldApplyDrawer.vue';
  import { columns, searchFormSchema } from './account.data';
  import { useGo } from '/@/hooks/web/usePage';
  import { useMessage } from '/@/hooks/web/useMessage';
  export default defineComponent({
    name: 'AccountManagement',
    components: { 
      BasicTable, 
      PageWrapper, 
      DeptTree, 
      AccountModal, 
      TableAction, 
      DownOutlined,
      EditOutlined,
      DeptDrawer,
      RoleDrawer,
      CompanyDrawer,
      AllocationDrawer,
      EmployeeFieldApplyDrawer,
    },
    setup() {
      const go = useGo();
      const { createMessage } = useMessage();
      const [registerModal, { openModal }] = useModal();
      const [registerDeptDrawer, { openDrawer: openDept }] = useDrawer();
      const [registerRoleDrawer, { openDrawer: openRole }] = useDrawer();
      const [registerCompanyDrawer, { openDrawer: openCompany }] = useDrawer();
      const [registerAllocationDrawer, { openDrawer: openAllocation }] = useDrawer();
      const [registerApplyDrawer, { openDrawer: openApply }] = useDrawer();
      const searchInfo = reactive<any>({isAdmin: "1"});
      const activeTab = ref('employee'); // 默认选中员工列表
      const checkedKeys = ref<(string | number)[]>([]); // 用于存储勾选的行
      const needRefresh = ref(false); // 标记是否需要刷新数据
      // 获取状态按钮文本
      function getStatusLabel(record) {
        if (activeTab.value === 'production') {
          return record.status === 10 ? '停用' : '启用';
        } else {
          return record.status === 10 ? '离职' : '启用';
        }
      }
      
      // 获取状态操作确认提示
      function getStatusTitle(record) {
        if (record.status !== 10) {
          return '是否确认启用';
        }
        
        if (activeTab.value === 'production') {
          return '是否确认停用该用户?';
        } else {
          return '是否确认离职该用户,离职用户无法通过忘记密码进行手机验证码修改密码。请管理员重置其账号密码并修改。';
        }
      }
      // 根据当前标签页决定显示哪些列
      const getColumns = computed(() => {
        if (activeTab.value === 'production') {
          // 生产科只显示姓名、手机号、邮箱、备注四列
          return columns.filter(column => 
            ['nickName', 'phone', 'email', 'status', 'remark', 'action'].includes(column.dataIndex as string)
          );
        }
        return columns; // 员工列表显示所有列
      });
      // 定义rowSelection,直接控制表格的选择功能
      const rowSelection = computed(() => {
        return {
          selectedRowKeys: checkedKeys.value,
          onChange: (keys: (string | number)[]) => {
            checkedKeys.value = keys;
            console.log('选中的键已更新:', keys);
          },
          columnWidth: 60,
          preserveSelectedRowKeys: true
        };
      });
      // 清空选择
      function handleClearSelection() {
        checkedKeys.value = [];
      }
      const [registerTable, { reload, getDataSource }] = useTable({  
        title: () => activeTab.value === 'employee' ? '员工列表' : '生产科列表',
        api: getUserList,
        rowKey: 'id',
        columns: getColumns,       
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
        },
        useSearchForm: true,
        showTableSetting: true,
        tableSetting: {
          setting: false,
        },
        bordered: true,
        handleSearchInfoFn(info) {
          // 合并当前的isAdmin参数
          return { ...info, isAdmin: searchInfo.isAdmin };
        },
        showIndexColumn: false, // 禁用序号列
        clickToRowSelect: false, // 禁止点击行选中
        actionColumn: {
          width: () => activeTab.value === 'employee' ? 350 : 250, // 根据标签页动态调整宽度
          title: '操作',
          dataIndex: 'action',
         
        },
      });
      // 页面激活时重新加载数据(解决缓存问题)
      onActivated(() => {
        console.log('页面激活,检查是否需要重新加载数据');
        // 只有在需要刷新时才重新加载
        if (needRefresh.value) {
          console.log('检测到需要刷新,延迟重新加载数据');
          // 添加小延迟确保页面完全激活后再刷新
          setTimeout(() => {
            reload();
            needRefresh.value = false; // 重置标记
          }, 100);
        }
      });
      // 组件挂载时加载数据
      onMounted(() => {
        console.log('组件挂载,加载数据');
        reload();
      });     
      // 打开部门管理抽屉
      function openDeptDrawer() {
        openDept(true, {});
      }
      // 打开角色岗位管理抽屉
      function openRoleDrawer() {
        openRole(true, {});
      }
      
      // 打开公司管理抽屉
      function openCompanyDrawer() {
        openCompany(true, {});
      }
      function handleTabChange(key: string) {
        // 重置勾选状态
        checkedKeys.value = [];
        
        // 根据选项卡设置isAdmin参数
        if (key === 'employee') {
          searchInfo.isAdmin = "1";
        } else {
          searchInfo.isAdmin = "0";
        }
        
        // 重新加载数据
        reload();
      }
      function handleCreate(type: string) {
        openModal(true, {
          isUpdate: false,
          type,
        });
      }

      function handleEdit(record) {
        // 当前是生产科列表,无论如何都使用production类型
        // 当前是员工列表,无论如何都使用employee类型
        const type = activeTab.value === 'production' ? 'production' : 'employee';
        
        // 在打开模态框前,先获取公司列表和考勤组数据
        getCompanyList({}).then(companies => {
          // 根据companyName查找对应的公司ID
          let companyId = null;
          if (record.companyName && companies && companies.length > 0) {
            const company = companies.find(item => item.name === record.companyName);
            if (company) {
              companyId = company.id;
            }
          }
          
          // 确保记录中包含公司ID
          const recordWithCompanyId = { 
            ...record,
            companyId: companyId || record.companyId || (record.company ? record.company.id : null)
          };
          
          console.log('打开编辑模态框,传递的记录:', recordWithCompanyId);
        openModal(true, {
          record: recordWithCompanyId,
          isUpdate: true,
          type,
          });
        });
      }

      async function handleDelete(record) {
        await userOpt({ ids: [record.id], optType: 20 });
        reload();
      }

      async function handleSuccess({ isUpdate, values }) {
        if (isUpdate) {
          await userEdit({ ...values });
        } else {
          await userAdd({ ...values });
        }
        // 标记需要刷新数据
        needRefresh.value = true;
        reload();
      }

      async function handleForbid(record) {
        await userOpt({ ids: [record.id], optType: record.status === 10 ? 30 : 10 });
        // 标记需要刷新数据
        needRefresh.value = true; 
        reload();
      }

      async function handleResetPassword(record) {
        await userResetPassword({ userId: record.id });
        // 标记需要刷新数据
        needRefresh.value = true;
        reload();
      }

      function handleSelect(deptId = '') {
        searchInfo.deptId = deptId;
        reload();
      }

      function handleView(record) {
        go('/system/account_detail/' + record.id);
      }
      function handleAllocation(record) {
        openAllocation(true, { record });
      }
      function handleApplyPermission(record) {
        // Implementation of handleApplyPermission function
        openApply(true, { record });
      }
     // 导出劳务合同
     async function handleExportContract() {
        // 检查是否有勾选的用户
        if (checkedKeys.value.length === 0) {
          createMessage.warning('请先勾选要导出劳务合同的用户');
          return;
        }
        
        // 检查是否只勾选了一个用户
        if (checkedKeys.value.length > 1) {
          createMessage.warning('只能勾选一个用户进行劳务合同导出');
          return;
        }
        
        try {
          // 直接从表格获取当前数据源
          const tableData = getDataSource();
         
          
          // 找到被勾选的用户数据
          const selectedUserId = checkedKeys.value[0];
          const selectedUser = tableData.find(user => user.id === selectedUserId);
          
          if (!selectedUser) {
            createMessage.error('未找到选中的用户信息');
            return;
          }
          
          
          
          // 准备请求参数
          const requestParams = {
            id: selectedUser.id,
            idCard: selectedUser.idCard || '',
            phone: selectedUser.phone || '',
            chineseName: selectedUser.chineseName || selectedUser.nickName || ''
          };
          
        
          
          createMessage.loading('正在导出劳务合同...', 0);
          
          // 获取当前的token和baseURL
          const token = localStorage.getItem('ACCESS_TOKEN') || sessionStorage.getItem('ACCESS_TOKEN');
          const baseURL = import.meta.env.VITE_GLOB_API_URL || '/api';
          
          // 使用原生fetch方法,避免响应拦截器干扰
          const response = await fetch(`${baseURL}/order/erp/users/exportContract`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': token ? `Bearer ${token}` : '',
            },
            body: JSON.stringify(requestParams),
          });
          
         
          
          if (!response.ok) {
            // 尝试读取错误信息
            const errorText = await response.text();
            console.error('服务器错误响应:', errorText);
            throw new Error(`服务器错误 (${response.status}): ${errorText || '请联系管理员'}`);
          }
          
          // 检查响应类型
          const contentType = response.headers.get('content-type');
          console.log('响应内容类型:', contentType);
          
          if (!contentType || !contentType.includes('application/octet-stream') && !contentType.includes('application/vnd.openxmlformats')) {
            const responseText = await response.text();
            console.error('响应不是文件类型:', responseText);
            throw new Error('服务器返回的不是文件数据,请检查接口实现');
          }
          
          // 获取文件数据
          const blob = await response.blob();
          
          
          if (blob.size === 0) {
            throw new Error('服务器返回的文件为空');
          }
          
          // 创建下载链接
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', `${selectedUser.chineseName || selectedUser.nickName}_劳务合同.docx`);
          document.body.appendChild(link);
          link.click();
          
          // 清理
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
          
          createMessage.destroy();
          createMessage.success('劳务合同导出成功');
          
        } catch (error) {
          createMessage.destroy();
          console.error('导出劳务合同失败 - 完整错误信息:', error);
          
          // 更详细的错误处理
          let errorMessage = '导出劳务合同失败,请重试';
          
          if (error.message) {
            errorMessage = error.message;
          }
          
          createMessage.error(errorMessage);
        }
      }
      // 处理抽屉操作成功
      function handleDrawerSuccess() {
        needRefresh.value = true;
        reload();
      }

      // 处理权限申请成功
      function handleApplySuccess() {
        console.log('权限申请操作完成,标记需要刷新数据');
        needRefresh.value = true;
        reload();
      }

      // 根据当前标签页和记录获取操作按钮
      function getActionButtons(record) {
        const baseActions = [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          }
        ];

        // 只有员工列表才显示分配比例按钮
        if (activeTab.value === 'employee') {
          baseActions.push({
            label: '分配比例',
            onClick: handleAllocation.bind(null, record),
          });
        }

        // 只有员工列表才显示申请权限按钮
        if (activeTab.value === 'employee') {
          baseActions.push({
            label: '申请权限',
            onClick: handleApplyPermission.bind(null, record),
          });
        }

        // 添加其他通用按钮
        baseActions.push(
          {
            label: '重置密码',
            popConfirm: {
              title: '是否确认重置密码',
              placement: 'left',
              confirm: handleResetPassword.bind(null, record),
            },
          },
          {
            color: 'error',
            label: getStatusLabel(record),
            popConfirm: {
              title: getStatusTitle(record),
              placement: 'left',
              confirm: handleForbid.bind(null, record),
            },
          },
          {
            color: 'error',
            label: '删除',
            popConfirm: {
              title: '是否确认删除',
              placement: 'left',
              confirm: handleDelete.bind(null, record),
            },
          }
        );

        return baseActions;
      }

      return {
        registerTable,
        registerModal,
        registerDeptDrawer,
        registerRoleDrawer,
        registerCompanyDrawer,
        registerAllocationDrawer,
        registerApplyDrawer,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleSelect,
        handleView,
        handleForbid,
        handleResetPassword,
        searchInfo,
        activeTab,
        handleTabChange,
        checkedKeys,
        handleClearSelection,
        rowSelection,
        getStatusLabel,
        getStatusTitle,
        openDeptDrawer,
        openRoleDrawer,
        openCompanyDrawer,
        openAllocation,
        openApply,
        reload,
        handleAllocation,
        handleApplyPermission,
        handleExportContract,
        handleDrawerSuccess,
        handleApplySuccess,
        getActionButtons,
      };
    },
  });
</script>