<template>
  <scroll-view scroll-y class="page-scroll">
    <view class="container">
      <view class="budget-card">
        <view class="card-header">
          <text class="card-title">预算设置</text>
          <text class="card-subtitle">{{ currentMonthText }}</text>
        </view>

        <view class="card-body">
          <view class="form-item">
            <text class="label">预算金额</text>
            <input 
              v-model="form.amount" 
              type="text"
              inputmode="decimal"
              placeholder="请输入预算金额" 
              @input="onAmountInput"
            />
            <text class="form-tip">设置本月预算金额，用于控制支出</text>
          </view>

          <view v-if="budget.usedAmount !== undefined" class="info-section">
            <view class="info-item">
              <text class="info-label">本月已支出</text>
              <text class="info-value expense">¥{{ budget.usedAmount ? budget.usedAmount.toFixed(2) : '0.00' }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">剩余预算</text>
              <text class="info-value" :class="budget.remainingAmount >= 0 ? 'positive' : 'negative'">
                ¥{{ budget.remainingAmount !== undefined ? budget.remainingAmount.toFixed(2) : '0.00' }}
              </text>
            </view>
            <view v-if="budget.remainingDaily !== undefined && budget.remainingDaily > 0" class="info-item">
              <text class="info-label">剩余日均</text>
              <text class="info-value">¥{{ budget.remainingDaily.toFixed(2) }}</text>
            </view>
          </view>
        </view>

        <view class="card-footer">
          <button class="save-btn" @click="saveBudget" :loading="saving">保存</button>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getBudget, setBudget } from '../../api/budget'

const budget = ref({
  id: null,
  year: null,
  month: null,
  amount: 0,
  usedAmount: 0,
  remainingAmount: 0,
  remainingDaily: 0
})

const form = ref({
  year: null,
  month: null,
  amount: '0.00'
})

const saving = ref(false)

const currentMonthText = computed(() => {
  if (budget.value.year && budget.value.month) {
    return `${budget.value.year}年${budget.value.month}月`
  }
  const now = new Date()
  return `${now.getFullYear()}年${now.getMonth() + 1}月`
})

const loadBudget = async () => {
  try {
    const data = await getBudget()
    if (data) {
      budget.value = data
      form.value.year = data.year
      form.value.month = data.month
      form.value.amount = data.amount ? data.amount.toFixed(2) : '0.00'
    } else {
      // 如果没有预算数据，使用默认值
      const now = new Date()
      budget.value = {
        year: now.getFullYear(),
        month: now.getMonth() + 1,
        amount: 0,
        usedAmount: 0,
        remainingAmount: 0,
        remainingDaily: 0
      }
      form.value.year = now.getFullYear()
      form.value.month = now.getMonth() + 1
      form.value.amount = '0.00'
    }
  } catch (error) {
    console.error('加载预算失败', error)
    uni.showToast({
      title: '加载预算失败',
      icon: 'none'
    })
  }
}

const onAmountInput = (e) => {
  let value = e.detail.value || ''
  value = value.replace(/[^\d.]/g, '')
  const parts = value.split('.')
  if (parts.length > 2) {
    value = parts[0] + '.' + parts.slice(1).join('')
  }
  if (parts.length === 2 && parts[1].length > 2) {
    value = parts[0] + '.' + parts[1].substring(0, 2)
  }
  form.value.amount = value
}

const saveBudget = async () => {
  const amount = parseFloat(form.value.amount) || 0
  
  if (amount < 0) {
    uni.showToast({
      title: '预算金额不能为负数',
      icon: 'none'
    })
    return
  }

  saving.value = true
  try {
    const data = await setBudget({
      year: form.value.year,
      month: form.value.month,
      amount: amount
    })
    
    if (data) {
      budget.value = data
      uni.showToast({
        title: '保存成功',
        icon: 'success'
      })
      
      // 触发首页刷新
      uni.$emit('refreshBills')
      
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  } catch (error) {
    console.error('保存预算失败', error)
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none'
    })
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadBudget()
})
</script>

<style scoped>
.page-scroll {
  height: 100vh;
  width: 100%;
  padding-bottom: calc(50px + env(safe-area-inset-bottom));
}

.container {
  min-height: calc(100vh - 100rpx);
  background: #f5f5f5;
  padding: 20rpx;
  padding-bottom: calc(170rpx + env(safe-area-inset-bottom));
}

.budget-card {
  background: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  text-align: center;
}

.card-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.card-subtitle {
  font-size: 28rpx;
  color: #666;
  display: block;
}

.card-body {
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.input {
  width: 100%;
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  font-size: 32rpx;
  box-sizing: border-box;
  border: none;
  outline: none;
  -webkit-appearance: none;
}

.form-tip {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.info-section {
  margin-top: 40rpx;
  padding-top: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.info-label {
  font-size: 28rpx;
  color: #666;
}

.info-value {
  font-size: 32rpx;
  font-weight: bold;
}

.info-value.positive {
  color: #667eea;
}

.info-value.negative {
  color: #fa3534;
}

.info-value.expense {
  color: #fa3534;
}

.card-footer {
  padding: 0 30rpx 30rpx;
}

.save-btn {
  width: 100%;
  height: 88rpx;
  background: #667eea;
  color: #fff;
  border-radius: 12rpx;
  font-size: 32rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>


