<template>
  <view class="loan-page">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="navbar-title">贷款管理</view>
      <view class="navbar-action" @click="showFilter = true">
        <uni-icons type="tune" size="18" />
      </view>
    </view>

    <!-- 统计卡片 -->
    <view class="stats-section">
      <scroll-view class="stats-scroll" scroll-x>
        <view 
          v-for="(stat, index) in statsData" 
          :key="index"
          class="stat-card"
          :class="stat.type"
        >
          <view class="stat-icon">
            <uni-icons :type="stat.icon" size="24" color="#fff" />
          </view>
          <view class="stat-info">
            <view class="stat-value">{{ stat.value }}</view>
            <view class="stat-label">{{ stat.label }}</view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 快捷操作 -->
    <view class="quick-actions">
      <view class="action-title">快捷操作</view>
      <view class="action-grid">
        <view 
          v-for="action in quickActions" 
          :key="action.id"
          class="action-item"
          @click="handleQuickAction(action.id)"
        >
          <view class="action-icon">
            <uni-icons :type="action.icon" size="20" :color="action.color" />
          </view>
          <text class="action-text">{{ action.text }}</text>
        </view>
      </view>
    </view>

    <!-- 贷款列表 -->
    <view class="loan-section">
      <view class="section-header">
        <view class="section-title">贷款申请</view>
        <view class="section-action" @click="goToApply">
          <text>新增申请</text>
          <uni-icons type="plus" size="16" />
        </view>
      </view>

      <scroll-view 
        class="loan-list" 
        scroll-y
        @scrolltolower="loadMore"
        :refresher-enabled="true"
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
      >
        <view 
          v-for="loan in loanList" 
          :key="loan.id"
          class="loan-card"
          @click="goToDetail(loan.id)"
        >
          <view class="loan-header">
            <view class="loan-info">
              <view class="loan-title">{{ loan.title }}</view>
              <view class="loan-amount">
                <text class="currency">¥</text>
                <text class="amount">{{ formatNumber(loan.amount) }}</text>
              </view>
            </view>
            <view class="loan-status" :class="loan.status">
              {{ getStatusText(loan.status) }}
            </view>
          </view>

          <view class="loan-details">
            <view class="detail-item">
              <text class="label">申请人：</text>
              <text class="value">{{ loan.applicant }}</text>
            </view>
            <view class="detail-item">
              <text class="label">申请时间：</text>
              <text class="value">{{ formatDate(loan.applyTime) }}</text>
            </view>
            <view class="detail-item">
              <text class="label">贷款期限：</text>
              <text class="value">{{ loan.term }}个月</text>
            </view>
            <view class="detail-item">
              <text class="label">利率：</text>
              <text class="value">{{ loan.interestRate }}%</text>
            </view>
          </view>

          <view class="loan-progress">
            <view class="progress-info">
              <text class="progress-label">审批进度</text>
              <text class="progress-percent">{{ loan.progress }}%</text>
            </view>
            <view class="progress-bar">
              <view 
                class="progress-fill" 
                :style="{ width: loan.progress + '%' }"
              ></view>
            </view>
          </view>

          <view class="loan-actions">
            <button 
              v-if="loan.status === 'pending'"
              class="action-btn primary"
              @click.stop="approveApplication(loan.id)"
            >
              审批
            </button>
            <button 
              v-if="loan.status === 'approved'"
              class="action-btn success"
              @click.stop="disburseLoan(loan.id)"
            >
              放款
            </button>
            <button 
              class="action-btn secondary"
              @click.stop="viewDetails(loan.id)"
            >
              查看详情
            </button>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="loading" class="loading-more">
          <uni-loading type="snow" />
          <text>加载中...</text>
        </view>
        
        <!-- 没有更多数据 -->
        <view v-if="!hasMore && loanList.length > 0" class="no-more">
          没有更多数据了
        </view>
      </scroll-view>
    </view>

    <!-- 筛选弹窗 -->
    <uni-popup ref="filterPopup" type="bottom">
      <view class="filter-popup">
        <view class="filter-header">
          <text>筛选条件</text>
          <view class="filter-actions">
            <text @click="resetFilter">重置</text>
            <text @click="applyFilter">确定</text>
          </view>
        </view>
        
        <view class="filter-content">
          <!-- 状态筛选 -->
          <view class="filter-section">
            <view class="section-title">申请状态</view>
            <view class="status-options">
              <view 
                v-for="status in statusOptions" 
                :key="status.value"
                class="status-item"
                :class="{ active: filterData.status === status.value }"
                @click="filterData.status = status.value"
              >
                {{ status.label }}
              </view>
            </view>
          </view>

          <!-- 金额范围 -->
          <view class="filter-section">
            <view class="section-title">贷款金额</view>
            <view class="amount-range">
              <input 
                v-model="filterData.minAmount" 
                type="number" 
                placeholder="最低金额"
                class="amount-input"
              />
              <text class="separator">-</text>
              <input 
                v-model="filterData.maxAmount" 
                type="number" 
                placeholder="最高金额"
                class="amount-input"
              />
            </view>
          </view>

          <!-- 时间范围 -->
          <view class="filter-section">
            <view class="section-title">申请时间</view>
            <view class="date-range">
              <picker 
                mode="date" 
                :value="filterData.startDate" 
                @change="onStartDateChange"
              >
                <view class="date-picker">
                  {{ filterData.startDate || '开始日期' }}
                </view>
              </picker>
              <text class="separator">至</text>
              <picker 
                mode="date" 
                :value="filterData.endDate" 
                @change="onEndDateChange"
              >
                <view class="date-picker">
                  {{ filterData.endDate || '结束日期' }}
                </view>
              </picker>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 审批弹窗 -->
    <uni-popup ref="approvePopup" type="center">
      <view class="approve-popup">
        <view class="popup-title">贷款审批</view>
        <view class="approve-form">
          <view class="form-item">
            <text class="form-label">审批结果</text>
            <radio-group @change="onApprovalChange">
              <label class="radio-item">
                <radio value="approved" />
                <text>通过</text>
              </label>
              <label class="radio-item">
                <radio value="rejected" />
                <text>拒绝</text>
              </label>
            </radio-group>
          </view>
          <view class="form-item">
            <text class="form-label">审批意见</text>
            <textarea 
              v-model="approvalData.comment"
              placeholder="请输入审批意见..."
              class="form-textarea"
            />
          </view>
        </view>
        <view class="popup-actions">
          <button class="cancel-btn" @click="closeApprovePopup">取消</button>
          <button class="confirm-btn" @click="submitApproval">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRequest } from '@/common/utils/request'
