<template>
  <scroll-view scroll-y class="page-scroll">
    <view class="container">
      <view class="form-card">
        <view class="form-header">
          <text class="form-title">编辑账单</text>
        </view>

        <view class="form-body">
          <view class="form-item">
            <text class="label">账单类型</text>
            <view class="type-selector-compact">
              <view 
                class="type-option-compact" 
                :class="{ active: form.type === 1 }" 
                @click="form.type = 1; loadCategories()"
              >
                <text class="type-icon-compact">📤</text>
                <text class="type-text-compact">支出</text>
              </view>
              <view 
                class="type-option-compact" 
                :class="{ active: form.type === 2 }" 
                @click="form.type = 2; loadCategories()"
              >
                <text class="type-icon-compact">📥</text>
                <text class="type-text-compact">收入</text>
              </view>
            </view>
          </view>

          <view class="form-item">
            <text class="label">分类</text>
            <view v-if="categories.length > 0" class="category-grid">
              <view 
                v-for="category in categories" 
                :key="category.id" 
                class="category-icon-item"
                :class="{ active: selectedCategory?.id === category.id }"
                @click="selectCategory(category)"
              >
                <view class="category-icon-circle">
                  <text class="category-icon-emoji">{{ category.icon || '📦' }}</text>
                </view>
                <text class="category-icon-name">{{ category.name }}</text>
              </view>
            </view>
            <view v-else class="category-empty">
              <text>暂无分类</text>
            </view>
          </view>

          <view class="form-item">
            <text class="label">金额</text>
            <input 
              v-model="form.amount" 
              type="text"
              inputmode="decimal"
              placeholder="请输入金额" 
              class="input"
              @input="onAmountInput"
            />
          </view>

          <view class="form-item">
            <text class="label">日期</text>
            <picker mode="date" :value="form.billDate" @change="onDateChange">
              <view class="picker">
                <text>{{ form.billDate || '选择日期' }}</text>
                <text class="arrow">></text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">备注</text>
            <textarea v-model="form.description" placeholder="请输入备注（可选）" class="textarea" />
          </view>
        </view>

        <view class="form-footer">
          <button class="delete-btn" @click="handleDelete">删除账单</button>
          <button class="submit-btn" @click="handleUpdate">保存修改</button>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { getBill, updateBill as updateBillApi, deleteBill as deleteBillApi } from '../../api/bill'
import { getCategories } from '../../api/category'
import { formatDate } from '../../utils/date'
import { onLoad } from '@dcloudio/uni-app'

const billId = ref(null)
const categories = ref([])
const selectedCategory = ref(null)

const form = ref({
  type: 1,
  categoryId: null,
  amount: '',
  description: '',
  billDate: formatDate(new Date())
})

const loadCategories = async () => {
  try {
    const type = form.value.type || 1
    const data = await getCategories(type)
    categories.value = data || []
    // 如果当前选中的分类不在新类型中，清空选择
    if (selectedCategory.value && selectedCategory.value.type !== type) {
      selectedCategory.value = null
      form.value.categoryId = null
    } else if (selectedCategory.value) {
      // 重新查找选中的分类
      const category = categories.value.find(cat => cat.id === selectedCategory.value.id)
      if (category) {
        selectedCategory.value = category
      }
    }
  } catch (error) {
    console.error('加载分类失败', error)
  }
}

const loadBill = async (id) => {
  try {
    const data = await getBill(id)
    if (data) {
      form.value = {
        type: data.type || 1,
        categoryId: data.categoryId,
        amount: Math.abs(data.amount || 0).toString(),
        description: data.description || '',
        billDate: formatDate(data.billDate || new Date())
      }
      
      // 加载分类后设置选中的分类
      await loadCategories()
      const category = categories.value.find(cat => cat.id === data.categoryId)
      if (category) {
        selectedCategory.value = category
      }
    }
  } catch (error) {
    console.error('加载账单失败', error)
    uni.showToast({
      title: '加载账单失败',
      icon: 'none'
    })
  }
}

const selectCategory = (category) => {
  selectedCategory.value = category
  form.value.categoryId = category.id
}

const onDateChange = (e) => {
  form.value.billDate = e.detail.value
}

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 handleUpdate = async () => {
  if (!form.value.type) {
    uni.showToast({
      title: '请选择账单类型',
      icon: 'none'
    })
    return
  }
  
  if (!form.value.categoryId) {
    uni.showToast({
      title: '请选择分类',
      icon: 'none'
    })
    return
  }

  if (!form.value.amount || parseFloat(form.value.amount) <= 0) {
    uni.showToast({
      title: '请输入有效金额',
      icon: 'none'
    })
    return
  }

  try {
    await updateBillApi(billId.value, {
      type: form.value.type,
      categoryId: form.value.categoryId,
      amount: parseFloat(form.value.amount),
      description: form.value.description,
      billDate: form.value.billDate
    })
    
    uni.showToast({
      title: '更新成功',
      icon: 'success'
    })

    // 触发首页刷新
    uni.$emit('refreshBills')
    
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } catch (error) {
    console.error('更新失败', error)
    uni.showToast({
      title: error.message || '更新失败',
      icon: 'none'
    })
  }
}

