<template>
  <view class="app-container pb-24">
    <TopBar title="客户管理" show-back>
      <template #right>
        <view class="px-2 py-1 flex items-center" @click="goToAdd">
          <text class="uni-icons uniui-plusempty text-primary text-xl"></text>
          <text class="text-primary text-sm ml-1">新增</text>
        </view>
      </template>
    </TopBar>

    <!-- 搜索栏 -->
    <view class="bg-white px-4 py-3 sticky top-0 z-40">
      <view class="flex items-center bg-gray-100 rounded-2xl px-4 py-2">
        <text class="uni-icons uniui-search text-gray-400 mr-2 text-base"></text>
        <input
          class="flex-1 bg-transparent text-sm text-gray-700"
          placeholder="搜索客户名称/联系人/电话"
          v-model="searchKeyword"
          confirm-type="search"
          @confirm="onSearch"
        />
      </view>
    </view>

    <!-- 状态筛选 -->
    <uni-segmented-control
      :current="currentFilterIndex"
      :values="filterLabels"
      style-type="text"
      active-color="#4f8ef7"
      @clickItem="onFilterChange"
    />

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

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

      <uni-list v-else border>
        <uni-swipe-action
          v-for="customer in filteredCustomers"
          :key="customer.id"
          :actions="swipeActions"
          @click="onSwipeAction(customer.id, $event)"
        >
          <uni-list-item
            :title="customer.customerName"
            :note="buildNote(customer)"
            show-arrow
            @click="goToDetail(customer.id)"
          >
            <template #header>
              <view class="w-10 h-10 bg-blue-50 rounded-xl flex items-center justify-center mr-3">
                <text class="uni-icons uniui-person-filled text-blue-500 text-lg"></text>
              </view>
            </template>
            <template #footer>
              <view
                class="px-2 py-1 rounded text-xs"
                :style="{ backgroundColor: statusBg(customer.status), color: statusColor(customer.status) }"
              >
                {{ statusText(customer.status) }}
              </view>
            </template>
          </uni-list-item>
        </uni-swipe-action>
      </uni-list>
    </view>

    <!-- 加载更多 -->
    <view v-if="filteredCustomers.length > 0" class="px-4 mt-4 mb-4">
      <view v-if="customerStore.hasMore" class="text-center py-4">
        <text class="text-sm text-blue-500 font-medium" @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>
</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 UniList from '@/components/uni-list/uni-list.vue'
import UniListItem from '@/components/uni-list/uni-list-item.vue'
import UniSwipeAction from '@/components/uni-swipe-action/uni-swipe-action.vue'
import UniSegmentedControl from '@/components/uni-segmented-control/uni-segmented-control.vue'

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

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

const swipeActions = [
  { text: '编辑', color: '#4f8ef7', 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 buildNote(customer: Customer) {
  const parts = [customer.contactName, customer.phone].filter(Boolean)
  return parts.length ? parts.join(' · ') : (customer.detailAddress || '暂无联系人信息')
}

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>