import { formatNumber, formatDate } from '@/common/utils/format'
import { showToast, showLoading, hideLoading } from '@/common/utils/uni-helper'

export default {
  name: 'LoanPage',
  setup() {
    const request = useRequest()
    
    // 响应式数据
    const loanList = ref([])
    const loading = ref(false)
    const refreshing = ref(false)
    const hasMore = ref(true)
    const currentPage = ref(1)
    const showFilter = ref(false)
    const currentLoanId = ref(null)
    
    // 统计数据
    const statsData = ref([
      {
        type: 'total',
        icon: 'wallet',
        value: '1,234',
        label: '总申请数'
      },
      {
        type: 'pending',
        icon: 'clock',
        value: '56',
        label: '待审批'
      },
      {
        type: 'approved',
        icon: 'checkmarkempty',
        value: '890',
        label: '已通过'
      },
      {
        type: 'disbursed',
        icon: 'redo',
        value: '¥2.1亿',
        label: '已放款'
      }
    ])
    
    // 快捷操作
    const quickActions = ref([
      { id: 'apply', icon: 'plus', color: '#2E8B57', text: '新增申请' },
      { id: 'approve', icon: 'checkmarkempty', color: '#007AFF', text: '批量审批' },
      { id: 'report', icon: 'bars', color: '#FF9500', text: '统计报告' },
      { id: 'export', icon: 'download', color: '#5856D6', text: '导出数据' }
    ])
    
    // 筛选数据
    const filterData = reactive({
      status: '',
      minAmount: '',
      maxAmount: '',
      startDate: '',
      endDate: ''
    })
    
    // 状态选项
    const statusOptions = ref([
      { value: '', label: '全部' },
      { value: 'pending', label: '待审批' },
      { value: 'approved', label: '已通过' },
      { value: 'rejected', label: '已拒绝' },
      { value: 'disbursed', label: '已放款' }
    ])
    
    // 审批数据
    const approvalData = reactive({
      result: '',
      comment: ''
    })
    
    // 获取贷款列表
    const getLoanList = async (isRefresh = false) => {
      if (loading.value && !isRefresh) return
      
      try {
        loading.value = true
        
        const params = {
          page: isRefresh ? 1 : currentPage.value,
          pageSize: 10,
          ...filterData
        }
        
        const response = await request.get('/api/loans/list', params)
        
        if (isRefresh) {
          loanList.value = response.data.list
          currentPage.value = 1
        } else {
          loanList.value.push(...response.data.list)
        }
        
        hasMore.value = response.data.hasMore
        currentPage.value++
        
      } catch (error) {
        showToast('获取数据失败')
      } finally {
        loading.value = false
        refreshing.value = false
      }
    }
    
    // 获取统计数据
    const getStatsData = async () => {
      try {
        const response = await request.get('/api/loans/stats')
        statsData.value = response.data
      } catch (error) {
        console.error('获取统计数据失败', error)
      }
    }
    
    // 下拉刷新
    const onRefresh = () => {
      refreshing.value = true
      getLoanList(true)
      getStatsData()
    }
    
    // 加载更多
    const loadMore = () => {
      if (hasMore.value && !loading.value) {
        getLoanList()
      }
    }
    
    // 快捷操作处理
    const handleQuickAction = (actionId) => {
      switch (actionId) {
        case 'apply':
          goToApply()
          break
        case 'approve':
          batchApprove()
          break
        case 'report':
          goToReport()
          break
        case 'export':
          exportData()
          break
      }
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        pending: '待审批',
        approved: '已通过',
        rejected: '已拒绝',
        disbursed: '已放款'
      }
      return statusMap[status] || '未知'
    }
    
    // 审批申请
    const approveApplication = (loanId) => {
      currentLoanId.value = loanId
      uni.$refs.approvePopup.open()
    }
    
    // 放款
    const disburseLoan = async (loanId) => {
      try {
        showLoading('处理中...')
        await request.post(`/api/loans/${loanId}/disburse`)
        showToast('放款成功')
        getLoanList(true)
      } catch (error) {
        showToast('放款失败')
      } finally {
        hideLoading()
      }
    }
    
    // 查看详情
    const viewDetails = (loanId) => {
      uni.navigateTo({
        url: `/pages/loan-detail/loan-detail?id=${loanId}`
      })
    }
    
    // 跳转到申请页面
    const goToApply = () => {
      uni.navigateTo({
        url: '/pages/loan-apply/loan-apply'
      })
    }
    
    // 跳转到详情页
    const goToDetail = (loanId) => {
      uni.navigateTo({
        url: `/pages/loan-detail/loan-detail?id=${loanId}`
      })
    }
    
    // 批量审批
    const batchApprove = () => {
      uni.navigateTo({
        url: '/pages/batch-approve/batch-approve'
      })
    }
    
    // 跳转到报告页
    const goToReport = () => {
      uni.navigateTo({
        url: '/pages/loan-report/loan-report'
      })
    }
    
    // 导出数据
    const exportData = async () => {
      try {
        showLoading('导出中...')
        await request.post('/api/loans/export')
        showToast('导出成功')
      } catch (error) {
        showToast('导出失败')
      } finally {
        hideLoading()
      }
    }
    
    // 审批结果改变
    const onApprovalChange = (e) => {
      approvalData.result = e.detail.value
    }
    
    // 提交审批
    const submitApproval = async () => {
      if (!approvalData.result) {
        showToast('请选择审批结果')
        return
      }
      
      try {
        showLoading('提交中...')
        await request.post(`/api/loans/${currentLoanId.value}/approve`, {
          result: approvalData.result,
          comment: approvalData.comment
        })
        showToast('审批成功')
        closeApprovePopup()
        getLoanList(true)
      } catch (error) {
        showToast('审批失败')
      } finally {
        hideLoading()
      }
    }
    
    // 关闭审批弹窗
    const closeApprovePopup = () => {
      uni.$refs.approvePopup.close()
      approvalData.result = ''
      approvalData.comment = ''
      currentLoanId.value = null
    }
    
    // 日期选择
    const onStartDateChange = (e) => {
      filterData.startDate = e.detail.value
    }
    
    const onEndDateChange = (e) => {
      filterData.endDate = e.detail.value
    }
    
    // 重置筛选
    const resetFilter = () => {
      Object.keys(filterData).forEach(key => {
        filterData[key] = ''
      })
    }
    
    // 应用筛选
    const applyFilter = () => {
      showFilter.value = false
      currentPage.value = 1
      getLoanList(true)
    }
    
    // 页面加载
    onMounted(() => {
      getLoanList(true)
      getStatsData()
    })
    
    return {
      loanList,
      loading,
      refreshing,
      hasMore,
      showFilter,
      statsData,
      quickActions,
      filterData,
      statusOptions,
      approvalData,
      formatNumber,
      formatDate,
      onRefresh,
      loadMore,
      handleQuickAction,
      getStatusText,
      approveApplication,
      disburseLoan,
      viewDetails,
      goToApply,
      goToDetail,
      onApprovalChange,
      submitApproval,
      closeApprovePopup,
      onStartDateChange,
      onEndDateChange,
      resetFilter,
      applyFilter
    }
  }
}
</script>

