index.vue 17.4 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
<template>
  <div>
    <PageWrapper dense contentFullHeight contentClass="flex">
      <OrganizationIdTree @select="handleSelect" ref="organizationIdTreeRef" />
      <BasicTable style="flex: auto" @register="registerTable" class="w-5/6 xl:w-4/5 device-table">
        <template #toolbar>
          <Authority :value="DeviceListAuthEnum.CREATE">
            <a-button type="primary" @click="handleCreate" v-if="authBtn(role)">
              {{ t('equipment.ledger.createLedgerText') }}
            </a-button>
          </Authority>

          <Authority :value="DeviceListAuthEnum.IMPORT">
            <Button type="primary" >
              {{ t('equipment.ledger.importLedgerText') }}
            </Button>
          </Authority>

          <Authority
            :value="[
              DeviceListAuthEnum.DELETE,
              DeviceListAuthEnum.ASSIGN,
              DeviceListAuthEnum.UPDATE_PRODUCT,
            ]"
          >
            <AuthDropDown
              v-if="authBtn(role)"
              :disabled="isPublicAndPrivateFlag || !isExistOption"
              :dropMenuList="[
                {
                  text: t('common.delText'),
                  auth: DeviceListAuthEnum.DELETE,
                  icon: 'ant-design:delete-outlined',
                  event: '',
                  disabled: !batchPrivateFlag,
                  popconfirm: {
                    title: t('common.deleteConfirmText'),
                    onConfirm: () => handleDelete(),
                  },
                },
                {
                  text: t('equipment.ledger.editProductText'),
                  auth: DeviceListAuthEnum.UPDATE_PRODUCT,
                  icon: 'clarity:note-edit-line',
                  event: '',
                  disabled: !batchPrivateFlag || batchUpdateProductFlag,
                  onClick: handelOpenBatchUpdateProductModal,
                },
                {
                  text: t('business.publicText'),
                  icon: 'ant-design:wallet-outlined',
                  event: '',
                  disabled: !batchPrivateFlag,
                  onClick: handleBatchPublic.bind(null),
                },
                {
                  text: t('business.privateText'),
                  icon: 'ant-design:wallet-outlined',
                  event: '',
                  disabled: batchPrivateFlag,
                  onClick: handleBatchPrivate.bind(null),
                },
                {
                  text: t('equipment.ledger.updateOrganization'),
                  icon: 'ant-design:wallet-outlined',
                  event: '',
                  disabled: !batchPrivateFlag || batchSensorFlag || diffBatchSensorFlag,
                  onClick: handleBatchOrg.bind(null),
                },
              ]"
            >
              <Button type="primary" :disabled="isPublicAndPrivateFlag || !isExistOption">
                {{ t('equipment.ledger.batchActionText') }}
              </Button>
            </AuthDropDown>
          </Authority>
        </template>
        <template #img="{ record }">
          <TableImg
            :size="30"
            :showBadge="false"
            :simpleShow="true"
            :imgList="
              typeof record?.deviceInfo?.avatar !== 'undefined' &&
              record?.deviceInfo?.avatar !== '' &&
              record?.deviceInfo?.avatar != null
                ? [record.deviceInfo.avatar]
                : null
            "
          />
        </template>
        <template #deviceProfile="{ record }">
          <Button
            @click="!isCustomer ? goDeviceProfile(record.deviceProfile.name) : null"
            type="link"
          >
            {{ record.deviceProfile.name }}
          </Button>
        </template>
        <template #deviceState="{ record }">
          <div v-if="record.isCollect">
            <div class="absolute top-0 left-0 device-collect"> </div>
            <Icon
              icon="ph:star-fill"
              class="fill-light-50 absolute top-0.5 left-0.5"
              color="#fff"
              :size="12"
            />
          </div>

          <Tag
            :color="
              record.deviceState == DeviceState.INACTIVE
                ? 'warning'
                : record.deviceState == DeviceState.ONLINE
                ? 'success'
                : record.deviceState == DeviceState.ACTIVE
                ? 'success'
                : 'error'
            "
            class="ml-2"
          >
            {{ t(`enum.deviceStatus.${record.deviceState}`) }}
          </Tag>
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                label: AlarmDetailActionButton({ hasAlarm: !!record.alarmStatus }),
                icon: 'ant-design:eye-outlined',
                auth: DeviceListAuthEnum.DETAIL,
                // onClick: handleDetail.bind(null, record),
              },
              {
                label: t('common.editText'),
                auth: DeviceListAuthEnum.UPDATE,
                icon: 'clarity:note-edit-line',
                ifShow: authBtn(role),
                // onClick: handleEdit.bind(null, record),
              },
            ]"
            :dropDownActions="[
              // record.customerId
              //   ? {
              //       label: t('deviceManagement.device.cancelAssignText'),
              //       icon: 'mdi:account-arrow-left',
              //       ifShow: authBtn(role) && !record?.customerAdditionalInfo?.isPublic,
              //       auth: DeviceListAuthEnum.ASSIGN,
              //       popConfirm: {
              //         title: t('deviceManagement.device.cancelAssignConfirmText'),
              //         confirm: handleCancelDispatchCustomer.bind(null, record),
              //       },
              //     }
              //   : {
              //       label: t('deviceManagement.device.assignCustomerText'),
              //       icon: 'mdi:account-arrow-right',
              //       ifShow: authBtn(role),
              //       auth: DeviceListAuthEnum.ASSIGN,
              //       onClick: handleDispatchCustomer.bind(null, record),
              //     },
              {
                label: record?.customerAdditionalInfo?.isPublic
                  ? t('business.privateText')
                  : t('business.publicText'),
                auth: DeviceListAuthEnum.PUBLIC,
                icon: record?.customerAdditionalInfo?.isPublic
                  ? 'ant-design:lock-outlined'
                  : 'ant-design:unlock-outlined',
                // onClick: handlePublicDevice.bind(null, record),
              },
              {
                label: t('deviceManagement.device.onlineRecordText'),
                auth: DeviceListAuthEnum.ONLINE,
                icon: 'ant-design:rise-outlined',
                // onClick: handleUpAndDownRecord.bind(null, record),
              },
              !record.isCollect
                ? {
                    label: t('deviceManagement.device.collectText'),
                    icon: 'ant-design:heart-outlined',
                    // onClick: handelCollect.bind(null, record),
                  }
                : {
                    label: t('deviceManagement.device.cancelCollectText'),
                    icon: 'ant-design:heart-outlined',
                    popConfirm: {
                      title: t('deviceManagement.device.cancelCollectConfirmText'),
                      // confirm: handelCollect.bind(null, record),
                    },
                  },
              {
                label: t('common.delText'),
                auth: DeviceListAuthEnum.DELETE,
                icon: 'ant-design:delete-outlined',
                ifShow: authBtn(role) && record.customerId === undefined,
                color: 'error',
                popConfirm: {
                  title: !!record.isEdge
                    ? t('common.edgeDeviceOperationConfirm')
                    : t('common.deleteConfirmText'),
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </BasicTable>
<!--      <LedgerDetailDrawer-->
<!--        @register="registerDetailDrawer"-->
<!--        @open-tb-device-detail="handleOpenTbDeviceDetail"-->
<!--        @open-gateway-device-detail="handleOpenGatewayDetail"-->
<!--      />-->
    </PageWrapper>
  </div>
</template>
<script setup lang="ts">
import {CSSProperties, h, reactive, ref} from "vue";
import { PageWrapper } from '/@/components/Page';
const searchInfo = reactive<Recordable>({});
const { organizationIdTreeRef, resetFn } = useResetOrganizationTree(searchInfo);
import {BasicTable, TableAction, TableImg, useTable} from "/@/components/Table";
import {OrganizationIdTree, useResetOrganizationTree} from "/@/views/common/organizationIdTree";
import {
  deleteDevice,
  devicePage,
  doBatchPrivateDevice,
  doBatchPublicDevice
} from "/@/api/device/deviceManager";
import {
  columns,
  DeviceListAuthEnum,
  searchFormSchema
} from "/@/views/equipment/ledger/config/ledger.data";
import {DeviceModel, DeviceRecord, DeviceState} from "/@/api/device/model/deviceModel";
import {useI18n} from "/@/hooks/web/useI18n";
import {authBtn} from "/@/enums/roleEnum";
import {Badge, Button, Tag} from "ant-design-vue";
import {Authority} from "/@/components/Authority";
import {AuthDropDown} from "/@/components/Widget";
import {getAuthCache} from "/@/utils/auth";
import {USER_INFO_KEY} from "/@/enums/cacheEnum";
import {useBatchOperation} from "/@/utils/useBatchOperation";
import {useMessage} from "/@/hooks/web/useMessage";
import {DataActionModeEnum} from "/@/enums/toolEnum";
import {
  BatchUpdateProductModalParamsType
} from "/@/views/device/list/cpns/modal/BatchUpdateProductModal/index";
import {useModal} from "/@/components/Modal";
import Icon from "/@/components/Icon";
// import LedgerDetailDrawer from "./cpns/modal/LedgerDetailDrawer.vue";
const { t } = useI18n();
const userInfo: any = getAuthCache(USER_INFO_KEY);
const role: string = userInfo.roles[0];
const isPublicAndPrivateFlag = ref(false);
const batchPrivateFlag = ref(true);
const batchUpdateProductFlag = ref(true);
const batchSensorFlag = ref(false);
const { createMessage } = useMessage();
const diffBatchSensorFlag = ref(false);
const [registerOrgModal, { openModal: openOrgodal }] = useModal();
const [registerBatchUpdateProductModal, { openModal: openBatchUpdateProductModal }] = useModal();

const AlarmDetailActionButton = ({ hasAlarm }: { hasAlarm?: boolean }) =>
  h(
    Badge,
    { offset: [0, -5] },
    {
      default: () => h('span', { style: { color: '#377dff' } }, t('common.detailText')),
      count: () =>
        h(
          'div',
          {
            style: {
              visibility: hasAlarm ? 'visible' : 'hidden',
              width: '14px',
              height: '14px',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              border: '1px solid #f46161',
              borderRadius: '50%',
            } as CSSProperties,
          },
          h(Icon, { icon: 'mdi:bell-warning', color: '#f46161', size: 12 })
        ),
    }
  );

const [
  registerTable,
  {
    reload,
    setLoading,
    setSelectedRowKeys,
    getForm,
    getSelectRowKeys,
    getSelectRows,
    getRowSelection,
    clearSelectedRowKeys,
  },
] = useTable({
  title: t('equipment.ledger.ledgerListText'),
  api: devicePage,
  columns,
  beforeFetch: (params) => {
    const { deviceProfileId } = params;
    if (!deviceProfileId) return;
    const obj = {
      ...params,
      ...{
        deviceProfileIds: deviceProfileId ? [deviceProfileId] : null,
      },
    };
    delete obj.deviceProfileId;
    return obj;
  },
  formConfig: {
    labelWidth: 140,
    schemas: searchFormSchema,
    resetFunc: resetFn,
  },
  useSearchForm: true,
  showTableSetting: true,
  bordered: true,
  showIndexColumn: false,
  rowKey: 'id',
  searchInfo: searchInfo,
  clickToRowSelect: false,
  rowClassName: (record) => ((record as DeviceRecord).alarmStatus ? 'device-alarm-badge' : ''),
  actionColumn: {
    width: 200,
    title: t('common.actionText'),
    slots: { customRender: 'action' },
    fixed: 'right',
  },
  rowSelection: {
    type: 'checkbox',
    getCheckboxProps: (record: DeviceModel) => {
      return { disabled: !!record.customerId && record.customerName !== 'Public' };
    },
    onSelect(_record, _selected, selectedRows) {
      const [firstItem] = selectedRows as DeviceRecord[];
      const { deviceType } = firstItem || {};
      batchUpdateProductFlag.value =
        !selectedRows.length ||
        !selectedRows.every((item) => (item as DeviceRecord).deviceType === deviceType);

      batchPrivateFlag.value = selectedRows.some((item: DeviceRecord) => !item?.customerId);
      const filterSensor = selectedRows.map((filterItem: DeviceRecord) => filterItem.deviceType);
      batchSensorFlag.value =
        filterSensor.includes('SENSOR') &&
        (filterSensor.includes('DIRECT_CONNECTION') || filterSensor.includes('GATEWAY')); // 网关子和直连设备或者网关设备,则禁用组织修改
      const filterGatewayId = selectedRows
        .filter((filterItem: DeviceRecord) => filterItem.deviceType === 'SENSOR')
        .map((mapItem: DeviceRecord) => mapItem.gatewayId);
      diffBatchSensorFlag.value = [...new Set(filterGatewayId)].length > 1; // 数组长度大于1,说明选择的网关子设备所属网关为多个,则禁用组织修改
      isPublicAndPrivateFlag.value =
        selectedRows.some((item: DeviceRecord) => !item?.customerId) &&
        selectedRows.some((item: DeviceRecord) => item?.customerAdditionalInfo?.isPublic);
    },
    onSelectAll(_selected, selectedRows) {
      const [firstItem] = selectedRows as DeviceRecord[];
      const { deviceType } = firstItem || {};
      batchUpdateProductFlag.value =
        !selectedRows.length ||
        !selectedRows.every((item) => (item as DeviceRecord).deviceType === deviceType);

      batchPrivateFlag.value = selectedRows.some((item) => !item?.customerId);
      const filterSensor = selectedRows.map((filterItem) => filterItem.deviceType);
      batchSensorFlag.value =
        filterSensor.includes('SENSOR') &&
        (filterSensor.includes('DIRECT_CONNECTION') || filterSensor.includes('GATEWAY')); // 网关子和直连设备或者网关设备,则禁用组织修改
      const filterGatewayId = selectedRows
        .filter((filterItem: DeviceRecord) => filterItem.deviceType === 'SENSOR')
        .map((mapItem: DeviceRecord) => mapItem.gatewayId);
      diffBatchSensorFlag.value = [...new Set(filterGatewayId)].length > 1; // 数组长度大于1,说明选择的网关子设备所属网关为多个,则禁用组织修改
      isPublicAndPrivateFlag.value =
        selectedRows.some((item) => !item?.customerId) &&
        selectedRows.some((item) => item?.customerAdditionalInfo?.isPublic);
    },
  },
});

const { isExistOption } = useBatchOperation(getRowSelection, setSelectedRowKeys);
function handleCreate() {
  // openModal(true, {
  //   isUpdate: false,
  // });
}

// 批量公开设备
const handleBatchPublic = async () => {
  setLoading(true);
  try {
    const options = getSelectRows();
    const tbDeviceIdJoinStr = options.map((item) => item.tbDeviceId).join(',');
    const res = await doBatchPublicDevice(tbDeviceIdJoinStr);
    createMessage.success(
      res === '公开成功' ? t('common.publicSuccess') : t('common.publicError')
    );
  } finally {
    handleReload();
    setLoading(false);
  }
};

function handleReload() {
  setSelectedRowKeys([]);
  handleSuccess();
}

// 批量私有设备
const handleBatchPrivate = async () => {
  setLoading(true);
  try {
    const options = getSelectRows();
    const tbDeviceIdJoinStr = options.map((item) => item.tbDeviceId).join(',');
    const res = await doBatchPrivateDevice(tbDeviceIdJoinStr);
    createMessage.success(
      res === '私有成功' ? t('common.privateSuccess') : t('common.privateError')
    );
  } finally {
    handleReload();
    setLoading(false);
  }
};

const handleBatchOrg = () => {
  const options = getSelectRows();
  openOrgodal(true, options);
};

const handelOpenBatchUpdateProductModal = () => {
  const rows: DeviceRecord[] = getSelectRows();
  const [firstItem] = rows;

  openBatchUpdateProductModal(true, {
    mode: DataActionModeEnum.UPDATE,
    record: {
      sourceDeviceProfileName: firstItem.deviceProfile.name,
      deviceType: firstItem.deviceType,
      deviceIds: rows.map((item) => item.tbDeviceId),
      deviceProfile: firstItem.deviceProfile,
    },
  } as BatchUpdateProductModalParamsType);
};

const handleDelete = async (record?: DeviceRecord) => {
  let ids: string[] = [];
  if (record) {
    ids.push(record.id);
  } else {
    ids = getSelectRowKeys();
  }
  try {
    setLoading(true);
    await deleteDevice(ids);
    createMessage.success(t('common.deleteSuccessText'));
    handleReload();
  } catch (error) {
    throw error;
  } finally {
    setLoading(false);
  }
};

function handleSuccess() {
  reload();
}

function handleSelect(organization) {
  searchInfo.organizationId = organization;
  handleSuccess();
}

</script>

<style scoped lang="less">
.device-table {
  :deep(.ant-form-item-control-input-content) {
    & > div > div {
      width: 100%;
    }
  }
}
</style>

<style lang="less">
.device-status {
  position: relative;

  .device-collect {
    width: 0;
    height: 0;
    border-top: 30px solid #377dff;
    border-right: 30px solid transparent;
  }
}

.device-name-edge {
  width: 100%;
  height: 100%;
  padding: 0 !important;
  position: relative;
}
</style>