﻿<template>
  <div class="page-container-flex periodic-record">
    <van-nav-bar 
      :title="navTitle" 
      left-text="返回"
      left-arrow
      placeholder 
      @click-left="handleBack"
    />

    <!-- 下拉刷新区域 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <!-- 加载提示 -->
      <van-loading v-if="loading && !periodicList.length" vertical style="padding: 50px 0">
        加载中...
      </van-loading>

      <!-- 周期性账单列表 -->
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        class="periodic-list"
        @load="onLoad"
      >
        <van-cell-group v-for="item in periodicList" :key="item.id" inset class="periodic-item">
          <van-swipe-cell>
            <div @click="editPeriodic(item)">
              <van-cell :title="item.reason || '无摘要'" :label="getPeriodicTypeText(item)">
                <template #value>
                  <div class="amount-info">
                    <span :class="['amount', item.type === 1 ? 'income' : 'expense']">
                      {{ item.type === 1 ? '+' : '-' }}{{ item.amount.toFixed(2) }}
                    </span>
                  </div>
                </template>
              </van-cell>
              <van-cell title="分类" :value="item.classify || '未分类'" />
              <van-cell title="下次执行时间" :value="formatDateTime(item.nextExecuteTime) || '未设置'" />
              <van-cell title="状态">
                <template #value>
                  <van-switch 
                    :model-value="item.isEnabled" 
                    size="20px"
                    @update:model-value="(val) => toggleEnabled(item.id, val)"
                    @click.stop
                  />
                </template>
              </van-cell>
            </div>
            <template #right>
              <van-button 
                square
                type="danger" 
                text="删除"
                class="delete-button"
                @click="deletePeriodic(item)"
              />
            </template>
          </van-swipe-cell>
        </van-cell-group>

        <!-- 空状态 -->
        <van-empty 
          v-if="!loading && !periodicList.length" 
          description="暂无周期性账单"
          image="search"
        />
      </van-list>

      <!-- 底部安全距离 -->
      <div style="height: calc(50px + env(safe-area-inset-bottom, 0px))"></div>
    </van-pull-refresh>

    <!-- 底部新增按钮 -->
    <div class="bottom-button">
      <van-button 
        type="primary" 
        size="large" 
        round 
        icon="plus"
        @click="openAddDialog"
      >
        新增周期账单
      </van-button>
    </div>

    <!-- 新增/编辑弹窗 -->
    <PopupContainer
      v-model="dialogVisible"
      :title="isEdit ? '编辑周期账单' : '新增周期账单'"
      height="75%"
    >
      <van-form>
        <van-cell-group inset title="周期设置">
            <van-field
              v-model="form.periodicTypeText"
              is-link
              readonly
              name="periodicType"
              label="周期"
              placeholder="请选择周期类型"
              :rules="[{ required: true, message: '请选择周期类型' }]"
              @click="showPeriodicTypePicker = true"
            />

            <!-- 每周配置 -->
            <van-field
              v-if="form.periodicType === 1"
              v-model="form.weekdaysText"
              is-link
              readonly
              name="weekdays"
              label="星期"
              placeholder="请选择星期几"
              :rules="[{ required: true, message: '请选择星期几' }]"
              @click="showWeekdaysPicker = true"
            />

            <!-- 每月配置 -->
            <van-field
              v-if="form.periodicType === 2"
              v-model="form.monthDaysText"
              is-link
              readonly
              name="monthDays"
              label="日期"
              placeholder="请选择每月的日期"
              :rules="[{ required: true, message: '请选择日期' }]"
              @click="showMonthDaysPicker = true"
            />

            <!-- 每季度配置 -->
            <van-field
              v-if="form.periodicType === 3"
              v-model="form.quarterDay"
              name="quarterDay"
              label="季度第几天"
              placeholder="请输入季度开始后第几天"
              type="number"
              :rules="[{ required: true, message: '请输入季度开始后第几天' }]"
            />

            <!-- 每年配置 -->
            <van-field
              v-if="form.periodicType === 4"
              v-model="form.yearDay"
              name="yearDay"
              label="年第几天"
              placeholder="请输入年开始后第几天"
              type="number"
              :rules="[{ required: true, message: '请输入年开始后第几天' }]"
            />
        </van-cell-group>

        <van-cell-group inset title="基本信息">
            <van-field
              v-model="form.reason"
              name="reason"
              label="摘要"
              placeholder="请输入交易摘要"
              type="textarea"
              rows="2"
              autosize
              maxlength="200"
              show-word-limit
            />
            <van-field
              v-model="form.amount"
              name="amount"
              label="金额"
              placeholder="请输入金额"
              type="number"
              :rules="[{ required: true, message: '请输入金额' }]"
            />
            <van-field
              v-model="form.type"
              name="type"
              label="类型"
            >
              <template #input>
                <van-radio-group v-model="form.type" direction="horizontal">
                  <van-radio :name="0">支出</van-radio>
                  <van-radio :name="1">收入</van-radio>
                  <van-radio :name="2">不计</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            <van-field name="classify" label="分类">
              <template #input>
                <span v-if="!form.classify" style="color: var(--van-gray-5);">请选择交易分类</span>
                <span v-else>{{ form.classify }}</span>
              </template>
            </van-field>
            
            <!-- 分类选择组件 -->
            <ClassifySelector
              v-model="form.classify"
              :type="form.type"
            />
        </van-cell-group>
      </van-form>
      <template #footer>
        <van-button round block type="primary" :loading="submitting" @click="submit">
          {{ isEdit ? '更新' : '确认添加' }}
        </van-button>
      </template>
    </PopupContainer>

    <!-- 周期类型选择器 -->
    <van-popup v-model:show="showPeriodicTypePicker" position="bottom" round teleport="body">
      <van-picker
        :columns="periodicTypeColumns"
        @confirm="onPeriodicTypeConfirm"
        @cancel="showPeriodicTypePicker = false"
      />
    </van-popup>

    <!-- 星期选择器 -->
    <van-popup v-model:show="showWeekdaysPicker" position="bottom" round teleport="body">
      <van-picker
        :columns="weekdaysColumns"
        @confirm="onWeekdaysConfirm"
        @cancel="showWeekdaysPicker = false"
      />
    </van-popup>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showMonthDaysPicker" position="bottom" round teleport="body">
      <van-picker
        :columns="monthDaysColumns"
        @confirm="onMonthDaysConfirm"
        @cancel="showMonthDaysPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { 
  getPeriodicList, 
  deletePeriodic as deletePeriodicApi,
  togglePeriodicEnabled
} from '@/api/transactionPeriodic'
import PopupContainer from '@/components/PopupContainer.vue'
import ClassifySelector from '@/components/ClassifySelector.vue'
import dayjs from 'dayjs'