<style lang="scss" scoped>
.loan-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: $bg-secondary;
}

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: $spacing-md;
  background-color: $white;
  border-bottom: 1px solid $border-color;
  
  .navbar-title {
    font-size: $font-size-lg;
    font-weight: $font-weight-medium;
    color: $text-primary;
  }
  
  .navbar-action {
    padding: $spacing-xs;
    color: $primary-color;
  }
}

.stats-section {
  background-color: $white;
  padding: $spacing-md;
  
  .stats-scroll {
    white-space: nowrap;
    
    .stat-card {
      display: inline-flex;
      align-items: center;
      padding: $spacing-md;
      margin-right: $spacing-md;
      border-radius: $border-radius-lg;
      min-width: 120px;
      gap: $spacing-sm;
      
      &.total {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }
      
      &.pending {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }
      
      &.approved {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }
      
      &.disbursed {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      }
      
      .stat-icon {
        width: 40px;
        height: 40px;
        background-color: rgba(255, 255, 255, 0.2);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      
      .stat-info {
        color: $white;
        
        .stat-value {
          font-size: $font-size-xl;
          font-weight: $font-weight-bold;
          line-height: 1.2;
        }
        
        .stat-label {
          font-size: $font-size-sm;
          opacity: 0.9;
        }
      }
    }
  }
}

.quick-actions {
  background-color: $white;
  padding: $spacing-md;
  margin-top: $spacing-sm;
  
  .action-title {
    font-size: $font-size-base;
    font-weight: $font-weight-medium;
    color: $text-primary;
    margin-bottom: $spacing-md;
  }
  
  .action-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: $spacing-md;
    
    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: $spacing-xs;
      
      .action-icon {
        width: 48px;
        height: 48px;
        background-color: $bg-light;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      
      .action-text {
        font-size: $font-size-sm;
        color: $text-secondary;
      }
    }
  }
}

