<script setup lang="ts">
import { ref } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { getMqttServerList, MqttServerDTO, deleteMqttServer, SearchMqttServerQuery } from "@/api/cabinet/mqttServer";
import EditPen from "@iconify-icons/ep/edit-pen";
import Delete from "@iconify-icons/ep/delete";
import AddFill from "@iconify-icons/ri/add-circle-line";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import { ElMessage, ElMessageBox } from "element-plus";
import MqttServerFormModal from "./mqtt-server-form-modal.vue";

defineOptions({
  name: "MqttServer"
});

const formRef = ref();
const tableRef = ref();
const modalVisible = ref(false);
const handleRefresh = () => {
  getList();
  modalVisible.value = false;
  editVisible.value = false;
};

const searchFormParams = ref<SearchMqttServerQuery>({
  serverUrl: "",
  username: ""
});

const pagination = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0
});

const loading = ref(false);
const dataList = ref<MqttServerDTO[]>([]);
const multipleSelection = ref<number[]>([]);
const editVisible = ref(false);
const currentRow = ref<MqttServerDTO>();

const getList = async () => {
  try {
    loading.value = true;
    const { data } = await getMqttServerList({
      ...searchFormParams.value,
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.currentPage
    });
    dataList.value = data.rows;
    pagination.value.total = data.total;
  } finally {
    loading.value = false;
  }
};

const onSearch = () => {
  pagination.value.currentPage = 1;
  getList();
};

const resetForm = () => {
  formRef.value.resetFields();
  onSearch();
};

const onSizeChange = (val: number) => {
  pagination.value.pageSize = val;
  getList();
};

const onCurrentChange = (val: number) => {
  pagination.value.currentPage = val;
  getList();
};

const handleDelete = async (row: MqttServerDTO) => {
  try {
    await deleteMqttServer(row.mqttServerId!.toString());
    ElMessage.success("删除成功");
    getList();
  } catch (error) {
    console.error("删除失败", error);
  }
};

const handleBulkDelete = async () => {
  if (multipleSelection.value.length === 0) return;

  try {
    await ElMessageBox.confirm(
      `确认删除选中的${multipleSelection.value.length}项MQTT服务吗？`,
      "警告",
      { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
    );

    await deleteMqttServer(multipleSelection.value.join(","));
    ElMessage.success("批量删除成功");
    multipleSelection.value = [];
    getList();
  } catch (error) {
    console.error("删除取消或失败", error);
  }
};

const handleSelectionChange = (rows: MqttServerDTO[]) => {
  multipleSelection.value = rows.map(row => row.mqttServerId!);
};

const handleEdit = (row: MqttServerDTO) => {
  currentRow.value = row;
  editVisible.value = true;
};

getList();
</script>

<template>
  <div class="main">
    <el-form ref="formRef" :inline="true" :model="searchFormParams"
      class="search-form bg-bg_color flex w-[99/100] pl-[22px] pt-[12px]">
      <el-form-item prop="serverUrl">
        <el-input @keydown.enter.prevent="onSearch" v-model="searchFormParams.serverUrl" placeholder="请输入服务地址" clearable
          class="!w-[200px]" />
      </el-form-item>
      <el-form-item prop="username">
        <el-input @keydown.enter.prevent="onSearch" v-model="searchFormParams.username" placeholder="请输入用户名" clearable
          class="!w-[200px]" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="useRenderIcon(Search)" @click="onSearch">
          搜索
        </el-button>
      </el-form-item>
      <el-form-item class="space-item">
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="modalVisible = true">
          新增服务
        </el-button>
      </el-form-item>
    </el-form>

    <div class="table-container">
      <el-table ref="tableRef" v-loading="loading" :data="dataList" row-key="id"
        @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" />
        <el-table-column label="服务ID" prop="mqttServerId" width="100" />
        <el-table-column label="服务地址" prop="serverUrl" />
        <el-table-column label="用户名" prop="username" width="120" />
        <el-table-column label="主题过滤" prop="topicFilter" width="180" />
        <el-table-column label="发布主题" prop="publishTopic" width="120" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link :icon="useRenderIcon(EditPen)" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-popconfirm :title="`确认删除【${row.serverUrl}】？`" @confirm="handleDelete(row)">
              <template #reference>
                <el-button type="danger" link :icon="useRenderIcon(Delete)">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
        @size-change="onSizeChange" @current-change="onCurrentChange" class="pagination" />
    </div>
    <MqttServerFormModal :visible="modalVisible" @update:visible="val => modalVisible = val" @refresh="handleRefresh" />
    <MqttServerFormModal :visible="editVisible" :row="currentRow" @update:visible="val => editVisible = val"
      @refresh="handleRefresh" />
  </div>
</template>

<style scoped lang="scss">
.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
    margin-right: 12px;
  }
}
.space-item {
  flex: 1;
  width: 100%;
}
.table-container {
  margin-top: 8px;
  background-color: var(--el-bg-color);
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;

  .el-table {
    flex: 1;
    overflow: hidden;
  }

  .pagination {
    margin-top: 10px;
  }
}
</style>