const router = useRouter()
const navTitle = ref('周期账单')

const periodicList = ref([])
const loading = ref(false)
const refreshing = ref(false)
const finished = ref(false)
const pageIndex = ref(1)
const pageSize = 20
const total = ref(0)

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const showPeriodicTypePicker = ref(false)
const showWeekdaysPicker = ref(false)
const showMonthDaysPicker = ref(false)

// 周期类型
const periodicTypeColumns = [
  { text: '每天', value: 0 },
  { text: '每周', value: 1 },
  { text: '每月', value: 2 },
  { text: '每季度', value: 3 },
  { text: '每年', value: 4 }
]

// 星期
const weekdaysColumns = [
  { text: '周日', value: 0 },
  { text: '周一', value: 1 },
  { text: '周二', value: 2 },
  { text: '周三', value: 3 },
  { text: '周四', value: 4 },
  { text: '周五', value: 5 },
  { text: '周六', value: 6 }
]

// 月份日期
const monthDaysColumns = Array.from({ length: 31 }, (_, i) => ({
  text: `${i + 1}日`,
  value: i + 1
}))

// 表单数据
const form = reactive({
  id: null,
  reason: '',
  amount: '',
  type: 0,
  classify: '',
  periodicType: 0,
  periodicTypeText: '',
  periodicConfig: '',
  // 每周
  weekdays: [],
  weekdaysText: '',
  // 每月
  monthDays: [],
  monthDaysText: '',
  // 每季度
  quarterDay: '',
  // 每年
  yearDay: ''
})

