﻿<template>
  <van-popup 
    v-model:show="visible" 
    position="bottom" 
    :style="{ height: '70%' }"
    round
    closeable
    @closed="handleClosed"
  >
    <div class="transaction-detail-dialog">
      <div class="dialog-header">
        <h3 class="dialog-title">账单详情</h3>
      </div>

      <div class="dialog-content">
        <van-form ref="formRef">
          <van-cell-group inset>
            <!-- 交易摘要 -->
            <van-field
              :model-value="formData.reason"
              label="交易摘要"
              readonly
              input-align="left"
            />

            <!-- 交易时间 -->
            <van-field
              :model-value="formatDateTime(formData.occurredAt)"
              label="交易时间"
              readonly
              input-align="left"
            />

            <!-- 卡号 -->
            <van-field
              v-if="formData.card"
              :model-value="formData.card"
              label="卡号"
              readonly
              input-align="left"
            />

            <!-- 交易金额 -->
            <van-field
              v-model.number="formData.amount"
              label="交易金额"
              type="number"
              placeholder="请输入金额"
              input-align="left"
              :rules="[{ required: true, message: '请输入交易金额' }]"
            />

            <!-- 交易后余额 -->
            <van-field
              v-model.number="formData.balance"
              label="交易后余额"
              type="number"
              placeholder="请输入余额"
              input-align="left"
            />

            <!-- 交易类型 -->
            <van-field
              v-model="typeText"
              is-link
              readonly
              label="交易类型"
              placeholder="请选择交易类型"
              @click="showTypePicker = true"
              :rules="[{ required: true, message: '请选择交易类型' }]"
            />

            <!-- 分类选择 -->
            <van-field label="分类">
              <template #input>
                <span v-if="!formData.classify" style="opacity: 0.4;">请选择分类</span>
                <span v-else>{{ formData.classify }}</span>
              </template>
            </van-field>
            
            <!-- 分类按钮网格 -->
            <div class="classify-buttons">
              <van-button
                v-for="item in classifyOptions"
                :key="item.id"
                :type="formData.classify === item.name ? 'primary' : 'default'"
                size="small"
                class="classify-btn"
                @click="selectClassify(item.name)"
              >
                {{ item.name }}
              </van-button>
              <van-button
                type="success"
                size="small"
                class="classify-btn"
                @click="showAddClassify = true"
              >
                + 新增
              </van-button>
              <van-button
                v-if="formData.classify"
                type="warning"
                size="small"
                class="classify-btn"
                @click="clearClassify"
              >
                清空
              </van-button>
            </div>
          </van-cell-group>
        </van-form>
      </div>

      <div class="dialog-footer">
        <van-button 
          type="primary" 
          block 
          :loading="saving"
          @click="handleSave"
        >
          保存
        </van-button>
      </div>
    </div>

    <!-- 交易类型选择器 -->
    <van-popup v-model:show="showTypePicker" position="bottom" round>
      <van-picker
        show-toolbar
        :columns="typeOptions"
        @confirm="handleConfirmType"
        @cancel="showTypePicker = false"
      />
    </van-popup>

    <!-- 新增分类对话框 -->
    <van-dialog 
      v-model:show="showAddClassify" 
      title="新增交易分类" 
      show-cancel-button
      @confirm="addNewClassify"
    >
      <van-field v-model="newClassify" placeholder="请输入新的交易分类" />
    </van-dialog>
  </van-popup>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { showToast, showSuccessToast } from 'vant'
import { updateTransaction } from '@/api/transactionRecord'
import { getCategoryList, createCategory } from '@/api/transactionCategory'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  transaction: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'saved'])

const visible = ref(props.modelValue)
const formRef = ref(null)
const saving = ref(false)
const showTypePicker = ref(false)
const showAddClassify = ref(false)
const newClassify = ref('')
const categories = ref([])

// 交易类型选项
const typeOptions = [
  { text: '支出', value: 0 },
  { text: '收入', value: 1 },
  { text: '不计收支', value: 2 }
]

