<template>
  <view class="split-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>
          <picker mode="selector" :range="typeOptions" range-key="label" @change="handleTypeChange">
            <view class="picker-value">
              <text :class="{ placeholder: !activeTypeLabel }">{{ activeTypeLabel || '全部类型' }}</text>
              <AppIcon name="chevron-down" :size="20" color="#999999" class="picker-arrow" />
            </view>
          </picker>
        </view>
      </view>
      <view class="filter-row">
        <view class="filter-item full-width">
          <text class="filter-label">交易流水号</text>
          <input type="text" placeholder="输入流水号搜索" v-model="tradeNo" @confirm="handleSearch" />
        </view>
      </view>
      <button class="search-btn" @click="handleSearch">查询</button>
    </view>

    <!-- 分账列表 -->
    <scroll-view
      class="split-scroll"
      scroll-y
      @scrolltolower="loadMore"
      lower-threshold="80">
      <view class="split-list" v-if="list.length > 0">
        <view class="split-item" v-for="(item, index) in list" :key="index">
          <view class="item-header">
            <text class="item-type" :style="getTypeStyle(item.type)">{{ fmtDictName('SplitRecord.type', item.type) }}</text>
            <text class="item-amount">{{ formatAmount(item.amount) }}</text>
          </view>
          <view class="item-content">
            <view class="info-row">
              <text class="info-label">入账站点</text>
              <text class="info-value">{{ item.toStationName || '-' }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">出账站点</text>
              <text class="info-value">{{ item.fromStationName || '-' }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">分账交易流水号</text>
              <view class="info-value-row">
                <text class="info-value trade-no">{{ item.tradeNo || '-' }}</text>
                <AppIcon v-if="item.tradeNo" name="copy" :size="26" color="#C6171E" class="copy-icon" @click.stop="copyText(item.tradeNo)" />
              </view>
            </view>
            <view class="info-row">
              <text class="info-label">创建时间</text>
              <text class="info-value">{{ formatTime(item.createTime) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">更新时间</text>
              <text class="info-value">{{ formatTime(item.updateTime) }}</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="trending-up" :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>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getSplitRecords } from '../../api/finance.js'
import { getStationList } from '../../api/station.js'
import { formatTime, formatAmount, fmtDictName, getDictColor, showToast, copyText } from '../../utils/index.js'
import { 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 tradeNo = ref('')
const stationList = ref([])
const selectedStationId = ref('')
const selectedStationName = ref('')
const activeType = ref('')
const activeTypeLabel = ref('')

const typeOptions = [
  { label: '全部类型', value: '' }
]

const getTypeStyle = (type) => {
  const color = getDictColor('SplitRecord.type', type)
  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 handleTypeChange = (e) => {
  const index = e.detail.value
  const selected = typeOptions[index]
  if (selected) {
    activeType.value = selected.value
    activeTypeLabel.value = selected.label
  }
}

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 (tradeNo.value) params.tradeNo = tradeNo.value
    if (activeType.value) params.type = activeType.value

    const res = await getSplitRecords(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
      }

      // 从数据中提取交易类型，补充到 typeOptions
      if (!isLoadMore && records.length > 0) {
        const types = new Set()
        records.forEach(r => { if (r.type) types.add(r.type) })
        if (typeOptions.length === 1) {
          types.forEach(t => typeOptions.push({ label: fmtDictName('SplitRecord.type', t) || t, value: t }))
        }
      }
    }
  } catch (error) {
    showToast('加载分账记录失败')
  } finally {
    loading.value = false
  }
}

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

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

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

<style scoped>
.split-container {
  height: 100vh;
  background-color: #F5F7FA;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.split-scroll {
  flex: 1;
  overflow: hidden;
}

.filter-section {
  flex-shrink: 0;
  background-color: #FFFFFF;
  padding: 24rpx 20rpx 20rpx;
  margin-bottom: 16rpx;
}
.filter-row {
  display: flex;
  gap: 16rpx;
  margin-bottom: 12rpx;
}
.filter-item {
  flex: 1;
}
.filter-item.full-width {
  flex: none;
  width: 100%;
}
.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;
}
.search-btn {
  width: 100%;
  padding: 16rpx 0;
  background: #C6171E;
  color: #FFFFFF;
  border-radius: 16rpx;
  font-size: 28rpx;
  border: none;
}

.split-list {
  padding: 0 20rpx;
}
.split-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);
}
.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #F0F0F0;
  margin-bottom: 16rpx;
}
.item-type {
  font-size: 24rpx;
  font-weight: 500;
  padding: 6rpx 20rpx;
  border-radius: 100rpx;
}
.item-amount {
  font-size: 32rpx;
  font-weight: 700;
  color: #C6171E;
}
.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
}
.info-label {
  font-size: 26rpx;
  color: #999999;
}
.info-value-row {
  display: flex;
  align-items: center;
  gap: 8rpx;
}
.info-value {
  font-size: 26rpx;
  color: #1A1A1A;
  max-width: 380rpx;
  text-align: right;
}
.info-value.trade-no {
  font-size: 24rpx;
  word-break: break-all;
}
.copy-icon {
  flex-shrink: 0;
}

.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; }
</style>
