<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" v-model="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));
}

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

.form-card {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
}

.form-header {
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.form-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

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

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

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

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

.type-option-compact {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 15rpx 30rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s;
  min-width: 120rpx;
}

.type-option-compact.active {
  background: #f0f7ff;
  border-color: #667eea;
}

.type-icon-compact {
  font-size: 32rpx;
  margin-bottom: 5rpx;
}

.type-text-compact {
  font-size: 24rpx;
  color: #333;
}

.type-option-compact.active .type-text-compact {
  color: #667eea;
  font-weight: bold;
}

.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: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: #f8f8f8;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8rpx;
  border: 3rpx solid transparent;
  transition: all 0.3s;
}

.category-icon-item.active .category-icon-circle {
  background: #f0f7ff;
  border-color: #667eea;
  transform: scale(1.1);
}

.category-icon-emoji {
  font-size: 48rpx;
  line-height: 1;
}

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

.category-icon-item.active .category-icon-name {
  color: #667eea;
  font-weight: bold;
}

.category-empty {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 26rpx;
}

.input, .textarea {
  width: 100%;
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  border: none;
  outline: none;
  -webkit-appearance: none;
  -webkit-tap-highlight-color: transparent;
  pointer-events: auto;
  user-select: text;
  -webkit-user-select: text;
}

.textarea {
  min-height: 200rpx;
}

.picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
}

.arrow {
  color: #999;
}

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

.delete-btn {
  flex: 1;
  height: 88rpx;
  background: #fa3534;
  color: #fff;
  border-radius: 12rpx;
  font-size: 28rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

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