<template>
  <view class="bill-add-page">
    <view class="custom-nav safe-area-top">
      <view class="nav-content">
        <view class="nav-back" @click="goBack">
          <uni-icons type="left" size="20" color="#1E293B"></uni-icons>
        </view>
        <text class="nav-title">记一笔</text>
        <view class="nav-actions">
          <view class="nav-btn" @click="save">
            <text class="save-text">保存</text>
          </view>
        </view>
      </view>
    </view>

    <scroll-view scroll-y class="page-content">
      <!-- 类型选择 -->
      <view class="type-section">
        <view class="type-tabs">
          <view class="type-tab" :class="{ active: form.type === 'income' }" @click="form.type = 'income'">
            <text>收入</text>
          </view>
          <view class="type-tab" :class="{ active: form.type === 'expense' }" @click="form.type = 'expense'">
            <text>支出</text>
          </view>
        </view>
      </view>

      <!-- 金额输入 -->
      <view class="amount-section">
        <text class="amount-label">金额</text>
        <view class="amount-input">
          <text class="currency">¥</text>
          <input type="digit" v-model="form.receivableAmount" placeholder="0.00" class="amount-field"/>
        </view>
      </view>

      <!-- 表单信息 -->
      <view class="form-section">
        <view class="form-card">
          <view class="form-item" @click="selectRoom">
            <text class="item-label">关联房间</text>
            <view class="item-value">
              <text :class="{ placeholder: !selectedRoom }">{{selectedRoom ? selectedRoom.roomNumber : '请选择房间'}}</text>
              <uni-icons type="right" size="16" color="#94A3B8"></uni-icons>
            </view>
          </view>
          <view class="form-item" @click="selectCategory">
            <text class="item-label required">收支类目</text>
            <view class="item-value">
              <text :class="{ placeholder: !form.category }">{{form.category ? getCategoryText(form.category) : '请选择类目'}}</text>
              <uni-icons type="right" size="16" color="#94A3B8"></uni-icons>
            </view>
          </view>
          <view class="form-item" @click="selectDate">
            <text class="item-label required">账单日期</text>
            <view class="item-value">
              <text>{{form.billDate}}</text>
              <uni-icons type="right" size="16" color="#94A3B8"></uni-icons>
            </view>
          </view>
          <view class="form-item">
            <text class="item-label">备注</text>
            <input type="text" v-model="form.remark" placeholder="请输入备注" class="item-input"/>
          </view>
        </view>
      </view>

      <view class="safe-area-bottom" style="height: 40rpx;"></view>
    </scroll-view>
  </view>
</template>

