<script setup lang="ts">
import { ref } from "vue";
import { useReplenisher } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";

import Delete from "~icons/ep/delete";
import EditPen from "~icons/ep/edit-pen";
import Refresh from "~icons/ep/refresh";
import AddFill from "~icons/ri/add-circle-line";
import Link from "~icons/ep/link";
import ArrowRight from "~icons/ep/arrow-right";

defineOptions({
  name: "ReplenisherManage"
});

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

const {
  form,
  loading,
  columns,
  dataList,
  pagination,
  onSearch,
  resetForm,
  openDialog,
  handleDelete,
  openBindingCodeDialog,
  bindingDialogVisible,
  bindingCodeData,
  generatingCode,
  formatBindingCode,
  copyBindingCode,
  openBindDialog,
  bindDialogVisible,
  currentReplenisher,
  deviceLoading,
  shopDeviceTree,
  loadingShopTree,
  selectedDeviceIds,
  toggleDeviceSelect,
  toggleShopSelectAll,
  getShopSelectState,
  handleConfirmBind,
  shopSearchKeyword,
  filteredShopTree,
  allDevicesCount,
  isAllSelected,
  toggleSelectAll,
  resetShopSearch,
  handleSizeChange,
  handleCurrentChange
} = useReplenisher(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="关键词：" prop="keyword">
        <el-input
          v-model="form.keyword"
          placeholder="搜索姓名/手机号/工号"
          clearable
          class="w-[200px]!"
        />
      </el-form-item>
      <el-form-item label="状态：" prop="status">
        <el-select
          v-model="form.status"
          placeholder="请选择状态"
          clearable
          class="w-[140px]!"
        >
          <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 #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="openDialog()"
        >
          新增补货员
        </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)'
          }"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(Link)"
              @click="openBindDialog(row)"
            >
              设备
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              @click="openBindingCodeDialog(row)"
            >
              绑定码
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="openDialog('修改', row)"
            >
              修改
            </el-button>
            <el-popconfirm
              :title="`是否确认删除补货员 ${row.name}?`"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon(Delete)"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <!-- 设备绑定弹窗（门店设备树） -->
    <el-dialog
      v-model="bindDialogVisible"
      :title="`设备绑定 - ${currentReplenisher?.name || ''}`"
      width="600px"
      draggable
      :close-on-click-modal="false"
      @close="resetShopSearch"
    >
      <div v-loading="loadingShopTree" class="bind-device-container">
        <!-- 搜索 + 全选 -->
        <div class="mb-3 flex items-center gap-3">
          <el-input
            v-model="shopSearchKeyword"
            placeholder="搜索门店名称或地址"
            clearable
            size="small"
            class="flex-1"
            :prefix-icon="useRenderIcon('ri/search-line')"
          />
          <el-checkbox
            :model-value="isAllSelected"
            :indeterminate="selectedDeviceIds.size > 0 && !isAllSelected"
            size="small"
            @change="toggleSelectAll"
          >
            全选 {{ selectedDeviceIds.size }}/{{ allDevicesCount }}
          </el-checkbox>
        </div>

        <!-- 绑定状态摘要 -->
        <div class="mb-3 px-1 text-sm text-gray-500 flex items-center gap-1">
          共 {{ shopDeviceTree.length }} 个门店
        </div>

        <!-- 门店设备列表 -->
        <div v-if="filteredShopTree.length === 0 && !loadingShopTree" class="py-8">
          <el-empty :description="shopSearchKeyword ? '未匹配到门店' : '暂无可用门店'" />
        </div>

        <div v-for="shop in filteredShopTree" :key="shop.id" class="mb-3 border rounded-lg overflow-hidden">
          <!-- 门店头部 -->
          <div
            class="flex items-center px-3 py-2.5 cursor-pointer select-none transition-colors hover:bg-gray-50"
            :class="{ 'border-b': shop.expanded }"
            @click="shop.expanded = !shop.expanded"
          >
            <el-icon
              class="mr-1.5 transition-transform duration-200 text-gray-400"
              :class="{ 'rotate-90': shop.expanded }"
            >
              <ArrowRight />
            </el-icon>
            <span class="flex-1 text-sm font-medium truncate">{{ shop.name }}</span>
            <span class="text-xs text-gray-400 mr-2">{{ shop.devices.length }}台设备</span>
            <el-checkbox
              :indeterminate="getShopSelectState(shop) === 'partial'"
              :model-value="getShopSelectState(shop) === 'all'"
              size="small"
              @click.stop
              @change="toggleShopSelectAll(shop)"
            />
          </div>
          <!-- 门店下设备列表 -->
          <div v-if="shop.expanded" class="divide-y divide-gray-50">
            <label
              v-for="device in shop.devices"
              :key="device.deviceId"
              class="flex items-center px-5 py-2.5 hover:bg-gray-50/50 cursor-pointer transition-colors"
            >
              <el-checkbox
                :model-value="selectedDeviceIds.has(device.deviceId)"
                size="small"
                @change="toggleDeviceSelect(device.deviceId)"
              />
              <span class="ml-2.5 text-sm">{{ device.name || device.deviceId }}</span>
              <span class="ml-1.5 text-xs text-gray-400">({{ device.deviceId }})</span>
            </label>
            <el-empty
              v-if="shop.devices.length === 0"
              description="该门店暂无设备"
              :image-size="50"
            />
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="bindDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="deviceLoading"
          @click="handleConfirmBind"
        >
          确认绑定
        </el-button>
      </template>
    </el-dialog>

    <!-- 绑定码弹窗 -->
    <el-dialog
      v-model="bindingDialogVisible"
      title="补货员微信绑定"
      width="520px"
      draggable
      :close-on-click-modal="false"
      @close="bindingDialogVisible = false"
    >
      <div v-loading="generatingCode" class="binding-dialog-body">
        <!-- 补货员信息 -->
        <div class="binding-header">
          <div class="binding-avatar">{{ (currentReplenisher?.name || '').charAt(0) || '?' }}</div>
          <div class="binding-user-info">
            <div class="binding-user-name">{{ currentReplenisher?.name || '未知' }}</div>
            <div class="binding-user-tag">补货员</div>
          </div>
        </div>

        <div class="binding-steps">
          <div class="step-item">
            <div class="step-num active">1</div>
            <div class="step-desc">管理员确认补货员身份，生成一次性绑定码</div>
          </div>
          <div class="step-item">
            <div class="step-num" :class="{ active: bindingCodeData.bindingCode }">2</div>
            <div class="step-desc">分享绑定码或二维码给补货员</div>
          </div>
          <div class="step-item">
            <div class="step-num" :class="{ active: bindingCodeData.bindingCode }">3</div>
            <div class="step-desc">补货员在小程序端完成微信绑定</div>
          </div>
        </div>

        <!-- 绑定码展示 -->
        <template v-if="bindingCodeData.bindingCode">
          <div class="binding-code-section">
            <div class="section-label">绑定码（24小时内有效）</div>
            <div class="binding-code-value" @click="copyBindingCode">
              {{ bindingCodeData.bindingCode }}
            </div>
            <div class="binding-code-hint">点击绑定码可复制</div>
          </div>

          <!-- 二维码展示 -->
          <div v-if="bindingCodeData.qrCodeDataUrl" class="qr-section">
            <div class="section-label">绑定二维码</div>
            <div class="qr-wrapper">
              <img :src="bindingCodeData.qrCodeDataUrl" alt="绑定二维码" class="qr-image" />
            </div>
            <div class="qr-hint">补货员可在小程序登录页扫码识别</div>
          </div>

          <!-- 操作指引 -->
          <div class="manual-section">
            <div class="section-label">补货员操作步骤</div>
            <div class="manual-content">
              <div class="manual-step">1. 打开"哈哈运营平台"小程序</div>
              <div class="manual-step">2. 在登录页点击"已有绑定码？点击绑定微信"</div>
              <div class="manual-step">3. 点击"扫码识别"扫描上方二维码，或手动输入绑定码</div>
              <div class="manual-step">4. 授权微信完成绑定，自动进入补货首页</div>
            </div>
          </div>
        </template>

        <!-- 空状态 -->
        <div v-if="!bindingCodeData.bindingCode && !generatingCode" class="binding-placeholder">
          <el-empty description="请点击'生成'按钮" :image-size="80" />
        </div>
      </div>

      <template #footer>
        <el-button @click="bindingDialogVisible = false">关闭</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;
  }
}

