<script setup lang="ts">
import { ref } from "vue";
import { useProduct } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import EditDialog from "./components/EditDialog.vue";
import Refresh from "~icons/ep/refresh";
import Delete from "~icons/ep/delete";
import EditPen from "~icons/ep/edit-pen";
import AddFill from "~icons/ri/add-circle-line";
import SyncAll from "~icons/ep/upload"; // 全量同步图标
import SyncOne from "~icons/ep/refresh-right"; // 单个设备同步图标

defineOptions({
  name: "LayerTemplateManage"
});

const formRef = ref();
const tableRef = ref();
const editDialogRef = ref();

const {
  form,
  loading,
  columns,
  dataList,
  pagination,
  syncStatusOptions,
  templateTypeOptions,

  // 设备相关（新增）
  deviceOptions,
  deviceLoading,
  selectedDeviceId,
  syncAllLoading,

  onSearch,
  resetForm,
  handleDelete,
  handleSyncByDevice,
  handleSyncAll,
  loadDeviceList,
  handleSizeChange,
  handleCurrentChange
} = useProduct(tableRef);

/**
 * 打开新增/编辑对话框
 * Open add/edit dialog
 * @param title - 对话框标题
 * @param row - 编辑时的行数据(可选)
 */
function openDialog(title?: string, row?: any) {
  editDialogRef.value?.open(title || "新增层模版", row);
}

/**
 * 处理单个设备同步
 * Handle single device sync (from dropdown selection)
 */
function handleSingleSync() {
  if (!selectedDeviceId.value) {
    // 如果没有选择设备，提示用户
    const msg = {
      type: "warning" as const,
      message: "请先选择要同步的设备"
    };
    import("@/utils/message").then(({ message }) => (message as any)(msg));
    return;
  }
  handleSyncByDevice(selectedDeviceId.value);
}
</script>

<template>
  <div class="main">
    <!-- 搜索表单区域 -->
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item label="设备ID：" prop="deviceId">
        <el-input
          v-model="form.deviceId"
          placeholder="请输入设备ID"
          clearable
          class="w-[180px]!"
        />
      </el-form-item>
      <el-form-item label="模板名称：" prop="templateName">
        <el-input
          v-model="form.templateName"
          placeholder="请输入模板名称"
          clearable
          class="w-[180px]!"
        />
      </el-form-item>
      <el-form-item label="同步状态：" prop="syncStatus">
        <el-select
          v-model="form.syncStatus"
          placeholder="请选择状态"
          clearable
          class="w-[180px]!"
        >
          <el-option
            v-for="item in syncStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="模版类型：" prop="templateType">
        <el-select
          v-model="form.templateType"
          placeholder="请选择模版类型"
          clearable
          class="w-[180px]!"
        >
          <el-option
            v-for="item in templateTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri/search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 表格区域 -->
    <PureTableBar
      title="设备模版管理"
      :columns="columns"
      @refresh="onSearch"
    >
      <!-- 操作按钮区域：包含新增、设备选择同步、全量同步 -->
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="openDialog()"
        >
          新增设备模版
        </el-button>

        <!-- 分隔线 -->
        <el-divider direction="vertical" class="!mx-2" />

        <!-- 单个设备同步：设备选择器 + 同步按钮 -->
        <el-select
          v-model="selectedDeviceId"
          placeholder="请选择要同步的设备"
          filterable
          clearable
          class="w-[240px]!"
          :loading="deviceLoading"
          :disabled="syncAllLoading"
          @visible-change="(visible: boolean) => visible && loadDeviceList()"
        >
          <template #empty>
            <div class="flex flex-col items-center py-3">
              <p class="text-gray-500 text-sm">{{ deviceLoading ? '加载中...' : '暂无可用设备' }}</p>
              <el-button
                v-if="!deviceLoading && deviceOptions.length === 0"
                type="primary"
                link
                size="small"
                class="mt-2"
                @click="loadDeviceList()"
              >
                点击重新加载
              </el-button>
            </div>
          </template>
          <el-option
            v-for="device in deviceOptions"
            :key="device.deviceId"
            :label="device.shopName ? `${device.deviceId} — ${device.shopName}` : device.deviceId"
            :value="device.deviceId"
          >
            <div class="flex items-center justify-between w-full">
              <span>{{ device.shopName ? `${device.deviceId} — ${device.shopName}` : device.deviceId }}</span>
              <el-tag
                v-if="device.isOnline !== undefined && device.isOnline !== null"
                size="small"
                :type="(device.isOnline as any) === true ? 'success' : 'info'"
                effect="light"
                round
              >
                {{ (device.isOnline as any) === true ? '在线' : '离线' }}
              </el-tag>
            </div>
          </el-option>
        </el-select>

        <el-button
          type="success"
          :icon="useRenderIcon(SyncOne)"
          :disabled="!selectedDeviceId || syncAllLoading"
          @click="handleSingleSync()"
        >
          同步选中设备
        </el-button>

        <!-- 全量同步按钮 -->
        <el-button
          type="warning"
          :icon="useRenderIcon(SyncAll)"
          :loading="syncAllLoading"
          @click="handleSyncAll()"
        >
          {{ syncAllLoading ? '同步中...' : '全量同步所有设备' }}
        </el-button>
      </template>

      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          ref="tableRef"
          row-key="id"
          adaptive
          :adaptiveConfig="{ offsetBottom: 108 }"
          align-whole="center"
          table-layout="auto"
          :loading="loading"
          :size="size"
          :data="dataList"
          :columns="dynamicColumns"
          :pagination="{ ...pagination, size }"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)',
            textAlign: 'center'
          }"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <!-- 操作列插槽 -->
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="openDialog('修改', row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`是否确认删除模板 ${row.templateName}?`"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="danger"
                  :size="size"
                  :icon="useRenderIcon(Delete)"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <!-- 编辑对话框组件 -->
    <EditDialog ref="editDialogRef" @success="onSearch" />
  </div>
</template>

<style lang="scss" scoped>
.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

/* 强制表格单元格内容居中，解决 showOverflowTooltip 导致的对齐问题 */
:deep(.el-table__body-wrapper .el-table__cell) {
  text-align: center;
}
</style>
