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

      <view v-else-if="contractStore.contracts.length === 0">
        <EmptyState icon="uniui-file-text-filled" text="暂无合同" />
      </view>

      <view v-else class="gap-y-3">
        <uni-swipe-action
          v-for="contract in contractStore.contracts"
          :key="contract.id"
          :actions="swipeActions"
          @click="onSwipeAction(contract.id, $event)"
        >
          <view class="data-card" @click="goToDetail(contract.id)">
            <!-- 头部：合同号 + 状态 -->
            <view class="flex items-start justify-between">
              <view class="min-w-0">
                <text class="card-title block truncate">{{ contract.contractNo }}</text>
                <text class="card-sub block mt-0.5">合同编号</text>
              </view>
              <view
                class="status-pill flex-shrink-0 px-2.5 py-0.5 rounded-full text-xs ml-2"
                :style="{ backgroundColor: statusBg(contract.status), color: statusColor(contract.status) }"
              >
                {{ statusText(contract.status) }}
              </view>
            </view>

            <!-- 金额高亮条 -->
            <view class="amount-row mt-3 rounded-2xl px-3.5 py-2.5 flex items-center justify-between">
              <view class="flex items-center">
                <text class="uni-icons uniui-wallet-filled amount-icon text-sm mr-2"></text>
                <text class="amount-label text-xs">合同金额</text>
              </view>
              <text class="amount-value">{{ formatMoney(contract.contractAmount) }}</text>
            </view>

            <!-- 底部信息行 -->
            <view class="card-foot mt-3 pt-2.5 flex items-center justify-between">
              <view class="foot-item flex items-center min-w-0 mr-3">
                <text class="uni-icons uniui-wallet-filled foot-icon text-xs mr-1.5 flex-shrink-0"></text>
                <text class="foot-text text-xs truncate">{{ getPaymentMethodText(contract.paymentMethod) || '未约定' }}</text>
              </view>
              <view class="foot-item flex items-center flex-shrink-0">
                <text class="uni-icons uniui-calendar foot-icon text-xs mr-1.5"></text>
                <text class="foot-text text-xs">{{ contract.signDate || '未签约' }}</text>
              </view>
            </view>
          </view>
        </uni-swipe-action>
      </view>

      <!-- 加载更多 -->
      <view v-if="contractStore.contracts.length > 0" class="mt-2 mb-4">
        <view v-if="contractStore.hasMore" class="text-center py-4">
          <text class="load-more" @click="loadMore">
            {{ contractStore.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, onMounted, onUnmounted } from 'vue'
import { onPullDownRefresh } from '@dcloudio/uni-app'
import { useContractStore } from '@/stores/contract'
import type { ContractStatus } from '@/types'
import {
  formatMoney,
  getPaymentMethodText,
  getContractStatusText,
  getContractStatusColor,
  getContractStatusBgColor
} 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 contractStore = useContractStore()
const searchKeyword = ref('')
const currentFilterIndex = ref(0)
const focusedSearch = ref(false)

const filterTypes: { value: ContractStatus | ''; label: string }[] = [
  { value: '', label: '全部' },
  { value: 'draft', label: '草稿' },
  { value: 'pending', label: '待生效' },
  { value: 'active', label: '生效中' },
  { value: 'expired', label: '已过期' },
  { value: 'terminated', label: '已终止' }
]

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

const statusText = getContractStatusText
const statusColor = getContractStatusColor
const statusBg = getContractStatusBgColor

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

function onFilterChange(index: number) {
  currentFilterIndex.value = index
  contractStore.setStatus(filterTypes[index].value)
  contractStore.fetchContracts(true)
}

function goToDetail(id: number | string) {
  contractStore.setCurrentContract(id)
  uni.navigateTo({ url: `/subPackages/pages-contract/contractDetail?id=${id}` })
}

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

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

function loadMore() {
  contractStore.loadMore()
}

async function refreshData() {
  await contractStore.fetchContracts(true)
  uni.stopPullDownRefresh()
}

onMounted(() => {
  contractStore.fetchContracts(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;
}
.card-sub {
  font-size: 11px;
  color: #b6c9be;
}
.status-pill {
  font-weight: 500;
}

/* 金额高亮条 */
.amount-row {
  background: linear-gradient(135deg, rgba(164, 216, 152, 0.22) 0%, rgba(90, 184, 208, 0.16) 100%);
  border: 1px solid rgba(164, 216, 152, 0.30);
}
.amount-icon {
  color: #368f6f;
}
.amount-label {
  color: #6b8a7a;
  font-weight: 500;
}
.amount-value {
  font-size: 17px;
  font-weight: 700;
  color: #2f7a5e;
  letter-spacing: 0.3px;
}

/* 底部信息行 */
.card-foot {
  border-top: 1px dashed rgba(164, 216, 152, 0.45);
}
.foot-icon {
  color: #5ab8d0;
}
.foot-text {
  color: #6b7280;
}

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