<template>
  <view class="refund-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper">
        <view class="search-icon">
          <AppIcon name="search" :size="28" color="#999999" />
        </view>
        <input type="text" placeholder="搜索手机号" v-model="searchKeyword" @confirm="handleSearch" />
      </view>
      <button class="search-btn" @click="handleSearch">搜索</button>
    </view>

    <!-- 状态筛选 + 全选 -->
    <view class="filter-bar">
      <scroll-view class="filter-scroll" scroll-x="true" :show-scrollbar="false">
        <view class="filter-scroll-inner">
          <view
            v-for="(option, index) in statusOptions"
            :key="index"
            class="filter-item"
            :class="{ active: activeStatus === option.value }"
            @click="handleStatusChange(option.value)">
            <text>{{ option.label }}</text>
          </view>
        </view>
      </scroll-view>
      <view class="filter-divider"></view>
      <view class="filter-item select-all-item" :class="{ active: isSelectAll }" @click="toggleSelectAll">
        <text>{{ isSelectAll ? '取消全选' : '全选待退款' }}</text>
      </view>
    </view>

    <!-- 退款列表 -->
    <view class="refund-list" v-if="list.length > 0">
      <view
        class="refund-item"
        v-for="(item, index) in list"
        :key="index"
        :class="{ selected: selectedIds.has(item.refundLogId) }"
        @click="handleItemClick(item)">
        <view class="item-header">
          <view class="item-left">
            <view class="checkbox-wrapper" v-if="isRefundableStatus(item.status)" @click.stop="toggleSelect(item)">
              <view class="checkbox" :class="{ checked: selectedIds.has(item.refundLogId) }">
                <AppIcon v-if="selectedIds.has(item.refundLogId)" name="check" :size="20" color="#FFFFFF" />
              </view>
            </view>
            <text class="item-phone">{{ item.mobilePhone || '-' }}</text>
          </view>
          <text class="status-tag" :style="getStatusStyle(item.status)">{{ fmtDictName('RefundLog.status', item.status) }}</text>
        </view>
        <view class="item-content">
          <view class="info-row">
            <text class="info-label">商户订单号</text>
            <text class="info-value">{{ item.outTradeNo || '-' }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">退款单号</text>
            <text class="info-value">{{ item.outRefundNo || '-' }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">原充值金额</text>
            <text class="info-value amount">{{ formatAmount(item.total) }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">退款金额</text>
            <text class="info-value amount-refund">{{ formatAmount(item.refund) }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">退款原因</text>
            <text class="info-value">{{ item.reason || '-' }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">退款人</text>
            <text class="info-value">{{ item.adminUsername || '-' }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">申请时间</text>
            <text class="info-value">{{ formatTime(item.createTime) }}</text>
          </view>
          <view class="info-row" v-if="item.successTime">
            <text class="info-label">退款成功时间</text>
            <text class="info-value">{{ formatTime(item.successTime) }}</text>
          </view>
        </view>
        <view class="item-footer" v-if="isRefundableStatus(item.status)">
          <button class="refund-btn" @click.stop="handleProcessRefund(item)">退款处理</button>
        </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="inbox" :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="batch-bar" v-if="selectedIds.size > 0">
      <view class="batch-info">
        <text class="batch-count">已选 {{ selectedIds.size }} 项</text>
      </view>
      <button class="batch-btn" @click="handleBatchRefund">批量退款处理</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { onReachBottom } from '@dcloudio/uni-app'
import { getRefundLogs, processRefund, batchProcessRefund } from '../../api/finance.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 searchKeyword = ref('')
const activeStatus = ref('')
const selectedIds = ref(new Set())

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

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

const isRefundableStatus = (status) => {
  return status === 'NEW'
}

// 当前页所有可退款的ID列表
const refundableIds = computed(() => {
  return list.value
    .filter(item => isRefundableStatus(item.status))
    .map(item => item.refundLogId)
})

const isSelectAll = computed(() => {
  const ids = refundableIds.value
  return ids.length > 0 && ids.every(id => selectedIds.value.has(id))
})

const toggleSelect = (item) => {
  const id = item.refundLogId
  const next = new Set(selectedIds.value)
  if (next.has(id)) {
    next.delete(id)
  } else {
    next.add(id)
  }
  selectedIds.value = next
}

const toggleSelectAll = () => {
  if (isSelectAll.value) {
    selectedIds.value = new Set()
  } else {
    selectedIds.value = new Set(refundableIds.value)
  }
}

const handleItemClick = (item) => {
  if (item.outRefundNo) {
    uni.navigateTo({
      url: `/pages/finance/refund-detail?outRefundNo=${item.outRefundNo}`
    })
  }
}

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

  loading.value = true
  try {
    const params = {
      pageNum: page.value,
      pageSize: pageSize.value
    }
    if (searchKeyword.value) params.mobilePhone = searchKeyword.value
    if (activeStatus.value) params.status = activeStatus.value

    const res = await getRefundLogs(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 handleProcessRefund = (item) => {
  uni.showModal({
    title: '确认退款',
    content: `确定对该笔退款（${item.outRefundNo || item.refundLogId}）进行退款处理吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await processRefund(item.refundLogId || item.id)
          if (result && result.code === 200) {
            showToast('退款处理成功', 'success')
            loadData()
          } else {
            showToast(result?.msg || '退款处理失败')
          }
        } catch (error) {
          showToast('退款处理失败')
        }
      }
    }
  })
}

const handleBatchRefund = () => {
  const ids = [...selectedIds.value]
  if (ids.length === 0) {
    showToast('请选择退款记录')
    return
  }
  uni.showModal({
    title: '批量退款确认',
    content: `确定对已选的 ${ids.length} 笔退款进行批量处理吗？`,
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '批量退款处理中...', mask: true })
        try {
          const result = await batchProcessRefund(ids)
          uni.hideLoading()
          if (result && result.code === 200) {
            showToast(`批量退款已提交，共${ids.length}笔`, 'success')
            selectedIds.value = new Set()
            loadData()
          } else {
            showToast(result?.msg || '批量退款处理失败')
          }
        } catch (error) {
          uni.hideLoading()
          showToast('批量退款处理失败')
        }
      }
    }
  })
}

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

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

.search-bar {
  display: flex;
  align-items: center;
  padding: 16rpx 20rpx;
  background-color: #FFFFFF;
}
.search-input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #F5F5F5;
  border-radius: 16rpx;
  padding: 0 16rpx;
}
.search-icon {
  margin-right: 8rpx;
}
.search-input-wrapper input {
  flex: 1;
  height: 60rpx;
  font-size: 28rpx;
}
.search-btn {
  margin-left: 16rpx;
  padding: 10rpx 28rpx;
  background: #C6171E;
  color: #FFFFFF;
  border-radius: 16rpx;
  font-size: 26rpx;
  border: none;
}

.search-btn:active {
  background: #A81212;
  transform: scale(0.97);
}

.filter-bar {
  display: flex;
  align-items: center;
  padding: 12rpx 20rpx;
  background-color: #FFFFFF;
}

.filter-scroll {
  flex: 1;
  min-width: 0;
}

.filter-scroll-inner {
  display: flex;
  gap: 16rpx;
  white-space: nowrap;
}

.filter-divider {
  width: 1rpx;
  height: 32rpx;
  background-color: #E5E5E5;
  margin: 0 16rpx;
  flex-shrink: 0;
}

.filter-item {
  padding: 8rpx 24rpx;
  background-color: #F5F5F5;
  border-radius: 100rpx;
  font-size: 24rpx;
  color: #666666;
  flex-shrink: 0;
  white-space: nowrap;
}

.filter-item.active {
  background: #C6171E;
  color: #FFFFFF;
}

.select-all-item {
  flex-shrink: 0;
  color: #C6171E;
  background-color: #FFF0F0;
}

.refund-list {
  padding: 20rpx;
}
.refund-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);
}
.refund-item.selected {
  background-color: #FFF5F5;
  border: 2rpx solid #C6171E;
}
.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #F0F0F0;
  margin-bottom: 16rpx;
}
.item-left {
  display: flex;
  align-items: center;
  gap: 16rpx;
}
.checkbox-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 44rpx;
  height: 44rpx;
}
.checkbox {
  width: 40rpx;
  height: 40rpx;
  border-radius: 8rpx;
  border: 2rpx solid #D0D0D0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.checkbox.checked {
  background-color: #C6171E;
  border-color: #C6171E;
}
.item-phone {
  font-size: 30rpx;
  font-weight: 600;
  color: #1A1A1A;
}
.status-tag {
  font-size: 22rpx;
  padding: 6rpx 24rpx;
  border-radius: 100rpx;
  font-weight: 500;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
}
.info-label {
  font-size: 26rpx;
  color: #999999;
}
.info-value {
  font-size: 26rpx;
  color: #1A1A1A;
  max-width: 400rpx;
  text-align: right;
  word-break: break-all;
}
.info-value.amount {
  color: #C6171E;
  font-weight: 500;
}
.info-value.amount-refund {
  color: #52C41A;
  font-weight: 500;
}

.item-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 16rpx;
  border-top: 1rpx solid #F0F0F0;
  margin-top: 16rpx;
}
.refund-btn {
  padding: 12rpx 32rpx;
  background: #C6171E;
  color: #FFFFFF;
  border-radius: 16rpx;
  font-size: 26rpx;
  border: none;
}

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

/* 批量操作栏 */
.batch-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background-color: #FFFFFF;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.08);
  z-index: 100;
}
.batch-info {
  display: flex;
  align-items: center;
}
.batch-count {
  font-size: 28rpx;
  color: #1A1A1A;
  font-weight: 500;
}
.batch-btn {
  padding: 16rpx 40rpx;
  background: #C6171E;
  color: #FFFFFF;
  border-radius: 16rpx;
  font-size: 28rpx;
  border: none;
  font-weight: 500;
}
.batch-btn:active {
  background: #A81212;
  transform: scale(0.97);
}
</style>