<script>
  import { billApi, roomApi } from '../../api/index.js'

  export default {
    data() {
      return {
        form: {
          type: 'income',
          receivableAmount: '',
          roomId: '',
          category: '',
          billDate: this.formatDate(new Date()),
          remark: ''
        },
        selectedRoom: null,
        categories: [
          { code: 'rent', name: '租金', type: 'income' },
          { code: 'deposit', name: '押金', type: 'income' },
          { code: 'water', name: '水费', type: 'income' },
          { code: 'electricity', name: '电费', type: 'income' },
          { code: 'maintenance', name: '维修费', type: 'expense' },
          { code: 'property', name: '物业费', type: 'expense' },
          { code: 'other', name: '其他', type: 'all' }
        ]
      }
    },
    methods: {
      async selectRoom() {
        try {
          const res = await roomApi.list()
          const rooms = res.data || []
          if (rooms.length === 0) {
            uni.showToast({ title: '暂无房间数据', icon: 'none' })
            return
          }
          const roomList = rooms.map(r => r.roomNumber)
          uni.showActionSheet({
            itemList: roomList,
            success: (res) => {
              this.selectedRoom = rooms[res.tapIndex]
              this.form.roomId = this.selectedRoom.id
            }
          })
        } catch (error) {
          uni.showToast({ title: '加载房间失败', icon: 'none' })
        }
      },
      selectCategory() {
        const filteredCategories = this.categories.filter(c => c.type === this.form.type || c.type === 'all')
        const categoryList = filteredCategories.map(c => c.name)
        uni.showActionSheet({
          itemList: categoryList,
          success: (res) => {
            this.form.category = filteredCategories[res.tapIndex].code
          }
        })
      },
      selectDate() {
        uni.showActionSheet({
          itemList: ['今天', '昨天', '自定义'],
          success: (res) => {
            const today = new Date()
            if (res.tapIndex === 0) {
              this.form.billDate = this.formatDate(today)
            } else if (res.tapIndex === 1) {
              const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)
              this.form.billDate = this.formatDate(yesterday)
            } else {
              uni.navigateTo({
                url: '/pages/calendar/calendar',
                events: {
                  selectDate: (date) => { this.form.billDate = date }
                }
              })
            }
          }
        })
      },
      async save() {
        if (!this.form.receivableAmount || parseFloat(this.form.receivableAmount) <= 0) {
          uni.showToast({ title: '请输入金额', icon: 'none' })
          return
        }
        if (!this.form.category) {
          uni.showToast({ title: '请选择类目', icon: 'none' })
          return
        }
        try {
          uni.showLoading({ title: '保存中...' })
          await billApi.create(this.form)
          uni.showToast({ title: '保存成功', icon: 'success' })
          setTimeout(() => { uni.navigateBack() }, 1500)
        } catch (error) {
          uni.showToast({ title: '保存失败', icon: 'none' })
        } finally {
          uni.hideLoading()
        }
      },
      goBack() { uni.navigateBack() },
      formatDate(date) {
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
      },
      getCategoryText(code) {
        const category = this.categories.find(c => c.code === code)
        return category ? category.name : code
      }
    }
  }
</script>

<style scoped>
  .bill-add-page { min-height: 100vh; background: #F8FAFC; display: flex; flex-direction: column; }
  .custom-nav { background: #FFFFFF; border-bottom: 2rpx solid #F1F5F9; }
  .nav-content { display: flex; align-items: center; justify-content: space-between; padding: 20rpx 32rpx; }
  .nav-back { width: 60rpx; height: 60rpx; display: flex; align-items: center; justify-content: center; }
  .nav-title { font-size: 36rpx; font-weight: 700; color: #1E293B; }
  .nav-actions { width: 80rpx; display: flex; align-items: center; justify-content: flex-end; }
  .save-text { font-size: 30rpx; color: #2563EB; font-weight: 600; }
  .page-content { flex: 1; padding: 24rpx 32rpx; }
  .type-section { margin-bottom: 32rpx; }
  .type-tabs { display: flex; background: #FFFFFF; border-radius: 16rpx; padding: 8rpx; }
  .type-tab { flex: 1; text-align: center; padding: 24rpx 0; font-size: 30rpx; color: #64748B; border-radius: 12rpx; }
  .type-tab.active { background: #2563EB; color: #FFFFFF; font-weight: 600; }
  .amount-section { background: #FFFFFF; border-radius: 24rpx; padding: 40rpx 32rpx; margin-bottom: 32rpx; box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.04); }
  .amount-label { font-size: 28rpx; color: #64748B; margin-bottom: 24rpx; display: block; }
  .amount-input { display: flex; align-items: center; gap: 16rpx; }
  .currency { font-size: 48rpx; font-weight: 700; color: #1E293B; }
  .amount-field { flex: 1; font-size: 64rpx; font-weight: 700; color: #1E293B; }
  .form-section { margin-bottom: 32rpx; }
  .form-card { background: #FFFFFF; border-radius: 24rpx; overflow: hidden; box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.04); }
  .form-item { display: flex; align-items: center; justify-content: space-between; padding: 28rpx 32rpx; border-bottom: 2rpx solid #F8FAFC; }
  .form-item:last-child { border-bottom: none; }
  .item-label { font-size: 30rpx; color: #1E293B; font-weight: 500; }
  .item-label.required::after { content: '*'; color: #EF4444; margin-left: 8rpx; }
  .item-value { display: flex; align-items: center; gap: 16rpx; font-size: 30rpx; color: #1E293B; }
  .item-value .placeholder { color: #94A3B8; }
  .item-input { flex: 1; font-size: 30rpx; color: #1E293B; text-align: right; }
</style>