.loan-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-top: $spacing-sm;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: $spacing-md;
    background-color: $white;
    
    .section-title {
      font-size: $font-size-base;
      font-weight: $font-weight-medium;
      color: $text-primary;
    }
    
    .section-action {
      display: flex;
      align-items: center;
      gap: $spacing-xs;
      color: $primary-color;
      font-size: $font-size-sm;
    }
  }
  
  .loan-list {
    flex: 1;
    padding: 0 $spacing-md $spacing-md;
  }
}

.loan-card {
  background-color: $white;
  border-radius: $border-radius-lg;
  padding: $spacing-md;
  margin-bottom: $spacing-md;
  box-shadow: $shadow-sm;
  
  .loan-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: $spacing-md;
    
    .loan-info {
      flex: 1;
      
      .loan-title {
        font-size: $font-size-base;
        font-weight: $font-weight-medium;
        color: $text-primary;
        margin-bottom: $spacing-xs;
      }
      
      .loan-amount {
        .currency {
          font-size: $font-size-sm;
          color: $primary-color;
        }
        
        .amount {
          font-size: $font-size-xl;
          font-weight: $font-weight-bold;
          color: $primary-color;
        }
      }
    }
    
    .loan-status {
      padding: $spacing-xs $spacing-sm;
      border-radius: $border-radius-full;
      font-size: $font-size-xs;
      
      &.pending {
        background-color: rgba(255, 149, 0, 0.1);
        color: #FF9500;
      }
      
      &.approved {
        background-color: rgba(0, 122, 255, 0.1);
        color: #007AFF;
      }
      
      &.rejected {
        background-color: rgba(255, 59, 48, 0.1);
        color: #FF3B30;
      }
      
      &.disbursed {
        background-color: rgba(46, 139, 87, 0.1);
        color: $primary-color;
      }
    }
  }
  
  .loan-details {
    margin-bottom: $spacing-md;
    
    .detail-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: $spacing-xs;
      
      .label {
        font-size: $font-size-sm;
        color: $text-secondary;
      }
      
      .value {
        font-size: $font-size-sm;
        color: $text-primary;
      }
    }
  }
  
  .loan-progress {
    margin-bottom: $spacing-md;
    
    .progress-info {
      display: flex;
      justify-content: space-between;
      margin-bottom: $spacing-xs;
      
      .progress-label {
        font-size: $font-size-sm;
        color: $text-secondary;
      }
      
      .progress-percent {
        font-size: $font-size-sm;
        color: $primary-color;
        font-weight: $font-weight-medium;
      }
    }
    
    .progress-bar {
      height: 4px;
      background-color: $bg-light;
      border-radius: 2px;
      overflow: hidden;
      
      .progress-fill {
        height: 100%;
        background-color: $primary-color;
        transition: width 0.3s ease;
      }
    }
  }
  
  .loan-actions {
    display: flex;
    gap: $spacing-sm;
    
    .action-btn {
      flex: 1;
      padding: $spacing-sm;
      border-radius: $border-radius-md;
      font-size: $font-size-sm;
      text-align: center;
      
      &.primary {
        background-color: $primary-color;
        color: $white;
      }
      
      &.success {
        background-color: $success-color;
        color: $white;
      }
      
      &.secondary {
        background-color: $bg-light;
        color: $text-secondary;
      }
    }
  }
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: $spacing-lg;
  gap: $spacing-sm;
  color: $text-muted;
  font-size: $font-size-sm;
}

