<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="switchType('income')">
            <text>收入</text>
          </view>
          <view class="type-tab" :class="{ active: form.type === 'expense' }" @click="switchType('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="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="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="selectRental" :class="{ disabled: !form.roomId }">
            <text class="item-label">关联租约</text>
            <view class="item-value">
              <text :class="{ placeholder: !selectedRental }">{{selectedRental ? selectedRental.tenantName : (form.roomId ? '请选择租约' : '请先选择房间')}}</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" @click="selectBillMonth">
            <text class="item-label">账单月份</text>
            <view class="item-value">
              <text :class="{ placeholder: !form.billMonth }">{{form.billMonth || '请选择账单月份'}}</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, rentalApi, settingApi } from '../../api/index.js'

  export default {
    data() {
      return {
        form: {
          type: 'income',
          receivableAmount: '',
          roomId: null,
          rentalId: null,
          category: '',
          billDate: this.formatDate(new Date()),
          billMonth: '',
          remark: ''
        },
        selectedRoom: null,
        selectedRental: null,
        rooms: [],
        roomRentals: [],
        incomeCategories: [],
        expenseCategories: []
      }
    },
    onLoad() {
      this.loadRooms()
      this.loadCategories()
      // 设置默认账单日期为本月最后一天
      const today = new Date()
      const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0)
      this.form.billDate = this.formatDate(lastDay)
      // 设置默认账单月份为当前月份
      this.form.billMonth = this.formatMonth(today)
    },
    methods: {
      // 切换类型
      switchType(type) {
        this.form.type = type
        this.form.category = ''
      },

      // 加载类目列表
      async loadCategories() {
        try {
          const res = await settingApi.getCategories()
          const categories = res.data || []
          this.incomeCategories = categories.filter(c => c.type === 'income')
          this.expenseCategories = categories.filter(c => c.type === 'expense')
        } catch (error) {
          console.error('加载类目列表失败:', error)
        }
      },

      // 加载房间列表
      async loadRooms() {
        try {
          const res = await roomApi.list()
          this.rooms = res.data || []
        } catch (error) {
          uni.showToast({ title: '加载房间列表失败', icon: 'none' })
        }
      },

      // 加载房间租约列表
      async loadRoomRentals(roomId) {
        try {
          const res = await rentalApi.getAll({ roomId, status: 'active' })
          this.roomRentals = res.data || []
        } catch (error) {
          console.error('加载租约列表失败:', error)
        }
      },

      async selectRoom() {
        if (this.rooms.length === 0) {
          uni.showToast({ title: '暂无房间数据', icon: 'none' })
          return
        }
        const roomList = this.rooms.map(r => (r.apartmentName || '') + ' - ' + r.roomNumber)
        uni.showActionSheet({
          itemList: roomList,
          success: (res) => {
            this.selectedRoom = this.rooms[res.tapIndex]
            this.form.roomId = this.selectedRoom.id
            // 清空租约选择
            this.selectedRental = null
            this.form.rentalId = null
            // 加载该房间的租约
            this.loadRoomRentals(this.form.roomId)
          }
        })
      },

      selectCategory() {
        const categories = this.form.type === 'income' ? this.incomeCategories : this.expenseCategories
        if (categories.length === 0) {
          uni.showToast({ title: '暂无类目数据', icon: 'none' })
          return
        }
        const categoryList = categories.map(c => c.name)
        uni.showActionSheet({
          itemList: categoryList,
          success: (res) => {
            this.form.category = categories[res.tapIndex].code
          }
        })
      },

      selectRental() {
        if (!this.form.roomId) {
          uni.showToast({ title: '请先选择房间', icon: 'none' })
          return
        }
        if (this.roomRentals.length === 0) {
          uni.showToast({ title: '该房间暂无租约', icon: 'none' })
          return
        }
        const rentalList = this.roomRentals.map(r => r.tenantName + ' (' + r.startDate + ' 至 ' + r.endDate + ')')
        uni.showActionSheet({
          itemList: rentalList,
          success: (res) => {
            this.selectedRental = this.roomRentals[res.tapIndex]
            this.form.rentalId = this.selectedRental.id
          }
        })
      },

      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 }
                }
              })
            }
          }
        })
      },

      selectBillMonth() {
        // 使用日期选择器选择月份
        const today = new Date()
        const currentYear = today.getFullYear()
        const years = [currentYear - 1, currentYear, currentYear + 1].map(String)
        const months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']

        uni.showActionSheet({
          itemList: years,
          title: '选择年份',
          success: (yearRes) => {
            const selectedYear = years[yearRes.tapIndex]
            uni.showActionSheet({
              itemList: months.map(m => selectedYear + '-' + m),
              title: '选择月份',
              success: (monthRes) => {
                this.form.billMonth = selectedYear + '-' + months[monthRes.tapIndex]
              }
            })
          }
        })
      },

      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
        }
        if (!this.form.billDate) {
          uni.showToast({ title: '请选择账单日期', icon: 'none' })
          return
        }

        try {
          uni.showLoading({ title: '保存中...' })
          const data = {
            ...this.form,
            receivableAmount: parseFloat(this.form.receivableAmount)
          }
          await billApi.create(data)
          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')}`
      },

      formatMonth(date) {
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
      },

      getCategoryText(code) {
        const allCategories = [...this.incomeCategories, ...this.expenseCategories]
        const category = allCategories.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; }
  .form-item.disabled { opacity: 0.6; }
  .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>
