TableMode.vue 9.38 KB
<template>
  <div>
    <BasicTable
      class="devide-profiles"
      @register="registerTable"
      :rowSelection="{ type: 'checkbox' }"
      :clickToRowSelect="false"
    >
      <template #toolbar>
        <Authority :value="ProductPermission.CREATE">
          <a-button type="primary" @click="handleCreate"> 新增产品 </a-button>
        </Authority>
        <Authority :value="ProductPermission.IMPORT">
          <ImpExcel @success="loadDataSuccess" dateFormat="YYYY-MM-DD">
            <a-button @click="handleImport"> 导入产品 </a-button>
          </ImpExcel>
        </Authority>
        <Authority :value="ProductPermission.DELETE">
          <Popconfirm
            title="您确定要批量删除数据"
            ok-text="确定"
            cancel-text="取消"
            @confirm="handleDeleteOrBatchDelete(null)"
          >
            <a-button type="primary" color="error" :disabled="hasBatchDelete"> 批量删除 </a-button>
          </Popconfirm>
        </Authority>
        <ModeSwitchButton :value="$props.mode" @change="handleModeChange" />
      </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: '详情',
              auth: ProductPermission.DETAIL,
              icon: 'ant-design:eye-outlined',
              onClick: handleDetailView.bind(null, record),
            },
            {
              label: '编辑',
              auth: ProductPermission.UPDATE,
              icon: 'clarity:note-edit-line',
              onClick: handleEdit.bind(null, record),
              ifShow: () => {
                return record.name !== 'default' ? true : false;
              },
            },
          ]"
          :drop-down-actions="[
            {
              label: '默认',
              icon: 'ant-design:profile-outlined',
              onClick: handleSetDefault.bind(null, record),
              ifShow: () => {
                return record.default === false;
              },
            },
            {
              label: '导出',
              auth: ProductPermission.EXPORT,
              icon: 'ant-design:login-outlined',
              onClick: handleExport.bind(null, record),
            },
            {
              label: '删除',
              auth: ProductPermission.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" />
    <DeviceProfileDrawer @register="registerDrawer" />
    <ExpExcelModal
      ref="expExcelModalRef"
      @register="registerExportModal"
      @success="defaultHeader"
    />
  </div>
</template>
<script lang="ts" setup>
  import { ref, nextTick, onUnmounted } from 'vue';
  import { BasicTable, TableImg, useTable, TableAction, BasicColumn } from '/@/components/Table';
  import { columns, searchFormSchema, defaultObj, ProductPermission } from './device.profile.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    deviceConfigGetQuery,
    deviceConfigDelete,
    setDeviceProfileIsDefaultApi,
  } from '/@/api/device/deviceConfigApi';
  import { useModal } from '/@/components/Modal';
  import { useDrawer } from '/@/components/Drawer';
  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';
  import DeviceProfileDrawer from './DeviceProfileDrawer.vue';
  import { EnumTableCardMode, ModeSwitchButton } from '/@/components/Widget';

  defineProps<{
    mode: EnumTableCardMode;
  }>();

  const emit = defineEmits(['changeMode']);

  const exportData: any = ref([]);
  const expExcelModalRef: any = 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, setTableData, getForm }] = 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: 200,
      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 = [];
    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() {
    openModal(true, {
      isUpdate: false,
    });
  }
  //编辑
  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  const [registerDrawer, { openDrawer }] = useDrawer();
  //详情
  function handleDetailView(record: Recordable) {
    openDrawer(true, { record });
  }

  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() {}
  function handleSuccess() {
    reload();
  }

  const handleSetDefault = async (record: Recordable) => {
    let id = record.tbProfileId;
    const data = await setDeviceProfileIsDefaultApi(id, 'default', defaultObj);
    if (!data) return createMessage.error('设置该产品为默认失败');
    createMessage.success('设置该产品为默认成功');
    reload();
    disabled.value = true;
  };

  const handleModeChange = (value: EnumTableCardMode) => {
    emit('changeMode', value);
  };
</script>

<style lang="css">
  .devide-profiles .rowcolor {
    color: red;
  }

  .devide-profiles .rowcolor2 {
    background: #a2c3e6;
  }
</style>