.no-more {
  text-align: center;
  padding: $spacing-lg;
  color: $text-muted;
  font-size: $font-size-sm;
}

.filter-popup {
  background-color: $white;
  border-radius: $border-radius-lg $border-radius-lg 0 0;
  max-height: 70vh;
  
  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: $spacing-lg;
    border-bottom: 1px solid $border-color;
    
    .filter-actions {
      display: flex;
      gap: $spacing-lg;
      
      text {
        color: $primary-color;
        font-size: $font-size-base;
      }
    }
  }
  
  .filter-content {
    padding: $spacing-lg;
    max-height: 50vh;
    overflow-y: auto;
  }
  
  .filter-section {
    margin-bottom: $spacing-xl;
    
    .section-title {
      font-size: $font-size-base;
      font-weight: $font-weight-medium;
      color: $text-primary;
      margin-bottom: $spacing-md;
    }
    
    .status-options {
      display: flex;
      flex-wrap: wrap;
      gap: $spacing-sm;
      
      .status-item {
        padding: $spacing-sm $spacing-md;
        background-color: $bg-light;
        border-radius: $border-radius-full;
        font-size: $font-size-sm;
        color: $text-secondary;
        
        &.active {
          background-color: $primary-color;
          color: $white;
        }
      }
    }
    
    .amount-range,
    .date-range {
      display: flex;
      align-items: center;
      gap: $spacing-sm;
      
      .amount-input,
      .date-picker {
        flex: 1;
        padding: $spacing-sm;
        border: 1px solid $border-color;
        border-radius: $border-radius-md;
        text-align: center;
        font-size: $font-size-sm;
      }
      
      .separator {
        color: $text-muted;
      }
    }
  }
}

.approve-popup {
  background-color: $white;
  border-radius: $border-radius-lg;
  padding: $spacing-lg;
  width: 300px;
  
  .popup-title {
    font-size: $font-size-lg;
    font-weight: $font-weight-medium;
    color: $text-primary;
    text-align: center;
    margin-bottom: $spacing-lg;
  }
  
  .approve-form {
    margin-bottom: $spacing-lg;
    
    .form-item {
      margin-bottom: $spacing-md;
      
      .form-label {
        display: block;
        font-size: $font-size-base;
        color: $text-primary;
        margin-bottom: $spacing-sm;
      }
      
      .radio-item {
        display: flex;
        align-items: center;
        gap: $spacing-xs;
        margin-bottom: $spacing-xs;
        
        text {
          font-size: $font-size-base;
          color: $text-primary;
        }
      }
      
      .form-textarea {
        width: 100%;
        min-height: 80px;
        padding: $spacing-sm;
        border: 1px solid $border-color;
        border-radius: $border-radius-md;
        font-size: $font-size-base;
        resize: none;
      }
    }
  }
  
  .popup-actions {
    display: flex;
    gap: $spacing-sm;
    
    button {
      flex: 1;
      padding: $spacing-sm;
      border-radius: $border-radius-md;
      font-size: $font-size-base;
      
      &.cancel-btn {
        background-color: $bg-light;
        color: $text-secondary;
      }
      
      &.confirm-btn {
        background-color: $primary-color;
        color: $white;
      }
    }
  }
}
</style>