// 加载数据
const loadData = async (isRefresh = false) => {
  if (isRefresh) {
    pageIndex.value = 1
    periodicList.value = []
    finished.value = false
  }

  loading.value = true
  try {
    const params = {
      pageIndex: pageIndex.value,
      pageSize: pageSize
    }
    
    const response = await getPeriodicList(params)
    
    if (response.success) {
      const newList = response.data || []
      total.value = response.total || 0
      
      if (isRefresh) {
        periodicList.value = newList
      } else {
        periodicList.value = [...periodicList.value, ...newList]
      }
      
      if (newList.length === 0 || newList.length < pageSize) {
        finished.value = true
      } else {
        finished.value = false
        pageIndex.value++
      }
    } else {
      showToast(response.message || '加载数据失败')
      finished.value = true
    }
  } catch (error) {
    console.error('加载数据出错:', error)
    showToast('加载数据出错')
    finished.value = true
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  loadData(true)
}

// 加载更多
const onLoad = () => {
  loadData(false)
}

// 返回上一页
const handleBack = () => {
  router.back()
}

// 获取周期类型文本
const getPeriodicTypeText = (item) => {
  const typeMap = {
    0: '每天',
    1: '每周',
    2: '每月',
    3: '每季度',
    4: '每年'
  }
  
  let text = typeMap[item.periodicType] || '未知'
  
  if (item.periodicConfig) {
    switch (item.periodicType) {
      case 1: // 每周
        { 
          const weekdays = item.periodicConfig.split(',').map(
            d => {
              const dayMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
              return dayMap[parseInt(d)] || ''
            }).join('、')
          text += ` (${weekdays})`
          break 
        }
      case 2: // 每月
        { 
          const days = item.periodicConfig.split(',').join('、')
          text += ` (${days}日)`
          break 
        }
      case 3: // 每季度
        text += ` (第${item.periodicConfig}天)`
        break
      case 4: // 每年
        text += ` (第${item.periodicConfig}天)`
        break
    }
  }
  
  return text
}

// 打开新增弹窗
const openAddDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑
const editPeriodic = (item) => {
  isEdit.value = true
  form.id = item.id
  form.reason = item.reason
  form.amount = item.amount.toString()
  form.type = item.type
  form.classify = item.classify
  form.periodicType = item.periodicType
  form.periodicTypeText = periodicTypeColumns.find(t => t.value === item.periodicType)?.text || ''
  
  // 解析周期配置
  if (item.periodicConfig) {
    switch (item.periodicType) {
      case 1: // 每周
        form.weekdays = item.periodicConfig.split(',').map(d => parseInt(d))
        form.weekdaysText = form.weekdays.map(d => {
          return weekdaysColumns.find(w => w.value === d)?.text || ''
        }).join('、')
        break
      case 2: // 每月
        form.monthDays = item.periodicConfig.split(',').map(d => parseInt(d))
        form.monthDaysText = form.monthDays.map(d => `${d}日`).join('、')
        break
      case 3: // 每季度
        form.quarterDay = item.periodicConfig
        break
      case 4: // 每年
        form.yearDay = item.periodicConfig
        break
    }
  }
  
  dialogVisible.value = true
}

// 删除
const deletePeriodic = async (item) => {
  try {
    await showConfirmDialog({
      title: '提示',
      message: '确定要删除这条周期性账单吗？',
    })

    const response = await deletePeriodicApi(item.id)
    if (response.success) {
      showToast('删除成功')
      loadData(true)
    } else {
      showToast(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除出错:', error)
      showToast('删除失败')
    }
  }
}

// 启用/禁用
const toggleEnabled = async (id, enabled) => {
  try {
    const response = await togglePeriodicEnabled(id, enabled)
    if (response.success) {
      showToast(enabled ? '已启用' : '已禁用')
      // 更新本地数据
      const item = periodicList.value.find(p => p.id === id)
      if (item) {
        item.isEnabled = enabled
      }
    } else {
      showToast(response.message || '操作失败')
      // 恢复状态
      loadData(true)
    }
  } catch (error) {
    console.error('操作失败:', error)
    showToast('操作失败')
    loadData(true)
  }
}

const formatDateTime = (date) => {
  if (!date) return ''

  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.reason = ''
  form.amount = ''
  form.type = 0
  form.classify = ''
  form.periodicType = 0
  form.periodicTypeText = ''
  form.periodicConfig = ''
  form.weekdays = []
  form.weekdaysText = ''
  form.monthDays = []
  form.monthDaysText = ''
  form.quarterDay = ''
  form.yearDay = ''
}

const onPeriodicTypeConfirm = ({ selectedValues, selectedOptions }) => {
  form.periodicType = selectedValues[0]
  form.periodicTypeText = selectedOptions[0].text
  // 清空之前的配置
  form.weekdays = []
  form.weekdaysText = ''
  form.monthDays = []
  form.monthDaysText = ''
  form.quarterDay = ''
  form.yearDay = ''
  showPeriodicTypePicker.value = false
}

const onWeekdaysConfirm = ({ selectedValues, selectedOptions }) => {
  form.weekdays = [selectedValues[0]]
  form.weekdaysText = selectedOptions[0].text
  showWeekdaysPicker.value = false
}

const onMonthDaysConfirm = ({ selectedValues, selectedOptions }) => {
  form.monthDays = [selectedValues[0]]
  form.monthDaysText = selectedOptions[0].text
  showMonthDaysPicker.value = false
}

</script>

<style scoped>
.periodic-record {
  background: var(--van-background);
}

.periodic-list {
  padding: 16px 0;
}

.periodic-item {
  margin-bottom: 16px;
}

.amount-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.amount {
  font-size: 18px;
  font-weight: bold;
}

.amount.income {
  color: var(--van-success-color);
}

.amount.expense {
  color: var(--van-danger-color);
}

.delete-button {
  height: 100%;
}

</style>