.bind-device-container {
  min-height: 200px;
  max-height: 400px;
  overflow-y: auto;
}

.device-item {
  transition: background-color 0.2s;

  &:hover {
    background-color: var(--el-fill-color-darker);
  }
}

/* 绑定码弹窗样式 */
.binding-dialog-body {
  min-height: 200px;
  padding: 8px 0;

  .binding-header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 24px;
    padding-bottom: 20px;
    border-bottom: 1px solid var(--el-border-color-lighter);

    .binding-avatar {
      width: 48px;
      height: 48px;
      background: var(--el-color-primary-light-9);
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22px;
      font-weight: 700;
      color: var(--el-color-primary);
      flex-shrink: 0;
    }

    .binding-user-info {
      .binding-user-name {
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .binding-user-tag {
        font-size: 12px;
        color: var(--el-color-primary);
        background: var(--el-color-primary-light-9);
        display: inline-block;
        padding: 2px 10px;
        border-radius: 4px;
        margin-top: 4px;
      }
    }
  }

  .binding-steps {
    margin-bottom: 24px;

    .step-item {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      margin-bottom: 14px;

      &:last-child {
        margin-bottom: 0;
      }

      .step-num {
        width: 22px;
        height: 22px;
        border-radius: 50%;
        background: var(--el-border-color-lighter);
        color: var(--el-text-color-placeholder);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: 600;
        flex-shrink: 0;
        margin-top: 1px;

        &.active {
          background: var(--el-color-primary);
          color: #fff;
        }
      }

      .step-desc {
        font-size: 13px;
        color: var(--el-text-color-regular);
        line-height: 1.5;
      }
    }
  }

  .section-label {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-bottom: 10px;
  }

  .binding-code-section {
    margin-bottom: 24px;

    .binding-code-value {
      background: var(--el-fill-color-light);
      border: 1px dashed var(--el-color-primary);
      border-radius: 8px;
      padding: 14px 20px;
      font-size: 20px;
      font-weight: 700;
      font-family: 'Courier New', Courier, monospace;
      letter-spacing: 4px;
      text-align: center;
      color: var(--el-color-primary);
      cursor: pointer;
      transition: background 0.15s;
      user-select: all;

      &:hover {
        background: var(--el-color-primary-light-9);
      }
    }

    .binding-code-hint {
      font-size: 12px;
      color: var(--el-text-color-placeholder);
      margin-top: 6px;
      text-align: center;
    }
  }

  .qr-section {
    margin-bottom: 24px;

    .qr-wrapper {
      display: flex;
      justify-content: center;
      background: #fff;
      border: 1px solid var(--el-border-color-lighter);
      border-radius: 8px;
      padding: 16px;
      width: fit-content;
      margin: 0 auto;

      .qr-image {
        width: 200px;
        height: 200px;
        display: block;
      }
    }

    .qr-hint {
      font-size: 12px;
      color: var(--el-text-color-placeholder);
      margin-top: 6px;
      text-align: center;
    }
  }

  .manual-section {
    margin-bottom: 8px;

    .section-label {
      font-size: 14px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 10px;
    }

    .manual-content {
      background: var(--el-color-primary-light-9);
      border: 1px solid var(--el-color-primary-light-7);
      border-radius: 8px;
      padding: 14px 18px;

      .manual-step {
        font-size: 13px;
        color: var(--el-text-color-secondary);
        line-height: 2;
      }
    }
  }

  .binding-placeholder {
    padding: 30px 0;
  }
}
</style>
