<template>
  <view class="app-container list-page pb-24">
    <TopBar title="客户管理" show-back />

    <!-- 工具栏：搜索 + 新增 -->
    <view class="toolbar px-4 py-3 sticky top-0 z-40 flex items-center gap-2">
      <view class="search-box flex-1 min-w-0 flex items-center rounded-2xl px-4 py-2" :class="{ 'search-focus': focusedSearch }">
        <text class="uni-icons uniui-search search-icon mr-2 text-base"></text>
        <input
          class="flex-1 bg-transparent text-sm text-gray-800"
          placeholder="搜索客户名称/联系人/电话"
          placeholder-class="search-ph"
          v-model="searchKeyword"
          confirm-type="search"
          @focus="focusedSearch = true"
          @blur="focusedSearch = false"
          @confirm="onSearch"
        />
      </view>
      <view
        class="add-btn w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0"
        hover-class="add-btn-hover"
        :hover-start-time="0"
        :hover-stay-time="120"
        @click="goToAdd"
      >
        <text class="uni-icons uniui-plusempty text-white text-xl"></text>
      </view>
    </view>

    <!-- 状态筛选 -->
    <scroll-view scroll-x class="filter-bar" :show-scrollbar="false" enhanced>
      <view class="flex items-center gap-2 px-4 py-3">
        <view
          v-for="(t, i) in filterTypes"
          :key="t.value"
          class="filter-tab flex-shrink-0 rounded-full px-4 py-1.5 text-sm border"
          :class="i === currentFilterIndex ? 'filter-tab--active' : 'filter-tab--normal'"
          @click="onFilterChange(i)"
        >
          {{ t.label }}
        </view>
      </view>
    </scroll-view>

    <!-- 列表 -->
    <view class="px-4 mt-3">
      <view v-if="customerStore.loading" class="py-16 text-center">
        <text class="loading-text">加载中...</text>
      </view>

      <view v-else-if="filteredCustomers.length === 0">
        <EmptyState icon="uniui-personadd-filled" text="暂无客户" />
      </view>

      <view v-else class="gap-y-3">
        <uni-swipe-action
          v-for="customer in filteredCustomers"
          :key="customer.id"
          :actions="swipeActions"
          @click="onSwipeAction(customer.id, $event)"
        >
          <view class="data-card" @click="goToDetail(customer.id)">
            <!-- 名称 + 状态 -->
            <view class="flex items-start justify-between gap-2">
              <text class="card-title truncate">{{ customer.customerName }}</text>
              <view
                class="status-pill flex-shrink-0 px-2.5 py-0.5 rounded-full text-xs"
                :style="{ backgroundColor: statusBg(customer.status), color: statusColor(customer.status) }"
              >
                {{ statusText(customer.status) }}
              </view>
            </view>
            <!-- 联系人 + 电话 -->
            <view v-if="customer.contactName || customer.phone" class="mt-1.5 flex items-center flex-wrap">
              <view v-if="customer.contactName" class="info-item flex items-center mr-4">
                <text class="uni-icons uniui-person-filled info-icon text-xs mr-1"></text>
                <text class="info-text text-xs truncate">{{ customer.contactName }}</text>
              </view>
              <view v-if="customer.phone" class="info-item flex items-center">
                <text class="uni-icons uniui-phone-filled info-icon text-xs mr-1"></text>
                <text class="info-text text-xs">{{ customer.phone }}</text>
              </view>
            </view>
            <view v-else class="mt-1.5">
              <text class="info-text text-xs">暂无联系人信息</text>
            </view>
            <!-- 地址 -->
            <view v-if="fullAddress(customer)" class="card-foot mt-2.5 pt-2 flex items-center">
              <text class="uni-icons uniui-location-filled foot-icon text-xs mr-1 flex-shrink-0"></text>
              <text class="foot-text text-xs truncate flex-1">{{ fullAddress(customer) }}</text>
            </view>
          </view>
        </uni-swipe-action>
      </view>

      <!-- 加载更多 -->
      <view v-if="filteredCustomers.length > 0" class="mt-2 mb-4">
        <view v-if="customerStore.hasMore" class="text-center py-4">
          <text class="load-more" @click="loadMore">
            {{ customerStore.loadingMore ? '加载中...' : '加载更多' }}
          </text>
        </view>
        <view v-else class="text-center py-4">
          <text class="text-xs text-gray-400">已经到底了</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { onPullDownRefresh } from '@dcloudio/uni-app'
import { useCustomerStore } from '@/stores/customer'
import type { Customer } from '@/types'
import {
  getCustomerStatusText,
  getCustomerStatusColor,
  getCustomerStatusBgColor
} from '@/utils'
import TopBar from '@/components/common/TopBar.vue'
import EmptyState from '@/components/common/EmptyState.vue'
import UniSwipeAction from '@/components/uni-swipe-action/uni-swipe-action.vue'

const customerStore = useCustomerStore()
const searchKeyword = ref('')
const currentFilterIndex = ref(0)
const focusedSearch = ref(false)