// 表单数据
const formData = ref({
  id: null,
  reason: '',
  occurredAt: '',
  card: '',
  amount: 0,
  balance: 0,
  type: 0,
  classify: ''
})

// 类型文本
const typeText = computed(() => {
  const option = typeOptions.find(o => o.value === formData.value.type)
  return option?.text || ''
})

// 根据选中的类型过滤分类选项
const classifyOptions = computed(() => {
  return categories.value.filter(c => c.type === formData.value.type)
})

// 监听modelValue变化
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val && props.transaction) {
    initFormData()
    loadCategories()
  }
})

// 监听visible变化
watch(visible, (val) => {
  emit('update:modelValue', val)
})

// 监听交易类型变化
watch(() => formData.value.type, () => {
  // 清空已选的分类（如果当前分类不属于新类型）
  const hasCurrentClassify = classifyOptions.value.some(
    c => c.name === formData.value.classify
  )
  if (!hasCurrentClassify) {
    formData.value.classify = ''
  }
})

// 初始化表单数据
const initFormData = () => {
  if (props.transaction) {
    formData.value = {
      id: props.transaction.id,
      reason: props.transaction.reason || '',
      occurredAt: props.transaction.occurredAt || '',
      card: props.transaction.card || '',
      amount: props.transaction.amount || 0,
      balance: props.transaction.balance || 0,
      type: props.transaction.type ?? 0,
      classify: props.transaction.classify || ''
    }
  }
}

// 加载分类列表
const loadCategories = async () => {
  try {
    const res = await getCategoryList()
    if (res.success) {
      categories.value = res.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 选择分类
const selectClassify = (classify) => {
  formData.value.classify = classify
}

// 确认选择交易类型
const handleConfirmType = ({ selectedOptions }) => {
  formData.value.type = selectedOptions[0].value
  showTypePicker.value = false
}

// 新增分类
const addNewClassify = async () => {
  if (!newClassify.value.trim()) {
    showToast('请输入分类名称')
    return
  }
  
  try {
    const categoryName = newClassify.value.trim()
    
    const response = await createCategory({
      name: categoryName,
      type: formData.value.type
    })
    
    if (response.success) {
      showToast('分类创建成功')
      await loadCategories()
      formData.value.classify = categoryName
    } else {
      showToast(response.message || '创建分类失败')
    }
  } catch (error) {
    console.error('创建分类出错:', error)
    showToast('创建分类失败')
  } finally {
    newClassify.value = ''
    showAddClassify.value = false
  }
}

// 清空分类
const clearClassify = () => {
  formData.value.classify = ''
}

// 保存
const handleSave = async () => {
  try {
    await formRef.value?.validate()
    
    saving.value = true
    
    const res = await updateTransaction({
      id: formData.value.id,
      amount: formData.value.amount,
      balance: formData.value.balance,
      type: formData.value.type,
      classify: formData.value.classify || ''
    })
    
    if (res.success) {
      showSuccessToast('保存成功')
      visible.value = false
      emit('saved', formData.value)
    } else {
      showToast(res.message || '保存失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存失败:', error)
      showToast(error.message || '保存失败')
    }
  } finally {
    saving.value = false
  }
}

// 处理弹窗关闭
const handleClosed = () => {
  formRef.value?.resetValidation()
}
</script>

<style scoped>
.transaction-detail-dialog {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.dialog-header {
  padding: 20px 16px 12px;
  border-bottom: 1px solid var(--van-border-color, #ebedf0);
}

.dialog-title {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  text-align: center;
}

.dialog-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px 0;
}

.dialog-footer {
  padding: 12px 16px;
  padding-bottom: calc(12px + env(safe-area-inset-bottom, 0px));
  border-top: 1px solid var(--van-border-color, #ebedf0);
}

.classify-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 12px 16px;
  max-height: 200px;
  overflow-y: auto;
}

.classify-btn {
  flex: 0 0 auto;
  min-width: 70px;
  border-radius: 16px;
}

@media (prefers-color-scheme: dark) {
  .dialog-header,
  .dialog-footer {
    border-color: var(--van-border-color, #3a3a3a);
  }
}
</style>