const handleDelete = () => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这笔账单吗？删除后无法恢复',
    confirmColor: '#fa3534',
    success: async (res) => {
      if (res.confirm) {
        try {
          await deleteBillApi(billId.value)
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
          
          // 触发首页刷新
          uni.$emit('refreshBills')
          
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } catch (error) {
          console.error('删除失败', error)
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 监听账单类型变化，重新加载分类
watch(() => form.value.type, (newType) => {
  if (newType && billId.value) {
    loadCategories()
  }
})

onLoad((options) => {
  if (options.id) {
    billId.value = options.id
    loadBill(options.id)
  }
})
</script>

<style scoped>
.page-scroll {
  height: 100vh;
  width: 100%;
  padding-bottom: calc(50px + env(safe-area-inset-bottom));
  background: linear-gradient(135deg, #FFE5CC 0%, #FFD4A8 50%, #FFC08A 100%);
}

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

.form-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 25rpx;
  padding: 40rpx 30rpx;
  border: 3rpx solid #C8956E;
  box-shadow: 0 10rpx 30rpx rgba(93, 64, 55, 0.15);
}

.form-header {
  margin-bottom: 35rpx;
  padding-bottom: 25rpx;
  border-bottom: 3rpx solid rgba(200, 149, 110, 0.3);
  text-align: center;
}

.form-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #5D4037;
  text-shadow: 2rpx 2rpx 0 rgba(255, 215, 0, 0.3);
}

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

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

.label {
  display: block;
  font-size: 28rpx;
  color: #5D4037;
  margin-bottom: 20rpx;
  font-weight: 600;
}

.type-selector-compact {
  display: flex;
  gap: 20rpx;
  justify-content: center;
}

.type-option-compact {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20rpx 40rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15rpx;
  border: 3rpx solid #C8956E;
  transition: all 0.3s;
  min-width: 140rpx;
  box-shadow: 0 4rpx 15rpx rgba(200, 149, 110, 0.1);
}

.type-option-compact.active {
  background: linear-gradient(135deg, #FFD700, #F5D59E);
  border-color: #FFD700;
  transform: scale(1.05);
  box-shadow: 0 8rpx 20rpx rgba(255, 215, 0, 0.3);
}

.type-icon-compact {
  font-size: 40rpx;
  margin-bottom: 8rpx;
  filter: drop-shadow(0 2rpx 4rpx rgba(0, 0, 0, 0.1));
}

.type-text-compact {
  font-size: 26rpx;
  color: #5D4037;
  font-weight: 600;
}

.category-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-top: 10rpx;
}

.category-icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: calc(25% - 15rpx);
  margin-bottom: 10rpx;
}

.category-icon-circle {
  width: 110rpx;
  height: 110rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10rpx;
  border: 3rpx solid #C8956E;
  transition: all 0.3s;
  box-shadow: 0 4rpx 15rpx rgba(200, 149, 110, 0.1);
}

.category-icon-item.active .category-icon-circle {
  background: linear-gradient(135deg, #FFD700, #F5D59E);
  border-color: #FFD700;
  transform: scale(1.15);
  box-shadow: 0 8rpx 20rpx rgba(255, 215, 0, 0.4);
}

.category-icon-emoji {
  font-size: 52rpx;
  line-height: 1;
  filter: drop-shadow(0 2rpx 4rpx rgba(0, 0, 0, 0.1));
}

.category-icon-name {
  font-size: 22rpx;
  color: #5D4037;
  text-align: center;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: 500;
}

.category-icon-item.active .category-icon-name {
  color: #FFD700;
  font-weight: bold;
  text-shadow: 0 2rpx 4rpx rgba(255, 215, 0, 0.3);
}

.category-empty {
  text-align: center;
  padding: 50rpx 0;
  color: #8D6E63;
  font-size: 26rpx;
  background: rgba(255, 255, 255, 0.5);
  border-radius: 15rpx;
  border: 2rpx dashed #C8956E;
}

.input, .textarea {
  width: 100%;
  padding: 25rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  border: 3rpx solid #C8956E;
  outline: none;
  color: #5D4037;
  box-shadow: 0 4rpx 15rpx rgba(200, 149, 110, 0.1);
  transition: all 0.3s;
}

.input:focus, .textarea:focus {
  border-color: #FFD700;
  box-shadow: 0 0 0 4rpx rgba(255, 215, 0, 0.3), 0 8rpx 25rpx rgba(255, 215, 0, 0.2);
}

.input::placeholder, .textarea::placeholder {
  color: #BCAAA4;
}

.textarea {
  min-height: 180rpx;
}

.picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15rpx;
  border: 3rpx solid #C8956E;
  box-shadow: 0 4rpx 15rpx rgba(200, 149, 110, 0.1);
}

.arrow {
  color: #C8956E;
  font-weight: bold;
}

.form-footer {
  display: flex;
  gap: 20rpx;
  margin-top: 40rpx;
}

.delete-btn {
  flex: 1;
  height: 96rpx;
  background: linear-gradient(135deg, #FA3534, #FF6B6B);
  color: #fff;
  border-radius: 50rpx;
  font-size: 28rpx;
  font-weight: bold;
  border: 3rpx solid #D32F2F;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 25rpx rgba(250, 53, 52, 0.3);
  transition: all 0.3s;
}

.delete-btn:active {
  transform: scale(0.98);
}

.submit-btn {
  flex: 2;
  height: 96rpx;
  background: linear-gradient(135deg, #C8956E, #F5D59E, #FFD700);
  color: #5D4037;
  border-radius: 50rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: 4rpx solid #5D4037;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 10rpx 30rpx rgba(200, 149, 110, 0.4);
  transition: all 0.3s;
}

.submit-btn:active {
  transform: scale(0.98);
}
</style>
