<template>
  <view class="page">
    <NavBar title="补货员管理" :showBack="true" @back="goBack" />

    <!-- 搜索 -->
    <view class="search-bar">
      <view class="search-box">
        <view class="search-icon">
          <view class="si-ring"></view>
          <view class="si-stem"></view>
        </view>
        <input
          class="search-input"
          v-model="keyword"
          placeholder="姓名 / 手机号 / 工号"
          placeholder-class="search-ph"
          confirm-type="search"
          @confirm="handleSearch"
        />
      </view>
      <view class="search-btn" @click="handleSearch">
        <text class="search-btn-text">搜索</text>
      </view>
    </view>

    <!-- 统计 -->
    <view class="stats" v-if="statistics">
      <view class="stat-item">
        <text class="stat-num">{{ statistics.total || 0 }}</text>
        <text class="stat-label">总数</text>
      </view>
      <view class="stat-divider"></view>
      <view class="stat-item">
        <text class="stat-num active">{{ statistics.active || 0 }}</text>
        <text class="stat-label">正常</text>
      </view>
      <view class="stat-divider"></view>
      <view class="stat-item">
        <text class="stat-num disabled">{{ statistics.disabled || 0 }}</text>
        <text class="stat-label">禁用</text>
      </view>
    </view>

    <!-- 列表 -->
    <scroll-view
      class="list-scroll"
      scroll-y
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="card-set" v-if="list.length > 0">
        <view
          class="card"
          v-for="item in list"
          :key="item.id"
          @click="goForm(item.id)"
          @longpress="showActions(item)"
        >
          <view class="card-avatar" :class="item.status === 0 ? 'off' : ''">
            <text>{{ (item.name || '?')[0] }}</text>
          </view>

          <view class="card-info">
            <view class="info-top">
              <text class="info-name">{{ item.name }}</text>
              <view class="info-status" :class="item.status === 1 ? 'on' : 'off'">
                <view class="info-dot" :class="item.status === 1 ? 'on' : 'off'"></view>
                <text>{{ item.status === 1 ? '正常' : '禁用' }}</text>
              </view>
            </view>
            <view class="info-sub">
              <text class="sub-phone" v-if="item.phone">{{ item.phone }}</text>
              <text class="sub-sep" v-if="item.phone && item.employeeId">·</text>
              <text class="sub-id" v-if="item.employeeId">工号 {{ item.employeeId }}</text>
            </view>
            <view class="info-meta">
              <text class="meta-item" v-if="item.boundDeviceCount != null">
                <text class="meta-val">{{ item.boundDeviceCount }}</text>
                <text class="meta-label">台设备</text>
              </text>
              <text class="meta-item" v-if="item.totalTasks != null">
                <text class="meta-val">{{ item.totalTasks }}</text>
                <text class="meta-label">次任务</text>
              </text>
            </view>
          </view>

          <view class="card-arrow">
            <view class="arr-inner"></view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="load-tip" v-if="loading">
        <view class="dot-row">
          <view class="pulse-dot"></view>
          <view class="pulse-dot"></view>
          <view class="pulse-dot"></view>
        </view>
      </view>

      <!-- 没有更多 -->
      <view class="end-tip" v-if="!hasMore && list.length > 0">
        <view class="end-line"></view>
        <text class="end-text">没有更多了</text>
        <view class="end-line"></view>
      </view>

      <!-- 空状态 -->
      <view class="empty" v-if="!loading && list.length === 0">
        <view class="empty-icon">
          <view class="empty-person">
            <view class="ep-head"></view>
            <view class="ep-body"></view>
          </view>
        </view>
        <text class="empty-title">暂无补货员</text>
        <text class="empty-desc">点击右下角按钮新增补货员</text>
      </view>
    </scroll-view>

    <!-- 新增按钮 -->
    <view class="fab" @click="goForm()">
      <text class="fab-text">+</text>
    </view>

    <CustomTabBar />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import NavBar from '@/components/NavBar.vue';
