<template>
  <view class="settlement-container">
    <!-- 筛选栏 -->
    <view class="filter-section">
      <view class="filter-row">
        <view class="filter-item">
          <text class="filter-label">站点</text>
          <picker mode="selector" :range="stationList" range-key="stationName" @change="handleStationChange">
            <view class="picker-value">
              <text :class="{ placeholder: !selectedStationName }">{{ selectedStationName || '全部站点' }}</text>
              <AppIcon name="chevron-down" :size="20" color="#999999" class="picker-arrow" />
            </view>
          </picker>
        </view>
        <view class="filter-item">
          <text class="filter-label">结算周期</text>
          <input type="text" placeholder="如 2026-05" v-model="settlementPeriod" @confirm="handleSearch" />
        </view>
      </view>
      <view class="filter-row">
        <view class="filter-segments">
          <view
            v-for="(option, index) in statusOptions"
            :key="index"
            class="segment-item"
            :class="{ active: activeStatus === option.value }"
            @click="handleStatusChange(option.value)">
            <text>{{ option.label }}</text>
          </view>
        </view>
      </view>
      <button class="search-btn" @click="handleSearch">查询</button>
    </view>

    <!-- 结算列表 -->
    <view class="settlement-list" v-if="list.length > 0">
      <view
        class="settlement-item"
        v-for="(item, index) in list"
        :key="index"
        @click="viewDetail(item)">
        <view class="item-header">
          <view class="item-left">
            <text class="item-station">{{ item.stationName || '-' }}</text>
            <text class="item-period">{{ item.settlementPeriod || '-' }}</text>
          </view>
          <text class="status-tag" :style="getStatusStyle(item.status)">{{ fmtDictName('Settlement.status', item.status) }}</text>
        </view>
        <view class="item-content">
          <view class="info-grid">
            <view class="info-item">
              <text class="info-label">期初余额</text>
              <text class="info-value">{{ formatAmount(item.openingPendingBalance) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">总充值</text>
              <text class="info-value">{{ formatAmount(item.totalRecharge) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">总退款</text>
              <text class="info-value">{{ formatAmount(item.totalRefund) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">跨店收入</text>
              <text class="info-value">{{ formatAmount(item.totalCrossIncome) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">跨店支出</text>
              <text class="info-value">{{ formatAmount(item.totalCrossExpend) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">平台费</text>
              <text class="info-value">{{ formatAmount(item.platformFee) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">提现手续费</text>
              <text class="info-value">{{ formatAmount(item.withdrawalFee) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">结算金额</text>
              <text class="info-value highlight">{{ formatAmount(item.settlementAmount) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">期末余额</text>
              <text class="info-value">{{ formatAmount(item.closingPendingBalance) }}</text>
            </view>
          </view>
          <view class="item-time">
            <text class="time-text">创建: {{ formatTime(item.createTime) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view class="load-more" v-if="list.length > 0">
      <text class="load-more-text" v-if="loadMoreStatus === 'more'">上拉加载更多</text>
      <text class="load-more-text" v-else-if="loadMoreStatus === 'loading'">正在加载...</text>
      <text class="load-more-text" v-else>没有更多数据了</text>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="list.length === 0 && !loading">
      <view class="empty-icon-wrapper">
        <AppIcon name="bar-chart" :size="80" color="#999999" />
      </view>
      <text class="empty-text">暂无结算记录</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading && list.length === 0">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 详情弹窗 -->
    <view class="detail-overlay" v-if="showDetail" @click="closeDetail">
      <view class="detail-card" @click.stop>
        <view class="detail-header">
          <text class="detail-title">结算详情</text>
          <view class="detail-close" @click="closeDetail">
            <AppIcon name="x" :size="32" color="#999999" />
          </view>
        </view>
        <view class="detail-content" v-if="detailItem">
          <view class="detail-row">
            <text class="d-label">站点名称</text>
            <text class="d-value">{{ detailItem.stationName || '-' }}</text>
          </view>
          <view class="detail-row">
            <text class="d-label">结算周期</text>
            <text class="d-value">{{ detailItem.settlementPeriod || '-' }}</text>
          </view>
          <view class="detail-row">
            <text class="d-label">期初余额</text>
            <text class="d-value amount">{{ formatAmount(detailItem.openingPendingBalance) }}</text>
          </view>
          <view class="detail-row">
            <text class="d-label">总充值</text>
            <text class="d-value">{{ formatAmount(detailItem.totalRecharge) }}</text>
          </view>
          <view class="detail-row">
            <text class="d-label">总退款</text>
            <text class="d-value">{{ formatAmount(detailItem.totalRefund) }}</text>
          </view>
          <view class="detail-row">
            <text class="d-label">跨店收入</text>
            <text class="d-value">{{ formatAmount(detailItem.totalCrossIncome) }}</text>
          </view>
          <view class="detail-row">
            <text class="d-label">跨店支出</text>
            <text class="d-value">{{ formatAmount(detailItem.totalCrossExpend) }}</text>
          </view>
          <view class="detail-row">
            <text class="d-label">平台费基数</text>
            <text class="d-value">{{ formatAmount(detailItem.platformFeeBase) }}</text>
          </view>
          <view class="detail-row">
            <text class="d-label">平台费</text>
            <text class="d-value">{{ formatAmount(detailItem.platformFee) }}</text>
          </view>
          <view class="detail-row highlight-row">
            <text class="d-label">结算金额</text>
            <text class="d-value settlement-amount">{{ formatAmount(detailItem.settlementAmount) }}</text>
          </view>
          <view class="detail-row">
            <text class="d-label">期末余额</text>
            <text class="d-value">{{ formatAmount(detailItem.closingPendingBalance) }}</text>
          </view>
          <view class="detail-row">
            <text class="d-label">状态</text>
            <text class="d-value" :style="getStatusStyle(detailItem.status)">{{ fmtDictName('Settlement.status', detailItem.status) }}</text>
          </view>
          <view class="detail-row" v-if="detailItem.remark">
            <text class="d-label">备注</text>
            <text class="d-value">{{ detailItem.remark }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { onReachBottom } from '@dcloudio/uni-app'
import { getSettlementRecords } from '../../api/finance.js'
import { getStationList } from '../../api/station.js'
import { formatTime, showToast, formatAmount, fmtDictName, getDictColor } from '../../utils/index.js'
import dictUtil, { loadDicts } from '../../utils/dict.js'

const list = ref([])
const loading = ref(true)
const page = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const loadMoreStatus = ref('more')
const activeStatus = ref('')
const settlementPeriod = ref('')
const stationList = ref([])
const selectedStationId = ref('')
const selectedStationName = ref('')
const showDetail = ref(false)
const detailItem = ref(null)

const statusOptions = computed(() => dictUtil.getDictFilterOptions('Settlement.status'))

const getStatusStyle = (status) => {
  const color = getDictColor('Settlement.status', status)
  if (color) return { color, backgroundColor: `${color}1A` }
  return {}
}

const loadStations = async () => {
  try {
    const res = await getStationList({ pageSize: 1024 })
    if (res && res.code === 200) {
      const data = res.data
      stationList.value = data.records || data.list || data || []
      stationList.value.unshift({ stationId: '', stationName: '全部站点' })
    }
  } catch (error) {
    showToast('加载站点列表失败')
  }
}

const handleStationChange = (e) => {
  const index = e.detail.value
  const selected = stationList.value[index]
  if (selected) {
    selectedStationId.value = selected.stationId || ''
    selectedStationName.value = selected.stationName || ''
  }
}

const loadData = async (isLoadMore = false) => {
  if (!isLoadMore) {
    page.value = 1
    list.value = []
    hasMore.value = true
    loadMoreStatus.value = 'more'
  } else {
    loadMoreStatus.value = 'loading'
  }

  loading.value = true
  try {
    const params = {
      pageNum: page.value,
      pageSize: pageSize.value
    }
    if (selectedStationId.value) params.stationId = selectedStationId.value
    if (settlementPeriod.value) params.settlementPeriod = settlementPeriod.value
    if (activeStatus.value !== '') params.status = activeStatus.value

    const res = await getSettlementRecords(params)
    if (res && res.code === 200) {
      const data = res.data
      const records = data.records || data.list || data
      const total = data.total || 0

      const totalPages = Math.ceil(total / pageSize.value)
      hasMore.value = page.value < totalPages
      loadMoreStatus.value = hasMore.value ? 'more' : 'noMore'

      if (isLoadMore) {
        list.value = [...list.value, ...records]
        page.value++
      } else {
        list.value = records
        page.value = 2
      }
    }
  } catch (error) {
    showToast('加载结算记录失败')
  } finally {
    loading.value = false
  }
}

const loadMore = () => {
  if (hasMore.value && !loading.value && loadMoreStatus.value !== 'loading') {
    loadData(true)
  }
}

onReachBottom(() => {
  loadMore()
})

const handleSearch = () => {
  loadData()
}

const handleStatusChange = (status) => {
  activeStatus.value = status
  loadData()
}

const viewDetail = (item) => {
  detailItem.value = item
  showDetail.value = true
}

const closeDetail = () => {
  showDetail.value = false
  detailItem.value = null
}

onMounted(async () => {
  await loadDicts()
  loadStations()
  loadData()
})
</script>

<style scoped>
.settlement-container {
  min-height: 100vh;
  background-color: #F5F7FA;
  padding-bottom: 60rpx;
}

.filter-section {
  background-color: #FFFFFF;
  padding: 24rpx 20rpx 20rpx;
  margin-bottom: 16rpx;
}
.filter-row {
  display: flex;
  gap: 16rpx;
  margin-bottom: 12rpx;
}
.filter-item {
  flex: 1;
}
.filter-label {
  font-size: 24rpx;
  color: #999999;
  margin-bottom: 8rpx;
  display: block;
}
.picker-value {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #F5F5F5;
  border-radius: 16rpx;
  padding: 14rpx 20rpx;
  font-size: 26rpx;
}
.picker-value .placeholder {
  color: #B0B0B0;
}
.picker-arrow {
  flex-shrink: 0;
}
.filter-item input {
  background-color: #F5F5F5;
  border-radius: 16rpx;
  padding: 14rpx 20rpx;
  font-size: 26rpx;
  height: 56rpx;
}
.filter-segments {
  display: flex;
  gap: 12rpx;
  flex-wrap: wrap;
}
.segment-item {
  padding: 8rpx 24rpx;
  background-color: #F5F5F5;
  border-radius: 100rpx;
  font-size: 24rpx;
  color: #666666;
}
.segment-item.active {
  background: #C6171E;
  color: #FFFFFF;
}
.search-btn {
  width: 100%;
  padding: 16rpx 0;
  background: #C6171E;
  color: #FFFFFF;
  border-radius: 16rpx;
  font-size: 28rpx;
  border: none;
}

.settlement-list {
  padding: 0 20rpx;
}
.settlement-item {
  background-color: #FFFFFF;
  border-radius: 24rpx;
  padding: 24rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06);
}
.settlement-item:active {
  transform: translateY(-4rpx);
  box-shadow: 0 2px 6px rgba(0,0,0,0.1), 0 2px 4px rgba(0,0,0,0.08);
}
.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #F0F0F0;
  margin-bottom: 16rpx;
}
.item-station {
  font-size: 30rpx;
  font-weight: 600;
  color: #1A1A1A;
  display: block;
}
.item-period {
  font-size: 24rpx;
  color: #999999;
  margin-top: 4rpx;
  display: block;
}
.status-tag {
  font-size: 22rpx;
  padding: 6rpx 24rpx;
  border-radius: 100rpx;
  font-weight: 500;
}
.info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12rpx;
}
.info-item {
  padding: 8rpx 0;
}
.info-label {
  font-size: 24rpx;
  color: #999999;
  display: block;
  margin-bottom: 4rpx;
}
.info-value {
  font-size: 26rpx;
  color: #1A1A1A;
  font-weight: 500;
}
.info-value.highlight {
  color: #C6171E;
  font-size: 28rpx;
}
.item-time {
  margin-top: 12rpx;
  padding-top: 12rpx;
  border-top: 1rpx solid #F0F0F0;
}
.time-text {
  font-size: 24rpx;
  color: #999999;
}

.load-more {
  display: flex;
  justify-content: center;
  padding: 24rpx 0;
}
.load-more-text {
  font-size: 24rpx;
  color: #999999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0;
}
.empty-text {
  font-size: 28rpx;
  color: #999999;
  margin-top: 20rpx;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0;
}
.loading-text {
  font-size: 28rpx;
  color: #999999;
  margin-top: 16rpx;
}

/* 详情弹窗 */
.detail-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 1000;
}
.detail-card {
  width: 100%;
  max-height: 80vh;
  background-color: #FFFFFF;
  border-radius: 32rpx 32rpx 0 0;
  padding: 30rpx;
  overflow-y: auto;
}
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}
.detail-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
}
.detail-close {
  padding: 10rpx;
}
.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #F5F5F5;
}
.detail-row.highlight-row {
  background-color: rgba(198, 23, 30, 0.04);
  padding: 16rpx 20rpx;
  border-radius: 16rpx;
  margin: 8rpx 0;
}
.d-label {
  font-size: 26rpx;
  color: #999999;
}
.d-value {
  font-size: 26rpx;
  color: #1A1A1A;
  font-weight: 500;
}
.d-value.amount {
  color: #C6171E;
}
.d-value.settlement-amount {
  color: #C6171E;
  font-size: 28rpx;
  font-weight: 700;
}
</style>
