﻿<template>
  <van-popup 
    v-model:show="visible" 
    position="bottom"
    :style="{ height: '85%' }"
    round
    closeable
    @update:show="handleVisibleChange"
  >
    <div class="transaction-detail" v-if="transaction">
      <div class="detail-header" style="margin-top: 10px;margin-left: 10px;">
        <h3>交易详情</h3>
      </div>
      
      <div class="scroll-area">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-cell title="卡号" :value="transaction.card" />
          <van-cell title="交易时间" :value="formatDate(transaction.occurredAt)" />
          <van-cell title="记录时间" :value="formatDate(transaction.createTime)" />
        </van-cell-group>

        <van-cell-group inset title="交易明细">
          <van-field
            v-model="editForm.reason"
            name="reason"
            label="交易摘要"
            placeholder="请输入交易摘要"
            type="textarea"
            rows="2"
            autosize
            maxlength="200"
            show-word-limit
          />
          <van-field
            v-model="editForm.amount"
            name="amount"
            label="交易金额"
            placeholder="请输入交易金额"
            type="number"
            :rules="[{ required: true, message: '请输入交易金额' }]"
          />
          <van-field
            v-model="editForm.balance"
            name="balance"
            label="交易后余额"
            placeholder="请输入交易后余额"
            type="number"
            :rules="[{ required: true, message: '请输入交易后余额' }]"
          />
          <van-field
            v-model="editForm.typeText"
            is-link
            readonly
            name="type"
            label="交易类型"
            placeholder="请选择交易类型"
            @click="showTypePicker = true"
            :rules="[{ required: true, message: '请选择交易类型' }]"
          />
          <van-field name="classify" label="交易分类">
            <template #input>
              <span v-if="!editForm.classify" style="color: #c8c9cc;">请选择交易分类</span>
              <span v-else>{{ editForm.classify }}</span>
            </template>
          </van-field>
          
          <!-- 分类按钮网格 -->
          <div class="classify-buttons">
            <van-button
              v-for="item in classifyColumns"
              :key="item.id"
              :type="editForm.classify === item.text ? 'primary' : 'default'"
              size="small"
              class="classify-btn"
              @click="selectClassify(item.text)"
            >
              {{ item.text }}
            </van-button>
            <van-button
              type="success"
              size="small"
              class="classify-btn"
              @click="showAddClassify = true"
            >
              + 新增
            </van-button>
            <van-button
              v-if="editForm.classify"
              type="warning"
              size="small"
              class="classify-btn"
              @click="clearClassify"
            >
              清空
            </van-button>
          </div>
        </van-cell-group>

        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit" :loading="submitting">
            保存修改
          </van-button>
        </div>
      </van-form>
      </div>
    </div>
  </van-popup>

  <!-- 交易类型选择器 -->
  <van-popup v-model:show="showTypePicker" position="bottom" round>
    <van-picker
      show-toolbar
      :columns="typeColumns"
      @confirm="onTypeConfirm"
      @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>
</template>

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

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

const emit = defineEmits(['update:show', 'save'])

const visible = ref(false)
const submitting = ref(false)

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

// 分类相关
const classifyColumns = ref([])
const showTypePicker = ref(false)
const showAddClassify = ref(false)
const newClassify = ref('')

// 编辑表单
const editForm = reactive({
  id: 0,
  reason: '',
  amount: '',
  balance: '',
  type: 0,
  typeText: '',
  classify: ''
})

// 监听props变化
watch(() => props.show, (newVal) => {
  visible.value = newVal
})

watch(() => props.transaction, (newVal) => {
  if (newVal) {
    // 填充编辑表单
    editForm.id = newVal.id
    editForm.reason = newVal.reason || ''
    editForm.amount = String(newVal.amount)
    editForm.balance = String(newVal.balance)
    editForm.type = newVal.type
    editForm.typeText = getTypeName(newVal.type)
    editForm.classify = newVal.classify || ''
    
    // 根据交易类型加载分类
    loadClassifyList(newVal.type)
  }
})

watch(visible, (newVal) => {
  emit('update:show', newVal)
})

// 监听交易类型变化，重新加载分类
watch(() => editForm.type, (newVal) => {
  // 清空已选的分类
  editForm.classify = ''
  // 重新加载对应类型的分类列表
  loadClassifyList(newVal)
})

const handleVisibleChange = (newVal) => {
  emit('update:show', newVal)
}

// 加载分类列表
const loadClassifyList = async (type = null) => {
  try {
    const response = await getCategoryList(type)
    if (response.success) {
      classifyColumns.value = (response.data || []).map(item => ({
        text: item.name,
        value: item.name,
        id: item.id
      }))
    }
  } catch (error) {
    console.error('加载分类列表出错:', error)
  }
}

// 提交编辑
const onSubmit = async () => {
  try {
    submitting.value = true
    
    const data = {
      id: editForm.id,
      reason: editForm.reason,
      amount: parseFloat(editForm.amount),
      balance: parseFloat(editForm.balance),
      type: editForm.type,
      classify: editForm.classify
    }
    
    const response = await updateTransaction(data)
    if (response.success) {
      showToast('保存成功')
      visible.value = false
      emit('save')
      // 重新加载分类列表
      await loadClassifyList(editForm.type)
    } else {
      showToast(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存出错:', error)
    showToast('保存失败')
  } finally {
    submitting.value = false
  }
}

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

// 交易类型选择确认
const onTypeConfirm = ({ selectedValues, selectedOptions }) => {
  editForm.type = selectedValues[0]
  editForm.typeText = selectedOptions[0].text
  showTypePicker.value = false
}

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

// 清空分类
const clearClassify = () => {
  editForm.classify = ''
  showToast('已清空分类')
}

// 获取交易类型名称
const getTypeName = (type) => {
  const typeMap = {
    0: '支出',
    1: '收入',
    2: '不计入收支'
  }
  return typeMap[type] || '未知'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

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

.detail-header {
  flex-shrink: 0;
  border-bottom: 1px solid #ebedf0;
}

.detail-header h3 {
  margin: 10px 0;
}

.scroll-area {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 20px;
}

.classify-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 12px 16px;
}

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