<script setup lang="ts">
import { ref, watch } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { getSmartCabinetList, SmartCabinetDTO } from "@/api/cabinet/smart-cabinet";
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 SmartCabinetFormModal from "./smart-cabinet-form-modal.vue";
import SmartCabinetEditModal from "./smart-cabinet-edit-modal.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "@/router";
import { deleteSmartCabinet } from "@/api/cabinet/smart-cabinet";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import GatewayConfigModal from "./GatewayConfigModal.vue";
import ShopConfigModal from "./ShopConfigModal.vue";
import MainCabinetConfigModal from "./MainCabinetConfigModal.vue";

defineOptions({
  name: "SmartCabinet"
});

const formRef = ref();
const tableRef = ref();
const modalVisible = ref(false);

const searchFormParams = ref({
  cabinetName: "",
  cabinetType: null
});

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

const loading = ref(false);
const dataList = ref<SmartCabinetDTO[]>([]);
const multipleSelection = ref<number[]>([]);
const editVisible = ref(false);
const currentRow = ref<SmartCabinetDTO>();
const gatewayConfigVisible = ref(false);
const shopConfigVisible = ref(false);
const mainCabinetConfigVisible = ref(false);
const currentCabinetId = ref<number>(0);

const getList = async () => {
  try {
    loading.value = true;
    const { data } = await getSmartCabinetList({
      ...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: SmartCabinetDTO) => {
  try {
    await deleteSmartCabinet(row.cabinetId!.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}项设备吗？`,
      "警告",
      { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
    );

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

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

const goCellManagement = (row: SmartCabinetDTO) => {
  // 保存信息到标签页
  useMultiTagsStoreHook().handleTags("push", {
    path: `/cabinet/cabinet-cell/index`,
    name: "CabinetCell",
    query: { cabinetId: row.cabinetId },
    meta: {
      title: `柜机${row.cabinetId} - 格口信息`,
      dynamicLevel: 3
    }
  });
  router.push({
    path: '/cabinet/cabinet-cell/index',
    query: { cabinetId: row.cabinetId }
  });
};

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

const handleGatewayConfig = (row: SmartCabinetDTO) => {
  currentCabinetId.value = row.cabinetId;
  gatewayConfigVisible.value = true;
};

const handleShopConfig = (row: SmartCabinetDTO) => {
  currentCabinetId.value = row.cabinetId;
  shopConfigVisible.value = true;
};

const handleMainCabinetConfig = (row: SmartCabinetDTO) => {
  currentCabinetId.value = row.cabinetId;
  mainCabinetConfigVisible.value = true;
};

getList();
</script>

<template>
  <div class="main">
    <el-form ref="formRef" :inline="true" :model="searchFormParams"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]">
      <el-form-item label="柜体名称：" prop="cabinetName">
        <el-input v-model="searchFormParams.cabinetName" placeholder="请输入柜体名称" clearable class="!w-[200px]" />
      </el-form-item>
      <el-form-item label="柜体类型：" prop="cabinetType">
        <el-select v-model="searchFormParams.cabinetType" placeholder="请选择类型" clearable class="!w-[180px]">
          <el-option label="主柜" :value="0" />
          <el-option label="副柜" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="useRenderIcon(Search)" @click="onSearch">
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar title="智能柜管理" @refresh="getList">
      <template #buttons>
        <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="modalVisible = true">
          新增设备
        </el-button>
        <el-button type="danger" :icon="useRenderIcon(Delete)" :disabled="multipleSelection.length === 0"
          @click="handleBulkDelete">
          批量删除
        </el-button>
      </template>
      <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="柜体名称" prop="cabinetName" />
        <el-table-column label="归属商店" prop="shopName" width="180">
          <template #default="{ row }">
            <span>{{ row.shopName }}</span>
            <el-button type="success" link :icon="useRenderIcon('ep:shop')" @click="handleShopConfig(row)">
              配置
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="归属主柜" prop="mainCabinetName" width="180">
          <template #default="{ row }">
            <template v-if="row.cabinetType === 1">
              <span>{{ row.mainCabinetName || '-' }}</span>
              <el-button type="primary" link :icon="useRenderIcon('ep:setting')" @click="handleMainCabinetConfig(row)">
                配置
              </el-button>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="柜体类型" prop="cabinetType" width="120">
          <template #default="{ row }">
            <el-tag :type="row.cabinetType === 0 ? 'success' : 'warning'">
              {{ row.cabinetType === 0 ? '主柜' : '副柜' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="模板编号" prop="templateNo" width="180" />
        <el-table-column label="锁控编号" prop="lockControlNo" width="120" />
        <el-table-column label="网关ID" prop="mqttServerId" width="180">
          <template #default="{ row }">
            <span>{{ row.mqttServerId }}</span>
            <el-button type="warning" link :icon="useRenderIcon('ant-design:gateway-outlined')"
              @click="handleGatewayConfig(row)">
              配置
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="位置" prop="location" 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-button type="warning" link :icon="useRenderIcon(EditPen)" @click="goCellManagement(row)">
              格口
            </el-button>
            <el-popconfirm :title="`确认删除【${row.cabinetName}】？`" @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" />
    </PureTableBar>
    <smart-cabinet-form-modal v-model:visible="modalVisible" @refresh="getList" />
    <smart-cabinet-edit-modal v-model:visible="editVisible" :row="currentRow" @refresh="getList" />
    <GatewayConfigModal v-model="gatewayConfigVisible" :cabinet-id="currentCabinetId" @refresh="getList" />
    <ShopConfigModal v-model="shopConfigVisible" :cabinet-id="currentCabinetId" @refresh="getList" />
    <MainCabinetConfigModal v-model="mainCabinetConfigVisible" :cabinet-id="currentCabinetId" @refresh="getList" />
  </div>
</template>