import CustomTabBar from '@/components/CustomTabBar.vue';
import {
  getReplenisherList,
  updateReplenisherStatus,
  deleteReplenisher,
  generateBindingCode,
  type ReplenisherQuery
} from '@/api/replenisher';

const list = ref<any[]>([]);
const loading = ref(false);
const hasMore = ref(true);
const page = ref(1);
const pageSize = 10;
const keyword = ref('');
const refreshing = ref(false);
const statistics = ref<{ total: number; active: number; disabled: number } | null>(null);

const fetchList = async () => {
  if (loading.value) return;
  loading.value = true;
  try {
    const params: ReplenisherQuery = { page: page.value, pageSize };
    if (keyword.value) {
      params.keyword = keyword.value;
    }
    const res = await getReplenisherList(params);
    if (page.value === 1) {
      list.value = res.list || [];
    } else {
      list.value = [...list.value, ...(res.list || [])];
    }
    hasMore.value = list.value.length < (res.total || 0);
    // 从列表数据推算统计（如果后端支持的话可以单独调统计接口）
    if (page.value === 1 && keyword.value === '') {
      const all = res.list || [];
      // 有总数字段就用total，否则从当前页推断
    }
  } catch (e) {
    // ignore
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

const fetchStats = async () => {
  try {
    // 用不带筛选条件的列表查询获取全局统计
    const res = await getReplenisherList({ page: 1, pageSize: 1 });
    const total = res.total || 0;
    // 分别查正常和禁用的数量
    const [activeRes, disabledRes] = await Promise.all([
      getReplenisherList({ page: 1, pageSize: 1, status: 1 }),
      getReplenisherList({ page: 1, pageSize: 1, status: 0 })
    ]);
    statistics.value = {
      total,
      active: activeRes.total || 0,
      disabled: disabledRes.total || 0
    };
  } catch (e) {
    // ignore
  }
};

const loadMore = () => {
  if (loading.value || !hasMore.value) return;
  page.value++;
  fetchList();
};

const onRefresh = () => {
  refreshing.value = true;
  page.value = 1;
  hasMore.value = true;
  fetchList();
  fetchStats();
};

const handleSearch = () => {
  page.value = 1;
  hasMore.value = true;
  fetchList();
};

const goForm = (id?: string) => {
  const url = id != null ? `/pages/replenisher/form?id=${id}` : '/pages/replenisher/form';
  uni.navigateTo({ url });
};

const goBack = () => {
  uni.navigateBack();
};

const showActions = (item: any) => {
  const isActive = item.status === 1;
  uni.showActionSheet({
    itemList: ['编辑信息', '绑定设备', '生成绑定码', isActive ? '禁用账号' : '启用账号', '删除补货员'],
    itemColor: '#1E293B',
    success: (res) => {
      switch (res.tapIndex) {
        case 0:
          goForm(item.id);
          break;
        case 1:
          handleBindDevices(item);
          break;
        case 2:
          handleGenCode(item);
          break;
        case 3:
          handleToggleStatus(item);
          break;
        case 4:
          handleDelete(item);
          break;
      }
    }
  });
};

const handleToggleStatus = (item: any) => {
  const newStatus = item.status === 1 ? 0 : 1;
  const actionText = newStatus === 0 ? '禁用' : '启用';
  uni.showModal({
    title: '确认操作',
    content: `确认${actionText}补货员「${item.name}」？`,
    success: async (res) => {
      if (!res.confirm) return;
      try {
        await updateReplenisherStatus(item.id, newStatus);
        uni.showToast({ title: `已${actionText}`, icon: 'success' });
        page.value = 1;
        fetchList();
        fetchStats();
      } catch (e) {
        uni.showToast({ title: '操作失败', icon: 'none' });
      }
    }
  });
};

const handleBindDevices = (item: any) => {
  uni.navigateTo({
    url: `/pages/replenisher/bind-device?id=${item.id}&name=${encodeURIComponent(item.name)}`
  });
};

const handleGenCode = async (item: any) => {
  uni.showLoading({ title: '生成中...', mask: true });
  try {
    const data = await generateBindingCode(item.id);
    uni.hideLoading();
    const code = data.bindingCode || '';
    uni.showModal({
      title: '微信绑定码',
      content: `${code}\n\n24小时内有效，点击确认复制`,
      success: (modalRes) => {
        if (modalRes.confirm) {
          uni.setClipboardData({
            data: code,
            success: () => {
              uni.showToast({ title: '绑定码已复制', icon: 'success' });
            }
          });
        }
      }
    });
  } catch (e) {
    uni.hideLoading();
    uni.showToast({ title: '生成失败', icon: 'none' });
  }
};

const handleDelete = (item: any) => {
  uni.showModal({
    title: '确认删除',
    content: `确认删除补货员「${item.name}」？\n删除后不可恢复。`,
    success: async (res) => {
      if (!res.confirm) return;
      try {
        await deleteReplenisher(item.id);
        uni.showToast({ title: '已删除', icon: 'success' });
        page.value = 1;
        fetchList();
        fetchStats();
      } catch (e) {
        uni.showToast({ title: '删除失败', icon: 'none' });
      }
    }
  });
};

onMounted(() => {
  fetchList();
  fetchStats();
});
</script>

<style lang="scss" scoped>
// ====== Page ======
.page {
  height: 100vh;
  background: $bg-color-page;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

// ====== Search ======
.search-bar {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 20rpx 24rpx;
  background: $bg-color-card;
  flex-shrink: 0;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background: $bg-color-page;
  border-radius: 40rpx;
  padding: 14rpx 24rpx;
  height: 68rpx;
}

.search-icon {
  position: relative;
  width: 30rpx;
  height: 30rpx;
  margin-right: 14rpx;
  flex-shrink: 0;

  .si-ring {
    width: 22rpx; height: 22rpx;
    border: 3rpx solid $text-color-muted;
    border-radius: 50%;
    position: absolute; top: 0; left: 0;
  }
  .si-stem {
    width: 9rpx; height: 3rpx;
    background: $text-color-muted;
    border-radius: 2rpx;
    position: absolute; bottom: 3rpx; right: 2rpx;
    transform: rotate(45deg);
  }
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: $text-color-primary;
}

.search-ph {
  color: $text-color-muted;
  font-size: 26rpx;
}

.search-btn {
  background: $primary-color;
  border-radius: 36rpx;
  padding: 14rpx 32rpx;
  flex-shrink: 0;
  transition: opacity 0.15s ease;
  &:active { opacity: 0.8; }

  .search-btn-text {
    font-size: 28rpx;
    color: $text-color-primary;
    font-weight: 500;
  }
}

// ====== Stats ======
.stats {
  display: flex;
  align-items: center;
  padding: 20rpx 32rpx;
  background: $bg-color-card;
  border-bottom: 1rpx solid $border-color-light;
  flex-shrink: 0;
}

.stat-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4rpx;
}

.stat-num {
  font-size: 32rpx;
  font-weight: 700;
  color: $text-color-primary;
  &.active { color: $success-color; }
  &.disabled { color: $text-color-muted; }
}

.stat-label {
  font-size: 22rpx;
  color: $text-color-muted;
}

.stat-divider {
  width: 1rpx;
  height: 36rpx;
  background: $border-color-light;
}

// ====== List ======
.list-scroll {
  flex: 1;
  height: 0;
}

.card-set {
  padding: 20rpx 24rpx;
  display: flex;
  flex-direction: column;
  gap: 14rpx;
}

// ====== Card ======
.card {
  display: flex;
  align-items: center;
  background: $bg-color-card;
  border-radius: 20rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: opacity 0.15s ease;
  gap: 18rpx;

  &:active { opacity: 0.7; }
}

.card-avatar {
  width: 72rpx;
  height: 72rpx;
  border-radius: 50%;
  background: $primary-color-bg;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;

  text {
    font-size: 32rpx;
    font-weight: 700;
    color: $primary-color-dark;
  }

  &.off {
    background: $bg-color-page;
    text { color: $text-color-placeholder; }
  }
}

.card-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.info-top {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.info-name {
  font-size: 30rpx;
  font-weight: 600;
  color: $text-color-primary;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.info-status {
  display: flex;
  align-items: center;
  gap: 6rpx;
  flex-shrink: 0;

  text { font-size: 22rpx; font-weight: 500; }

  &.on text { color: $success-color; }
  &.off text { color: $text-color-muted; }
}

.info-dot {
  width: 10rpx; height: 10rpx; border-radius: 50%;
  &.on { background: $success-color; }
  &.off { background: $text-color-placeholder; }
}

.info-sub {
  display: flex;
  align-items: center;
  gap: 6rpx;
}

.sub-phone {
  font-size: 24rpx;
  color: $text-color-secondary;
}

.sub-sep {
  font-size: 22rpx;
  color: $border-color;
}

.sub-id {
  font-size: 24rpx;
  color: $text-color-muted;
}

.info-meta {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4rpx;
}

.meta-val {
  font-size: 24rpx;
  font-weight: 600;
  color: $accent-color;
}

.meta-label {
  font-size: 22rpx;
  color: $text-color-muted;
}

.card-arrow {
  width: 36rpx;
  height: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;

  .arr-inner {
    width: 14rpx; height: 14rpx;
    border-top: 2rpx solid $text-color-placeholder;
    border-right: 2rpx solid $text-color-placeholder;
    transform: rotate(45deg);
  }
}

// ====== Load more ======
.load-tip {
  display: flex;
  justify-content: center;
  padding: 36rpx 0 20rpx;
}

.dot-row {
  display: flex;
  gap: 8rpx;
}

.pulse-dot {
  width: 9rpx; height: 9rpx;
  background: $text-color-placeholder;
  border-radius: 50%;
  animation: pulse 1.2s ease-in-out infinite;
  &:nth-child(2) { animation-delay: 0.2s; }
  &:nth-child(3) { animation-delay: 0.4s; }
}

@keyframes pulse {
  0%, 80%, 100% { transform: scale(0.5); opacity: 0.4; }
  40% { transform: scale(1); opacity: 1; }
}

// ====== End ======
.end-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
  padding: 36rpx 0 20rpx;
}
.end-line { width: 44rpx; height: 1rpx; background: $border-color; }
.end-text { font-size: 24rpx; color: $text-color-muted; }

// ====== Empty ======
.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0 60rpx;
  gap: 20rpx;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: $bg-color-secondary;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-person {
  position: relative;
  width: 40rpx;
  height: 48rpx;
  .ep-head {
    position: absolute; top: 0; left: 50%;
    transform: translateX(-50%);
    width: 18rpx; height: 18rpx;
    background: $text-color-placeholder;
    border-radius: 50%;
  }
  .ep-body {
    position: absolute; bottom: 0; left: 50%;
    transform: translateX(-50%);
    width: 34rpx; height: 20rpx;
    background: $text-color-placeholder;
    border-radius: 17rpx 17rpx 4rpx 4rpx;
  }
}

.empty-title { font-size: 28rpx; color: $text-color-secondary; font-weight: 500; }
.empty-desc { font-size: 24rpx; color: $text-color-muted; }

// ====== FAB ======
.fab {
  position: fixed;
  right: 40rpx;
  bottom: 240rpx;
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
  background: $primary-color;
  box-shadow: 0 8rpx 24rpx rgba(255, 193, 7, 0.35);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  transition: opacity 0.15s ease;

  &:active { opacity: 0.8; }

  .fab-text {
    font-size: 48rpx;
    color: $text-color-primary;
    font-weight: 300;
    line-height: 1;
    margin-top: -4rpx;
  }
}
</style>
