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

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

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

    <!-- 加载更多 -->
    <view v-if="contractStore.contracts.length > 0" class="px-4 mt-4 mb-4">
      <view v-if="contractStore.hasMore" class="text-center py-4">
        <text class="text-sm text-blue-500 font-medium" @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>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { onPullDownRefresh } from '@dcloudio/uni-app'
import { useContractStore } from '@/stores/contract'
import type { Contract, 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 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 contractStore = useContractStore()
const searchKeyword = ref('')
const currentFilterIndex = ref(0)

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

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

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

function buildNote(contract: Contract) {
  const amount = formatMoney(contract.contractAmount)
  const method = getPaymentMethodText(contract.paymentMethod)
  return [amount, method, contract.signDate].filter(Boolean).join(' · ')
}

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>
