<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.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(1, 10)">
            <icon-mdi-refresh class="mr-4px text-16px" :class="{ 'animate-spin': loading }" />
            刷新表格
          </n-button>
        </n-space>
      </n-space>
      <n-data-table remote :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>({
  pub_topic_name: '',
  sub_topic_name: '',
  pasture_name: '',
  user_name: ''
});

const tableData = ref<Mqtt.Auth[]>([]);
const editData = ref<Mqtt.Auth | null>(null);
const modalType = ref<ModalType>('add');
const groupEnumListData = ref<SelectOption[]>([]);
const defaultPage = ref(1);
const defaultPageSize = ref(10);
const pagination: PaginationProps = reactive({
  page: defaultPage.value,
  pageSize: defaultPageSize.value,
  itemCount: 100,
  showSizePicker: true,
  pageSizes: [10, 15, 20, 30, 50],
  onChange: (page: number) => {
    pagination.page = page;
    getTableData(page, Number(pagination.pageSize));
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    getTableData(Number(pagination.page), pageSize);
  }
});

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

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

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

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

async function getTableData(page: number, pageSize: number) {
  startLoading();
  const { data } = await fetchMqttAuthList(page, pageSize, formValue.value);
  if (data) {
    setTableData(data.list);
    pagination.pageCount = Math.ceil(data.count / data.list.length);
    pagination.itemCount = data.count;
    pagination.page = data.page;
    pagination.pageSize = data.page_size;
    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: 'key',
    title: '序号',
    align: 'center'
  },
  {
    key: 'pasture_name',
    title: '牧场名称',
    align: 'center'
  },
  {
    key: 'mount_point',
    title: '挂载点',
    align: 'center'
  },
  {
    key: 'client_id',
    title: '客户端ID',
    align: 'center'
  },
  {
    key: 'user_name',
    title: '用户名称',
    align: 'center'
  },
  {
    key: 'sub_topic_name',
    title: '订阅topic名称',
    align: 'center'
  },
  {
    key: 'subscribe_acl',
    title: '订阅topic',
    align: 'center'
  },
  {
    key: 'pub_topic_name',
    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>>;

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

function handleEditTable(rowId: number) {
  getGroupEnumList();
  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('删除成功！');
    }
  });
  setTimeout(() => {
    init();
  }, 100);
}

function handleModalVisibilityChange() {
  setTimeout(() => {
    getTableData(defaultPage.value, defaultPageSize.value);
  }, 200);
}

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

function init() {
  getTableData(defaultPage.value, defaultPageSize.value);
}

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

<style scoped></style>
