<template>
  <div class="h-full overflow-hidden">
    <n-card title="认证鉴权" :bordered="false" class="rounded-16px shadow-sm">
      <n-space class="pb-12px" justify="space-between">
        <n-space>
          <n-button type="primary" @click="handleAddTable">
            <icon-ic-round-plus class="mr-4px text-20px" />
            新增
          </n-button>
        </n-space>
        <n-space align="center" :size="18">
          <n-input-group>
            <n-input v-model:value="formValue.subscribe_topic_name" placeholder="输入订阅主题名称" />
            <n-input v-model:value="formValue.publish_topic_name" placeholder="输入发布主题名称" />
            <n-input v-model:value="formValue.user_name" placeholder="输入用户姓名" />
            <n-input v-model:value="formValue.pasture_name" placeholder="输入牧场名称" />
            <n-button type="primary" @click="handleSearch">搜索</n-button>
          </n-input-group>
          <n-button size="small" type="primary" @click="getTableData">
            <icon-mdi-refresh class="mr-4px text-16px" :class="{ 'animate-spin': loading }" />
            刷新表格
          </n-button>
        </n-space>
      </n-space>
      <n-data-table :columns="columns" :data="tableData" :loading="loading" :pagination="pagination" />
      <table-action-modal
        v-model:visible="visible"
        :type="modalType"
        :edit-data="editData"
        :group-enum-list-data="groupEnumListData"
        @update:visible="handleModalVisibilityChange"
      />
    </n-card>
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref } from 'vue';
import type { Ref } from 'vue';
import { NButton, NSpace, NPopconfirm } from 'naive-ui';
import type { DataTableColumns, PaginationProps, SelectOption } from 'naive-ui';
import { useBoolean, useLoading } from '@/hooks';
import { fetchMqttAuthList, groupEnumList, mqttAuthDelete } from '@/service/api/mqtt';
import TableActionModal from '../authentication/components/table-action-modal.vue';
import type { ModalType } from '../authentication/components/table-action-modal.vue';

const { loading, startLoading, endLoading } = useLoading(false);
const { bool: visible, setTrue: openModal } = useBoolean();
const formValue = ref<Mqtt.SearchAuth>({
  publish_topic_name: '',
  subscribe_topic_name: '',
  pasture_name: '',
  user_name: ''
});

const tableData = ref<ApiMqttAuth.Auth[]>([]);
const editData = ref<Mqtt.Auth | null>(null);
const modalType = ref<ModalType>('add');
const groupEnumListData = ref<SelectOption[]>([]);

function setGroupList(data: SelectOption[]) {
  groupEnumListData.value = data;
}

function setEditData(data: Mqtt.Auth | null) {
  editData.value = data;
}

function setTableData(data: ApiMqttAuth.Auth[]) {
  tableData.value = data;
}

function setModalType(type: ModalType) {
  modalType.value = type;
}

async function getTableData() {
  startLoading();
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
  const { data } = await fetchMqttAuthList(pagination.page, pagination.pageSize, formValue.value);
  if (data) {
    setTableData(data);
    endLoading();
  } else {
    endLoading();
  }
}

async function getGroupEnumList() {
  const { data } = await groupEnumList();
  if (data) {
    setTimeout(() => {
      setGroupList(data);
    }, 100);
  }
}

const columns: Ref<DataTableColumns<ApiMqttAuth.Auth>> = ref([
  {
    type: 'selection',
    align: 'center'
  },
  {
    key: 'index',
    title: '序号',
    align: 'center'
  },
  {
    key: 'pasture_name',
    title: '牧场名称',
    align: 'center'
  },
  {
    key: 'group_name',
    title: '集团名称',
    align: 'center'
  },
  {
    key: 'mount_point',
    title: '挂载点',
    align: 'center'
  },
  {
    key: 'client_id',
    title: '客户端ID',
    align: 'center'
  },
  {
    key: 'user_name',
    title: '用户名称',
    align: 'center'
  },
  {
    key: 'subscribe_topic_name_stings',
    title: '订阅topic名称',
    align: 'center'
  },
  {
    key: 'subscribe_acl',
    title: '订阅topic',
    align: 'center'
  },
  {
    key: 'publish_topic_name_stings',
    title: '发布topic名称',
    align: 'center'
  },
  {
    key: 'publish_acl',
    title: '发布topic',
    align: 'center'
  },
  {
    key: 'actions',
    title: '操作',
    align: 'center',
    render: row => {
      return (
        <NSpace justify={'center'}>
          <NButton type="info" size={'small'} onClick={() => handleEditTable(row.id)}>
            编辑
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDeleteTable(row.id)}>
            {{
              default: () => '确认删除',
              trigger: () => (
                <NButton type="error" size={'small'}>
                  删除
                </NButton>
              )
            }}
          </NPopconfirm>
        </NSpace>
      );
    }
  }
]) as Ref<DataTableColumns<ApiMqttAuth.Auth>>;

const pagination: PaginationProps = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 15, 20, 25, 30],
  onChange: (page: number) => {
    pagination.page = page;
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
  }
});

async function handleSearch() {
  if (!formValue.value) {
    window.$message?.warning('请输入相关名称');
  } else {
    startLoading();
    const { data } = await fetchMqttAuthList(pagination.page, pagination.pageSize, formValue.value);
    if (data) {
      setTableData(data);
      endLoading();
    } else {
      endLoading();
    }
  }
}

function handleEditTable(rowId: number) {
  const findItem = tableData.value.find(item => item.id === rowId);
  if (findItem) {
    setEditData(findItem);
  }
  setModalType('edit');
  openModal();
}

function handleDeleteTable(rowId: number) {
  const data = mqttAuthDelete(rowId);
  data.then(res => {
    if (res.data) {
      window.$message?.success('删除成功！');
    }
  });
  init();
}

function handleModalVisibilityChange() {
  setTimeout(() => {
    getTableData();
  }, 200);
}

function handleAddTable() {
  getGroupEnumList();
  openModal();
  setModalType('add');
}

function init() {
  getTableData();
}

// 初始化
init();
</script>

<style scoped></style>
