<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { financeRecordApi } from '@/api/finance.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增收支记录')
const submitLoading = ref(false)
const auditVisible = ref(false)
const currentRecord = ref(null)
const isEdit = ref(false)

const searchForm = reactive({ type: '', audit_status: '', record_no: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({
  id: null, record_no: '', type: '', category_id: '',
  amount: 0, pay_method: '', description: '', record_date: ''
})
const formRules = {
  record_no: [{ required: true, message: '请输入记录编号', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
  record_date: [{ required: true, message: '请选择日期', trigger: 'change' }]
}

const auditForm = reactive({ status: 1, audit_remark: '' })

const typeMap = { 1: '收入', 2: '支出' }
const typeType = { 1: 'success', 2: 'danger' }
const auditMap = { 0: '待审核', 1: '已通过', 2: '已驳回' }
const auditType = { 0: 'warning', 1: 'success', 2: 'danger' }
const payMethodMap = { 1: '现金', 2: '微信', 3: '支付宝', 4: '银行转账' }

async function fetchList() {
  loading.value = true
  try {
    const res = await financeRecordApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } finally { loading.value = false }
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() { Object.assign(searchForm, { type: '', audit_status: '', record_no: '' }); handleSearch() }

function handleAdd() {
  isEdit.value = false; dialogTitle.value = '新增收支记录'
  Object.assign(form, { id: null, record_no: '', type: '', category_id: '', amount: 0, pay_method: '', description: '', record_date: '' })
  dialogVisible.value = true
}

async function handleEdit(row) {
  if (row.audit_status !== 0) { ElMessage.warning('只能编辑待审核记录'); return }
  isEdit.value = true; dialogTitle.value = '编辑收支记录'
  const res = await financeRecordApi.getDetail(row.id)
  const d = res.data
  Object.assign(form, {
    id: d.id, record_no: d.record_no, type: d.type, category_id: d.category_id || '',
    amount: d.amount, pay_method: d.pay_method || '', description: d.description || '', record_date: d.record_date || ''
  })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) { await financeRecordApi.update(form.id, form); ElMessage.success('更新成功') }
      else { await financeRecordApi.create(form); ElMessage.success('创建成功') }
      dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleDelete(row) {
  if (row.audit_status !== 0) { ElMessage.warning('只能删除待审核记录'); return }
  await ElMessageBox.confirm('确定删除该收支记录吗？', '删除确认', { type: 'warning' })
  await financeRecordApi.delete(row.id); ElMessage.success('删除成功'); fetchList()
}

function openAudit(row) {
  currentRecord.value = row
  Object.assign(auditForm, { status: 1, audit_remark: '' })
  auditVisible.value = true
}

async function submitAudit() {
  await financeRecordApi.audit(currentRecord.value.id, auditForm)
  ElMessage.success('审核完成')
  auditVisible.value = false; fetchList()
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }

onMounted(() => { fetchList() })
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-select v-model="searchForm.type" placeholder="收支类型" clearable style="width:120px">
        <el-option v-for="(v, k) in typeMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-select v-model="searchForm.audit_status" placeholder="审核状态" clearable style="width:120px">
        <el-option v-for="(v, k) in auditMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-input v-model="searchForm.record_no" placeholder="记录编号" style="width:180px" clearable @keydown.enter="handleSearch" />
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3">
          <span class="font-medium text-gray-700">收支记录列表</span>
        </div>
        <el-button type="primary" @click="handleAdd">新增记录</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column prop="record_no" label="记录编号" min-width="150" />
          <el-table-column label="类型" width="90" align="center">
            <template #default="{ row }"><el-tag :type="typeType[row.type]" size="small">{{ typeMap[row.type] || '-' }}</el-tag></template>
          </el-table-column>
          <el-table-column prop="category" label="分类" min-width="120">
            <template #default="{ row }">{{ row.category?.name || row.category || '-' }}</template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" min-width="110" align="right" />
          <el-table-column label="支付方式" width="110" align="center">
            <template #default="{ row }">{{ payMethodMap[row.pay_method] || '-' }}</template>
          </el-table-column>
          <el-table-column label="审核状态" width="100" align="center">
            <template #default="{ row }"><el-tag :type="auditType[row.audit_status]" size="small">{{ auditMap[row.audit_status] }}</el-tag></template>
          </el-table-column>
          <el-table-column prop="record_date" label="记录日期" min-width="120" />
          <el-table-column label="操作" width="220" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="row.audit_status===0" size="small" type="success" text @click="openAudit(row)">审核</el-button>
              <el-button v-if="row.audit_status===0" size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button v-if="row.audit_status===0" size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
              <span v-if="row.audit_status!==0" class="text-muted">-</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.per_page" :total="total" :page-sizes="[10,20,50]" layout="total,sizes,prev,pager,next,jumper" background @current-change="handlePageChange" @size-change="handleSizeChange" />
      </div>
    </div>

    <!-- Add/Edit -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="650px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="记录编号" prop="record_no">
              <el-input v-model="form.record_no" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="选择类型" style="width:100%">
                <el-option v-for="(v, k) in typeMap" :key="k" :label="v" :value="Number(k)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类">
              <el-input v-model="form.category_id" placeholder="分类ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="amount">
              <el-input-number v-model="form.amount" :min="0" :precision="2" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付方式">
              <el-select v-model="form.pay_method" placeholder="选择支付方式" clearable style="width:100%">
                <el-option v-for="(v, k) in payMethodMap" :key="k" :label="v" :value="Number(k)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="记录日期" prop="record_date">
              <el-date-picker v-model="form.record_date" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述">
              <el-input v-model="form.description" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- Audit -->
    <el-dialog v-model="auditVisible" title="收支审核" width="450px" destroy-on-close>
      <el-form label-width="80px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.status">
            <el-radio :value="1">通过</el-radio>
            <el-radio :value="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注">
          <el-input v-model="auditForm.audit_remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