const filterTypes = [
  { value: 'all', label: '全部' },
  { value: '1', label: '合作中' },
  { value: '2', label: '潜在客户' },
  { value: '0', label: '已停用' }
]

const swipeActions = [
  { text: '编辑', color: '#368f6f', key: 'edit' },
  { text: '删除', color: '#ff3b30', key: 'delete' }
]

const statusText = getCustomerStatusText
const statusColor = getCustomerStatusColor
const statusBg = getCustomerStatusBgColor

const filteredCustomers = computed(() => {
  const filterValue = filterTypes[currentFilterIndex.value].value
  if (filterValue === 'all') return customerStore.customers
  return customerStore.customers.filter(c => String(c.status) === filterValue)
})

function fullAddress(customer: Customer) {
  return [customer.province, customer.city, customer.district, customer.street, customer.detailAddress]
    .filter(Boolean)
    .join('')
}

let searchTimer: ReturnType<typeof setTimeout> | null = null
function onSearch() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    customerStore.setKeyword(searchKeyword.value.trim())
    customerStore.fetchCustomers(true)
  }, 300)
}

function onFilterChange(index: number) {
  currentFilterIndex.value = index
}

function goToDetail(id: number | string) {
  customerStore.setCurrentCustomer(id)
  uni.navigateTo({ url: `/subPackages/pages-customer/customerDetail?id=${id}` })
}

function goToAdd() {
  uni.navigateTo({ url: '/subPackages/pages-customer/customerForm' })
}

function onSwipeAction(id: number | string, action: { key?: string }) {
  if (action.key === 'edit') {
    uni.navigateTo({ url: `/subPackages/pages-customer/customerForm?id=${id}` })
  } else if (action.key === 'delete') {
    uni.showModal({
      title: '确认删除',
      content: '删除后无法恢复，是否继续？',
      success: async (res) => {
        if (res.confirm) {
          try {
            await customerStore.removeCustomer(id)
            uni.showToast({ title: '已删除', icon: 'success' })
          } catch (e) {
            uni.showToast({ title: '删除失败', icon: 'none' })
          }
        }
      }
    })
  }
}

function loadMore() {
  customerStore.loadMore()
}

async function refreshData() {
  await customerStore.fetchCustomers(true)
  uni.stopPullDownRefresh()
}

onMounted(() => {
  customerStore.fetchCustomers(true)
})

onUnmounted(() => {
  if (searchTimer) clearTimeout(searchTimer)
})

onPullDownRefresh(() => {
  refreshData()
})
</script>

<style scoped>
.list-page {
  background-color: #f6fbf9;
}

.toolbar {
  background-color: rgba(246, 251, 249, 0.88);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border-bottom: 1px solid rgba(164, 216, 152, 0.28);
}

.search-box {
  background-color: #ffffff;
  border: 1px solid #e5e7eb;
  transition: border-color 0.15s ease, box-shadow 0.15s ease, background-color 0.15s ease;
}
.search-focus {
  background-color: #ffffff;
  border-color: #368f6f;
  box-shadow: 0 0 0 3px rgba(164, 216, 152, 0.30);
}
.search-icon {
  color: #9ca3af;
}
.search-ph {
  color: #9ca3af;
}

.add-btn {
  background: linear-gradient(135deg, #368f6f 0%, #5ab8d0 100%);
  box-shadow: 0 8px 18px -8px rgba(54, 143, 111, 0.55);
}
.add-btn-hover {
  opacity: 0.92;
  transform: scale(0.94);
}

.filter-bar {
  background-color: rgba(246, 251, 249, 0.88);
  border-bottom: 1px solid rgba(164, 216, 152, 0.20);
  white-space: nowrap;
}
.filter-tab {
  transition: all 0.15s ease;
}
.filter-tab--normal {
  background-color: #ffffff;
  border-color: #e5e7eb;
  color: #4b5563;
}
.filter-tab--active {
  background: linear-gradient(135deg, #368f6f 0%, #5ab8d0 100%);
  border-color: transparent;
  color: #ffffff;
  box-shadow: 0 6px 14px -8px rgba(54, 143, 111, 0.6);
}

.data-card {
  background-color: #ffffff;
  border-radius: 20px;
  padding: 14px 16px;
  box-shadow: 0 14px 34px -18px rgba(54, 143, 111, 0.35);
  border: 1px solid rgba(164, 216, 152, 0.28);
}
.data-card:active {
  transform: scale(0.99);
  background-color: #fbfefb;
}
.card-title {
  font-size: 15px;
  font-weight: 600;
  color: #1f2937;
}
.status-pill {
  font-weight: 500;
}

.info-icon {
  color: #5ab8d0;
}
.info-text {
  color: #6b7280;
}

/* 底部地址行 */
.card-foot {
  border-top: 1px dashed rgba(164, 216, 152, 0.45);
}
.foot-icon {
  color: #368f6f;
}
.foot-text {
  color: #9ca3af;
}

.loading-text {
  color: #6b7280;
}
.load-more {
  font-size: 14px;
  font-weight: 500;
  color: #368f6f;
}
</style>
