<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { GatewayForm } from '#/api/operations/gateway/model';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';

import { Modal, Popconfirm, Space, Tag } from 'ant-design-vue';

import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
  gatewayExport,
  gatewayList,
  gatewayRemove,
} from '#/api/operations/gateway';
import { commonDownloadExcel } from '#/utils/file/download';

import {
  columns,
  getNetworkOptions,
  getProtocolOptions,
  providerOptions,
  querySchema,
  registerNetworkOptionsUpdate,
} from './data';
import gatewayDrawer from './gateway-drawer.vue';

const formOptions: VbenFormProps = {
  collapsed: true,
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  // 需要使用i18n注意这里要改成getter形式 否则切换语言不会刷新
  // columns: columns(),
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await gatewayList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          orderByColumn: 'createTime',
          isAsc: 'desc',
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'operations-gateway-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

// 更新网络组件选项
async function updateNetworkComponentOptions(provider: string) {
  try {
    if (provider && provider !== 'child-device') {
      const networkOptions = await getNetworkOptions(provider);

      await tableApi.formApi.updateSchema(
        querySchema().map((field: any) => {
          if (field.fieldName === 'channelId') {
            return {
              ...field,
              componentProps: {
                ...field.componentProps,
                options: networkOptions,
              },
            };
          }
          return field;
        }),
      );
    } else {
      // 如果是网关子设备接入，清空网络组件选项
      await tableApi.formApi.updateSchema(
        querySchema().map((field: any) => {
          if (field.fieldName === 'channelId') {
            return {
              ...field,
              componentProps: {
                ...field.componentProps,
                options: [],
              },
            };
          }
          return field;
        }),
      );
    }
  } catch (error) {
    console.error('更新网络组件选项失败:', error);
  }
}

// 注册网络组件更新回调
registerNetworkOptionsUpdate(updateNetworkComponentOptions);

// 动态加载表单选项
async function loadFormOptions() {
  try {
    const protocolOptions = await getProtocolOptions();

    // 更新表单字段的选项
    await tableApi.formApi.updateSchema(
      querySchema().map((field: any) => {
        if (field.fieldName === 'protocol') {
          return {
            ...field,
            componentProps: {
              ...field.componentProps,
              options: protocolOptions,
            },
          };
        }
        return field;
      }),
    );
  } catch (error) {
    console.error('加载表单选项失败:', error);
  }
}

// 组件挂载后加载选项
loadFormOptions();

const [GatewayDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: gatewayDrawer,
});

function handleAdd() {
  drawerApi.setData({});
  drawerApi.open();
}

async function handleEdit(row: Required<GatewayForm>) {
  drawerApi.setData({ id: row.id });
  drawerApi.open();
}

async function handleDelete(row: Required<GatewayForm>) {
  await gatewayRemove(row.id);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: Required<GatewayForm>) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await gatewayRemove(ids);
      await tableApi.query();
    },
  });
}

function handleDownloadExcel() {
  commonDownloadExcel(
    gatewayExport,
    '设备接入网关数据',
    tableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="设备接入网关列表">
      <template #toolbar-tools>
        <Space>
          <a-button
            v-access:code="['operations:gateway:export']"
            @click="handleDownloadExcel"
          >
            {{ $t('pages.common.export') }}
          </a-button>
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            v-access:code="['operations:gateway:remove']"
            @click="handleMultiDelete"
          >
            {{ $t('pages.common.delete') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['operations:gateway:add']"
            @click="handleAdd"
          >
            {{ $t('pages.common.add') }}
          </a-button>
        </Space>
      </template>
      <template #provider="{ row }">
        <div class="flex flex-col">
          <span class="font-medium">{{
            providerOptions.find((option) => option.value === row.provider)
              ?.label
          }}</span>
        </div>
      </template>
      <template #enabled="{ row }">
        <Tag :color="row.enabled === '1' ? 'success' : 'error'">
          {{ row.enabled === '1' ? '启用' : '禁用' }}
        </Tag>
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['operations:gateway:edit']"
            @click.stop="handleEdit(row)"
          >
            {{ $t('pages.common.edit') }}
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              danger
              v-access:code="['operations:gateway:remove']"
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <GatewayDrawer @reload="tableApi.query()" />
  </Page>
</template>
