index.vue 11.8 KB
<template>
  <div>
    <BasicTable
      class="devide-profiles"
      @register="registerTable"
      @selection-change="useSelectionChange"
      :rowSelection="{ type: 'checkbox' }"
      :clickToRowSelect="false"
    >
      <template #toolbar>
        <Authority value="api:yt:deviceProfile:post">
          <a-button type="primary" @click="handleCreate"> 新增设备配置 </a-button>
        </Authority>
        <Authority value="api:yt:deviceProfile:import">
          <ImpExcel @success="loadDataSuccess" dateFormat="YYYY-MM-DD">
            <a-button @click="handleImport"> 导入设备配置 </a-button>
          </ImpExcel>
        </Authority>
        <Authority value="api:yt:deviceProfile:delete">
          <Popconfirm
            title="您确定要批量删除数据"
            ok-text="确定"
            cancel-text="取消"
            @confirm="handleDeleteOrBatchDelete(null)"
          >
            <a-button type="primary" color="error" :disabled="hasBatchDelete"> 批量删除 </a-button>
          </Popconfirm>
        </Authority>
      </template>
      <template #img="{ record }">
        <TableImg
          :size="30"
          :showBadge="false"
          :simpleShow="true"
          :imgList="
            typeof record.image !== 'undefined' && record.image !== '' && record.image != null
              ? [record.image]
              : null
          "
        />
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '默认',
              icon: 'ant-design:profile-outlined',
              onClick: handleSetDefault.bind(null, record),
              ifShow: () => {
                return record.default === false;
              },
            },
            {
              label: '详情',
              auth: 'api:yt:deviceProfile:get',
              icon: 'ant-design:eye-outlined',
              onClick: handleDetailView.bind(null, record),
            },
            {
              label: '编辑',
              auth: 'api:yt:deviceProfile:update',
              icon: 'clarity:note-edit-line',
              onClick: handleEdit.bind(null, record),
              ifShow: () => {
                return record.name !== 'default' ? true : false;
              },
            },
            {
              label: '导出',
              auth: 'api:yt:deviceProfile:export',
              icon: 'ant-design:login-outlined',
              onClick: handleExport.bind(null, record),
            },
            {
              label: '删除',
              auth: 'api:yt:deviceProfile:delete',
              icon: 'ant-design:delete-outlined',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDeleteOrBatchDelete.bind(null, record),
              },
              ifShow: () => {
                return record.default === false && record.name !== 'default';
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <DeviceProfileModal @register="registerModal" @success="handleSuccess" />
    <ExpExcelModal
      ref="expExcelModalRef"
      @register="registerExportModal"
      @success="defaultHeader"
    />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, onUnmounted } from 'vue';
  import { BasicTable, TableImg, useTable, TableAction, BasicColumn } from '/@/components/Table';
  import { columns, searchFormSchema } from './device.profile.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    deviceConfigGetQuery,
    deviceConfigDelete,
    setDeviceProfileIsDefaultApi,
  } from '/@/api/device/deviceConfigApi';
  import { useModal } from '/@/components/Modal';
  import DeviceProfileModal from '/@/views/device/profiles/DeviceProfileModal.vue';
  import { ImpExcel, ExcelData } from '/@/components/Excel';
  import { jsonToSheetXlsx, ExpExcelModal, ExportModalResult } from '/@/components/Excel';
  import { Authority } from '/@/components/Authority';
  import { useBatchDelete } from '/@/hooks/web/useBatchDelete';
  import { Popconfirm } from 'ant-design-vue';

  export default defineComponent({
    name: 'DeviceProfileManagement',
    components: {
      BasicTable,
      DeviceProfileModal,
      TableAction,
      ImpExcel,
      TableImg,
      Authority,
      ExpExcelModal,
      Popconfirm,
    },
    setup() {
      const exportData: any = ref([]);
      const expExcelModalRef = ref(null);
      let selectedRowKeys: any = [];
      const deviceDetailRef = ref(null);
      const getPathUrl = ref('');
      const getPathUrlName = ref('');
      const disabled = ref(true);
      const onCloseVal = ref(0);
      const immediateStatus = ref(false);
      const { createMessage } = useMessage();
      const [registerModal, { openModal }] = useModal();
      const [registerExportModal, { openModal: openModalExcel }] = useModal();
      const [
        registerTable,
        { setProps, reload, getSelectRows, setTableData, getForm, getSelectRowKeys },
      ] = useTable({
        title: '设备配置列表',
        clickToRowSelect: false,
        api: deviceConfigGetQuery,
        immediate: immediateStatus.value,
        columns,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
        },
        rowKey: 'id',
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        showIndexColumn: false,
        actionColumn: {
          width: 240,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right',
        },
      });
      const { hasBatchDelete, handleDeleteOrBatchDelete, selectionOptions } = useBatchDelete(
        deviceConfigDelete,
        handleSuccess,
        setProps
      );
      selectionOptions.rowSelection.getCheckboxProps = (record: Recordable) => {
        // Demo:status为1的选择框禁用
        if (record.default === true) {
          return { disabled: true };
        } else if (record.name == 'default') {
          return { disabled: true };
        } else {
          return { disabled: false };
        }
      };
      nextTick(() => {
        setProps(selectionOptions);
      });
      /**
       *@param url,name
       **/
      function getParam(url, name) {
        try {
          let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
          let r = url.split('?')[1].match(reg);
          if (r != null) {
            return r[2];
          }
          return ''; //如果此处只写return;则返回的是undefined
        } catch (e) {
          return ''; //如果此处只写return;则返回的是undefined
        }
      }
      getPathUrl.value = window.location.href;
      const name = 'name';
      const getName = getParam(getPathUrl.value, name);
      getPathUrlName.value = decodeURIComponent(getName);

      const setRowClassName = async () => {
        if (getPathUrlName.value !== '') {
          const { items } = await deviceConfigGetQuery({
            page: 1,
            pageSize: 10,
            name: getPathUrlName.value,
          });
          nextTick(() => {
            setTableData(items);
            const { setFieldsValue, resetFields } = getForm();
            setFieldsValue({
              name: getPathUrlName.value,
            });
            if (onCloseVal.value == 1) {
              resetFields();
            }
          });
        } else {
          setTimeout(() => {
            reload();
          }, 80);
        }
      };
      setRowClassName();
      onUnmounted(() => {
        getPathUrlName.value = '';
        onCloseVal.value = 1;
      });
      const tableListRef = ref<
        {
          title: string;
          columns?: any[];
          dataSource?: any[];
        }[]
      >([]);

      function loadDataSuccess(excelDataList: ExcelData[]) {
        tableListRef.value = [];
        console.log(excelDataList);
        for (const excelData of excelDataList) {
          const {
            header,
            results,
            meta: { sheetName },
          } = excelData;
          const columns: BasicColumn[] = [];
          for (const title of header) {
            columns.push({ title, dataIndex: title });
          }
          tableListRef.value.push({ title: sheetName, dataSource: results, columns });
        }
      }

      function handleCreate() {
        setTimeout(() => {
          openModal(true, {
            isUpdate: 1,
          });
        }, 10);
      }

      function handleEdit(record: Recordable) {
        setTimeout(() => {
          openModal(true, {
            record,
            isUpdate: 2,
            isLostFocuxStatus: true,
          });
        }, 10);
      }
      async function handleDetailView(record: Recordable) {
        setTimeout(() => {
          openModal(true, {
            record,
            isUpdate: 3,
            isLostFocuxStatus: true,
          });
        }, 10);
      }
      const useSelectionChange = () => {
        selectedRowKeys = getSelectRowKeys();
        if (selectedRowKeys.length > 0) {
          disabled.value = false;
        }
        const isJudge = getSelectRows().map((m) => m.default);
        if (isJudge.includes(true)) {
          disabled.value = true;
        } else {
          disabled.value = false;
        }
        if (isJudge.length === 0) {
          disabled.value = true;
        }
      };

      function handleDelete(record: Recordable) {
        let ids = [record.id];
        deviceConfigDelete(ids).then(() => {
          createMessage.success('删除设备配置成功');
          handleSuccess();
        });
      }

      function defaultHeader({ filename, bookType }: ExportModalResult) {
        // 默认Object.keys(data[0])作为header
        const data = exportData.value;
        jsonToSheetXlsx({
          data,
          filename,
          write2excelOpts: {
            bookType,
          },
        });
      }
      //导出
      const handleExport = (record: Recordable) => {
        exportData.value = [];
        exportData.value.push({
          createTime: record.createTime,
          description: record.description,
          name: record.name,
        });
        nextTick(() => {
          openModalExcel();
          expExcelModalRef.value?.clearFieldFunc();
        });
      };
      //导入
      function handleImport() {
        console.log('record');
      }
      function handleSuccess() {
        reload();
      }

      const handleSetDefault = async (record: Recordable) => {
        let id = record.id;
        const obj = {
          headers: {
            normalizedNames: {},
            lazyUpdate: null,
          },
          params: {
            updates: null,
            cloneFrom: null,
            encoder: {},
            map: null,
            interceptorConfig: {
              ignoreLoading: false,
              ignoreErrors: false,
              resendRequest: false,
            },
          },
        };
        const data = await setDeviceProfileIsDefaultApi(id, 'default', obj);
        if (!data) return createMessage.error('设置该设备配置为默认失败');
        createMessage.success('设置该设备配置为默认成功');
        reload();
        disabled.value = true;
      };
      return {
        handleSetDefault,
        disabled,
        deviceDetailRef,
        registerExportModal,
        defaultHeader,
        useSelectionChange,
        tableListRef,
        loadDataSuccess,
        handleImport,
        handleExport,
        handleDetailView,
        registerTable,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        registerModal,
        hasBatchDelete,
        handleDeleteOrBatchDelete,
        expExcelModalRef,
      };
    },
  });
</script>

<style lang="css">
  .devide-profiles .rowcolor {
    color: red;
  }
  .devide-profiles .rowcolor2 {
    background: #a2c3e6;
  }
</style>