<template>
  <div>
    <div class="header">
      <SvgIcon size="19" name="list" />
      <div class="title">设备列表</div>
    </div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate" :icon="h(PlusOutlined)">新增</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <TableAction
            :actions="[
              {
                label: '编辑',
                icon: 'clarity:note-edit-line',
                onClick: handleEdit.bind(null, record),
                divider: true,
              },
              {
                label: '删除',
                icon: 'ant-design:delete-outlined',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  confirm: handleDelete.bind(null, record),
                  placement: 'topRight',
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <DeviceDrawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { isObject } from '@/utils/is';
  import dayjs from 'dayjs';
  import * as DeviceApi from '@/api/data/deviceApi';
  import { useDrawer } from '@/components/Drawer';
  import DeviceDrawer from './drawer.vue';
  import { columns, searchFormSchema } from './schema';
  import {SvgIcon} from "@/components/Icon";
  import {h, onMounted} from "vue";
  import {PlusOutlined} from "@ant-design/icons-vue";

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload }] = useTable({
    api: (params) => DeviceApi.search(handleParams(params)),
    columns,
    formConfig: {
      labelWidth: 0,
      schemas: searchFormSchema,
      showAdvancedButton: false,
    },
    useSearchForm: true,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    canResize: false,
    rowKey: (record: any) => record.id,
    actionColumn: {
      width: 180,
      title: '操作',
      dataIndex: 'action',
      fixed: undefined,
    },
  });

  onMounted(() => {
    WebViewService.setIsLoading(false).then(() => {});
  });

  const handleParams = (params: any) => {
    const { pageNum, pageSize, field = 'id', order = 'descend', ...rest } = params;
    const handledParams: any = {
      pageNum,
      pageSize,
      orderByClause: `${field} ${order === 'descend' ? 'desc' : 'asc'}`,
    };
    Object.keys(rest).forEach((key) => {
      const schema = searchFormSchema.find((item) => item.field === key);
      const value = params[key];
      const paramKey = key;
      if (schema) {
        if (value !== undefined && value !== '') {
          if (schema.component === 'Input') {
            handledParams[paramKey] = `%${value.trim()}%`;
          } else if (['Select', 'ApiSelect', 'ApiTreeSelect'].includes(schema.component)) {
            handledParams[paramKey] = isObject(value) ? value.value : value;
          } else if (schema.component === 'RangePicker') {
            handledParams[`${paramKey}From`] = dayjs(value[0])
              .startOf('d')
              .format('YYYY-MM-DD HH:mm:ss');
            handledParams[`${paramKey}To`] = dayjs(value[1])
              .endOf('d')
              .format('YYYY-MM-DD HH:mm:ss');
          } else if (schema.component === 'DatePicker') {
            handledParams[paramKey] = dayjs(value).format(
              (schema.componentProps as any).format || 'YYYY-MM-DD',
            );
          } else {
            handledParams[paramKey] = value;
          }
        }
      } else {
        handledParams[paramKey] = value;
      }
    });
    return handledParams;
  };

  const handleCreate = () => {
    openDrawer(true, {
      isUpdate: false,
    });
  };

  const handleEdit = (record: Recordable) => {
    openDrawer(true, {
      record,
      isUpdate: true,
    });
  };

  const handleDelete = (record: Recordable) => {
    DeviceApi.remove(record.id).then((_) => {
      reload();
    });
  };

  const handleSuccess = () => {
    reload();
  };
</script>
<style lang="scss" scoped>
  @use '@/assets/custom.scss';
</style>
