<script setup lang="ts">
import { ref, computed } from "vue";
import { useDevice } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Refresh from "~icons/ep/refresh";
import Unlock from "~icons/ep/unlock";
import Temperature from "~icons/ri/temp-hot-line";
import Volume from "~icons/ri/volume-up-line";
import Document from "~icons/ep/document";
import User from "~icons/ep/user";
import Monitor from "~icons/ep/monitor";

defineOptions({
  name: "DeviceManage"
});

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

const {
  form,
  loading,
  columns,
  dataList,
  pagination,
  shopOptions,
  onSearch,
  resetForm,
  handleOpenDoor,
  handleSetTemperature,
  handleSetVolume,
  handleSizeChange,
  handleCurrentChange,
  operatingIds,
  showDoorRecords,
  dialogVisible,
  recordLoading,
  recordList,
  recordColumns,
  recordPagination,
  handleRecordSizeChange,
  handleRecordCurrentChange,
  replenisherDialogVisible,
  replenisherLoading,
  currentDeviceForReplenisher,
  boundReplenishers,
  allReplenishers,
  selectedReplenisherIds,
  replenisherFilterKeyword,
  filteredReplenishers,
  replenisherAllSelected,
  replenisherSelectPartial,
  confirmReplenisherLoading,
  handleDeviceDetailStatus,
  handleBindReplenisher,
  toggleReplenisherSelect,
  toggleAllReplenishers,
  handleReplenisherConfirm
} = useDevice(tableRef);
</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="shopId">
        <el-select
          v-model="form.shopId"
          placeholder="请选择门店"
          clearable
          class="w-[180px]!"
        >
          <el-option
            v-for="shop in shopOptions"
            :key="shop.id"
            :label="shop.name"
            :value="shop.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态：" prop="status">
        <el-select
          v-model="form.status"
          placeholder="请选择状态"
          clearable
          class="w-[180px]!"
        >
          <el-option label="在线" :value="1" />
          <el-option label="离线" :value="0" />
        </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 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)'
          }"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(Unlock)"
              :loading="operatingIds.has(row.id)"
              @click="handleOpenDoor(row)"
            >
              开门
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(Temperature)"
              :loading="operatingIds.has(row.id)"
              @click="handleSetTemperature(row)"
            >
              温度
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(Volume)"
              :loading="operatingIds.has(row.id)"
              @click="handleSetVolume(row)"
            >
              音量
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(Monitor)"
              @click="handleDeviceDetailStatus(row)"
            >
              详细状态
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(Document)"
              @click="showDoorRecords(row)"
            >
              开关门记录
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(User)"
              @click="handleBindReplenisher(row)"
            >
              补货员
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <!-- 开关门记录弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="开关门记录"
      width="90%"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <pure-table
        row-key="id"
        :loading="recordLoading"
        :data="recordList"
        :columns="recordColumns"
        :pagination="{ ...recordPagination, size: 'default' }"
        @page-size-change="handleRecordSizeChange"
        @page-current-change="handleRecordCurrentChange"
      />
    </el-dialog>

    <!-- 补货员绑定弹窗（勾选模式） -->
    <el-dialog
      v-model="replenisherDialogVisible"
      :title="`补货员绑定 - ${currentDeviceForReplenisher?.deviceId || ''}`"
      width="500px"
      draggable
      :close-on-click-modal="false"
      destroy-on-close
    >
      <div v-loading="replenisherLoading" class="replenisher-dialog-container">
        <!-- 绑定状态摘要 -->
        <div class="mb-3 px-1 text-sm text-gray-500 flex items-center gap-1">
          已选择
          <span class="font-bold text-[var(--el-color-primary)]">{{ selectedReplenisherIds.size }}</span>
          名补货员
          <el-divider direction="vertical" />
          共 {{ allReplenishers.length }} 名补货员
        </div>

        <!-- 搜索过滤 -->
        <el-input
          v-model="replenisherFilterKeyword"
          placeholder="输入姓名/手机号/工号筛选补货员"
          clearable
          class="mb-2"
          size="small"
        />

        <!-- 全选 -->
        <div class="flex items-center px-1 pb-2 border-b border-gray-100 mb-2">
          <el-checkbox
            :model-value="replenisherAllSelected && filteredReplenishers.length > 0"
            :indeterminate="replenisherSelectPartial"
            size="small"
            @change="toggleAllReplenishers"
          />
          <span class="ml-2 text-xs text-gray-400">全选当前列表（{{ filteredReplenishers.length }}人）</span>
        </div>

        <!-- 补货员列表 -->
        <div v-if="allReplenishers.length === 0 && !replenisherLoading" class="py-8">
          <el-empty description="暂无可用补货员" />
        </div>

        <div v-if="filteredReplenishers.length > 0" class="divide-y divide-gray-100">
          <label
            v-for="r in filteredReplenishers"
            :key="r.id"
            class="replenisher-item flex items-center px-3 py-2.5 hover:bg-gray-50/50 cursor-pointer transition-colors rounded"
          >
            <el-checkbox
              :model-value="selectedReplenisherIds.has(r.id)"
              size="small"
              @change="toggleReplenisherSelect(r.id)"
            />
            <div class="ml-2.5 flex items-center gap-2 min-w-0">
              <span class="text-sm font-medium truncate">{{ r.name }}</span>
              <span v-if="r.phone" class="text-xs text-gray-400 shrink-0">{{ r.phone }}</span>
              <el-tag v-if="r.employeeId" size="small" type="info" class="shrink-0">{{ r.employeeId }}</el-tag>
            </div>
          </label>
        </div>
        <div v-else-if="!replenisherLoading && replenisherFilterKeyword && allReplenishers.length > 0" class="text-xs text-gray-400 text-center py-4">
          未找到匹配的补货员
        </div>
      </div>

      <template #footer>
        <el-button @click="replenisherDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="confirmReplenisherLoading"
          @click="handleReplenisherConfirm"
        >
          确认绑定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

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

.replenisher-dialog-container {
  min-height: 200px;
  max-height: 450px;
  overflow-y: auto;
}

.replenisher-item {
  transition: background-color 0.2s;
  &:hover {
    background-color: var(--el-fill-color-darker);
  }
}
</style>
