<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"
        />
      </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="projectStore.loading" class="py-16 text-center">
        <text class="loading-text">加载中...</text>
      </view>

      <view v-else-if="filteredProjects.length === 0">
        <EmptyState icon="uniui-folder-add-filled" text="暂无项目" />
      </view>

      <view v-else class="gap-y-3">
        <uni-swipe-action
          v-for="project in filteredProjects"
          :key="project.projectId"
          :actions="swipeActions"
          @click="onSwipeAction(project.projectId, $event)"
        >
          <view class="data-card" @click="goToDetail(project.projectId)">
            <!-- 头部：项目名 + 合作类型 -->
            <view class="flex items-start justify-between mb-3">
              <text class="card-title flex-1 min-w-0 truncate mr-3">{{ project.projectName }}</text>
              <view class="type-pill px-2.5 py-0.5 rounded-full text-xs flex-shrink-0">
                {{ getCooperationTypeText(project.cooperationType) }}
              </view>
            </view>

            <!-- 信息行 -->
            <view class="space-y-2">
              <view class="info-row">
                <text class="uni-icons uniui-settings-filled info-icon text-xs mr-2 flex-shrink-0"></text>
                <text class="info-text text-xs truncate">{{ facilityText(project) }}</text>
              </view>
              <view class="info-row">
                <text class="uni-icons uniui-location-filled info-icon text-xs mr-2 flex-shrink-0"></text>
                <text class="info-text text-xs truncate">{{ addressText(project) }}</text>
              </view>
              <view class="info-row">
                <text class="uni-icons uniui-map-pin-ellipse info-icon text-xs mr-2 flex-shrink-0"></text>
                <text class="info-text text-xs">服务点数：<text class="text-primary font-medium">{{ servicePointCount(project) }}个</text></text>
              </view>
              <view class="info-row">
                <text class="uni-icons uniui-person-filled info-icon text-xs mr-2 flex-shrink-0"></text>
                <text class="info-text text-xs truncate">{{ contactText(project) }}</text>
              </view>
            </view>
          </view>
        </uni-swipe-action>
      </view>

      <!-- 加载更多 -->
      <view v-if="filteredProjects.length > 0" class="mt-2 mb-4">
        <view v-if="projectStore.hasMore" class="text-center py-4">
          <text class="load-more" @click="loadMore">
            {{ projectStore.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 } from 'vue'
import { onPullDownRefresh } from '@dcloudio/uni-app'
import { useProjectStore } from '../../stores/project'
import type { CooperationType, Project } from '../../types'
import { getCooperationTypeText, getFacilityTypeText, parseJsonArray } from '../../utils'
import EmptyState from '../../components/common/EmptyState.vue'
import TopBar from '../../components/common/TopBar.vue'
import UniSwipeAction from '../../components/uni-swipe-action/uni-swipe-action.vue'

const projectStore = useProjectStore()
const searchKeyword = ref('')
const currentFilterIndex = ref(0)
const focusedSearch = ref(false)

const filterTypes: { value: CooperationType | 'all'; label: string }[] = [
  { value: 'all', label: '全部' },
  { value: 'annual', label: '包年' },
  { value: 'single', label: '单次' },
  { value: 'quarter', label: '季度' },
  { value: 'monthly', label: '月付' }
]

const filteredProjects = computed(() => {
  let list = projectStore.projects
  const filterValue = filterTypes[currentFilterIndex.value].value

  if (filterValue !== 'all') {
    list = list.filter(p => p.cooperationType === filterValue)
  }

  if (searchKeyword.value) {
    const kw = searchKeyword.value.trim()
    list = list.filter(p =>
      (p.projectName || '').includes(kw) || (p.customerName || '').includes(kw)
    )
  }

  return list
})

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

function addressText(project: Project) {
  return (
    project.address ||
    [project.province, project.city, project.district, project.detailAddress].filter(Boolean).join('') ||
    '暂无地址'
  )
}

function facilityText(project: Project) {
  const list = parseJsonArray<string>(project.facilityTypes)
  if (list.length === 0) return '暂无设施类型'
  return list.map(t => getFacilityTypeText(t)).join('、')
}

function servicePointCount(project: Project) {
  return parseJsonArray(project.servicePoints).length
}

function maskPhone(phone?: string) {
  if (!phone) return ''
  if (phone.length === 11) {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
  }
  return phone
}

function contactText(project: Project) {
  const name = project.primaryContactName
  const phone = maskPhone(project.primaryContactPhone)
  if (name && phone) return `${name} · ${phone}`
  if (name) return name
  if (phone) return phone
  return '暂无联系人'
}

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

function onSwipeAction(projectId: number | string, action: { key?: string; text?: string }) {
  if (action.key === 'delete') {
    uni.showModal({
      title: '确认删除',
      content: '删除后无法恢复，是否继续？',
      success: (res) => {
        if (res.confirm) {
          projectStore.deleteProject(projectId)
          uni.showToast({ title: '已删除', icon: 'success' })
        }
      }
    })
  } else if (action.key === 'edit') {
    projectStore.setCurrentProject(projectId)
    uni.navigateTo({ url: `/subPackages/pages-common/addProject?mode=edit&id=${projectId}` })
  }
}

function goToDetail(projectId: number | string) {
  projectStore.setCurrentProject(projectId)
  uni.navigateTo({ url: `/subPackages/pages-common/projectDetail?id=${projectId}` })
}

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

async function refreshData() {
  await projectStore.fetchProjects(true)
  uni.stopPullDownRefresh()
}

function loadMore() {
  if (projectStore.loadingMore) return
  projectStore.loadMore()
}

onMounted(() => {
  projectStore.fetchProjects(true)
})

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;
}
.type-pill {
  background-color: rgba(164, 216, 152, 0.20);
  color: #368f6f;
  font-weight: 500;
}

.info-icon {
  color: #9ca3af;
}
.info-text {
  color: #6b7280;
}
.info-row {
  display: flex;
  align-items: center;
}
.text-primary {
  color: #368f6f;
}

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