<template>
  <view class="page">
    <!-- 导航栏 -->
    <NavBar title="客户管理" />

    <!-- 筛选栏 -->
    <view class="filter-header">
      <view class="filter-tabs">
        <view
          class="filter-tab"
          :class="{ active: currentStatus === -1 }"
          @click="changeStatus(-1)"
        >
          <text>全部</text>
        </view>
        <view
          class="filter-tab"
          :class="{ active: currentStatus === 1 }"
          @click="changeStatus(1)"
        >
          <text>正常</text>
        </view>
        <view
          class="filter-tab"
          :class="{ active: currentStatus === 0 }"
          @click="changeStatus(0)"
        >
          <text>禁用</text>
        </view>
      </view>
      <view class="search-btn" @click="showSearch = true">
        <view class="search-icon"></view>
      </view>
    </view>

    <!-- 客户列表 -->
    <scroll-view
      class="customer-scroll"
      scroll-y
      @scrolltolower="loadMore"
    >
      <view class="customer-list">
        <view
          class="customer-card"
          v-for="customer in customerList"
          :key="customer.id"
          @click="goDetail(customer.id)"
        >
          <view class="card-avatar">
            <text class="avatar-text">{{ getAvatarText(customer.nickname) }}</text>
          </view>
          <view class="card-content">
            <view class="card-row-main">
              <text class="customer-name">{{ customer.nickname || '未命名用户' }}</text>
              <view class="status-tag" :class="getStatusClass(customer.status)">
                <text>{{ getStatusText(customer.status) }}</text>
              </view>
            </view>
            <view class="card-row-info">
              <text class="info-text">{{ formatPhone(customer.phone) }}</text>
              <text class="info-divider">·</text>
              <text class="info-text">信用分 {{ customer.creditScore || 0 }}</text>
            </view>
          </view>
          <view class="card-arrow"></view>
        </view>
      </view>

      <view class="loading-more" v-if="loading">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>

      <view class="no-more" v-if="!hasMore && customerList.length > 0">
        <text>— 没有更多了 —</text>
      </view>

      <view class="empty-state" v-if="!loading && customerList.length === 0">
        <view class="empty-icon">
          <view class="empty-icon-inner"></view>
        </view>
        <text class="empty-text">暂无客户数据</text>
      </view>
    </scroll-view>

    <!-- 搜索弹窗 -->
    <view class="search-modal" v-if="showSearch" @click="showSearch = false">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">搜索客户</text>
        </view>
        <view class="modal-body">
          <input
            class="search-input"
            v-model="searchKeyword"
            placeholder="请输入手机号或昵称"
            placeholder-class="input-placeholder"
            @confirm="doSearch"
          />
        </view>
        <view class="modal-footer">
          <button class="btn-cancel" @click="showSearch = false">取消</button>
          <button class="btn-confirm" @click="doSearch">搜索</button>
        </view>
      </view>
    </view>

    <!-- 自定义TabBar -->
    <CustomTabBar />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { logger } from '@/utils/logger';
import NavBar from '@/components/NavBar.vue';
import CustomTabBar from '@/components/CustomTabBar.vue';
import { getCustomerList } from '@/api/customer';
import { UserStatus, UserStatusText } from '@/utils/constants';

const customerList = ref<any[]>([]);
const currentStatus = ref(-1);
const searchKeyword = ref('');
const showSearch = ref(false);
const loading = ref(false);
const hasMore = ref(true);
const page = ref(1);
const pageSize = 10;

const getStatusText = (status: number) => UserStatusText[status] || '未知';

const getStatusClass = (status: number) => {
  return status === UserStatus.ENABLED ? 'enabled' : 'disabled';
};

const getAvatarText = (nickname: string) => {
  if (!nickname) return '?';
  return nickname.charAt(0).toUpperCase();
};

const formatPhone = (phone: string) => {
  if (!phone) return '未绑定手机号';
  if (phone.length === 11) {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  }
  return phone;
};

const changeStatus = (status: number) => {
  currentStatus.value = status;
  page.value = 1;
  hasMore.value = true;
  loadCustomers();
};

const loadCustomers = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: page.value,
      pageSize
    };
    if (currentStatus.value !== -1) {
      params.status = currentStatus.value;
    }
    if (searchKeyword.value) {
      if (/^\d+$/.test(searchKeyword.value)) {
        params.phone = searchKeyword.value;
      } else {
        params.nickname = searchKeyword.value;
      }
    }

    const res = await getCustomerList(params);

    if (page.value === 1) {
      customerList.value = res.list || [];
    } else {
      customerList.value = [...customerList.value, ...(res.list || [])];
    }

    hasMore.value = customerList.value.length < (res.total || 0);
  } catch (error) {
    logger.warn('加载客户列表失败', error);
  } finally {
    loading.value = false;
  }
};

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

const doSearch = () => {
  showSearch.value = false;
  page.value = 1;
  hasMore.value = true;
  loadCustomers();
};

const goDetail = (customerId: number) => {
  uni.navigateTo({ url: `/pages/customer/detail?id=${customerId}` });
};

onMounted(() => {
  loadCustomers();
});
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: $bg-color-page;
  display: flex;
  flex-direction: column;
  padding-bottom: 200rpx;
}

/* 筛选栏 */
.filter-header {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  gap: 12rpx;
  background: $bg-color-card;
  border-bottom: 1rpx solid $border-color;
}

.filter-tabs {
  flex: 1;
  display: flex;
  gap: 10rpx;

  .filter-tab {
    padding: 14rpx 24rpx;
    background: $bg-color-page;
    border: 2rpx solid $border-color;
    border-radius: 20rpx;
    font-size: 26rpx;
    color: $text-color-tertiary;
    transition: all 0.15s;

    &.active {
      background: $success-color-bg;
      border-color: $primary-color;
      color: $primary-color;
    }
  }
}

.search-btn {
  width: 72rpx;
  height: 72rpx;
  background: $success-color-bg;
  border: 2rpx solid $primary-color;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  .search-icon {
    width: 28rpx;
    height: 28rpx;
    border: 3rpx solid $primary-color;
    border-radius: 50%;
    position: relative;

    &::after {
      content: '';
      position: absolute;
      bottom: -6rpx;
      right: -6rpx;
      width: 10rpx;
      height: 3rpx;
      background: $primary-color;
      transform: rotate(45deg);
    }
  }
}

/* 客户列表 */
.customer-scroll {
  flex: 1;
  height: 0;
}

.customer-list {
  padding: 16rpx 24rpx;
}

.customer-card {
  background: $bg-color-card;
  border: 1rpx solid $border-color;
  border-radius: 12rpx;
  margin-bottom: 10rpx;
  padding: 14rpx 16rpx;
  display: flex;
  align-items: center;
  transition: transform 0.15s;

  &:active {
    transform: scale(0.98);
  }
}

.card-avatar {
  width: 80rpx;
  height: 80rpx;
  background: $success-color-bg;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
  flex-shrink: 0;

  .avatar-text {
    font-size: 32rpx;
    font-weight: 600;
    color: $primary-color;
  }
}

.card-content {
  flex: 1;
  min-width: 0;
}

.card-row-main {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;

  .customer-name {
    font-size: 28rpx;
    font-weight: 600;
    color: $text-color-primary;
    margin-right: 12rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.status-tag {
  padding: 2rpx 10rpx;
  border-radius: 4rpx;
  font-size: 20rpx;
  font-weight: 500;
  flex-shrink: 0;

  &.enabled {
    background: $success-color-bg;
    color: $primary-color;
  }

  &.disabled {
    background: $error-color-bg;
    color: $error-color;
  }
}

.card-row-info {
  display: flex;
  align-items: center;

  .info-text {
    font-size: 24rpx;
    color: $text-color-tertiary;
  }

  .info-divider {
    margin: 0 8rpx;
    color: $text-color-placeholder;
    font-size: 24rpx;
  }
}

.card-arrow {
  width: 12rpx;
  height: 12rpx;
  border-top: 3rpx solid $text-color-placeholder;
  border-right: 3rpx solid $text-color-placeholder;
  transform: rotate(45deg);
  margin-left: 12rpx;
  flex-shrink: 0;
}

/* 加载状态 */
.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  padding: 32rpx;
  color: $text-color-muted;
  font-size: 24rpx;

  .loading-spinner {
    width: 32rpx;
    height: 32rpx;
    border: 3rpx solid $border-color;
    border-top-color: $primary-color;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.no-more {
  text-align: center;
  padding: 32rpx;
  font-size: 24rpx;
  color: $text-color-placeholder;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;

  .empty-icon {
    width: 120rpx;
    height: 120rpx;
    background: $bg-color-secondary;
    border-radius: 24rpx;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .empty-icon-inner {
      width: 48rpx;
      height: 48rpx;
      border: 4rpx solid $text-color-placeholder;
      border-radius: 50%;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 20rpx;
        height: 20rpx;
        background: $text-color-placeholder;
        border-radius: 50%;
      }
    }
  }

  .empty-text {
    font-size: 28rpx;
    color: $text-color-muted;
  }
}

/* 搜索弹窗 */
.search-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 48rpx;
}

.modal-content {
  width: 100%;
  background: $bg-color-card;
  border-radius: 20rpx;
  overflow: hidden;

  .modal-header {
    padding: 24rpx;
    border-bottom: 1rpx solid $bg-color-secondary;

    .modal-title {
      font-size: 32rpx;
      font-weight: 600;
      color: $text-color-primary;
    }
  }

  .modal-body {
    padding: 24rpx;

    .search-input {
      width: 100%;
      height: 88rpx;
      background: $bg-color-page;
      border: 2rpx solid $border-color;
      border-radius: 12rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
      color: $text-color-primary;
      box-sizing: border-box;
    }
  }

  .modal-footer {
    display: flex;
    padding: 16rpx 24rpx 24rpx;
    gap: 12rpx;

    button {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 12rpx;
      font-size: 28rpx;
      font-weight: 500;
      border: none;
      padding: 0;

      &::after {
        border: none;
      }
    }

    .btn-cancel {
      background: $bg-color-page;
      color: $text-color-tertiary;
    }

    .btn-confirm {
      background: $primary-color;
      color: #fff;
    }
  }
}

.input-placeholder {
  color: $text-color-placeholder;
}
</style>
