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

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)

const searchForm = reactive({ status: '', date_from: '', date_to: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({
  customer_id: '',
  customer_name: '',
  contract_id: '',
  amount: 0,
  payment_method: '',
  remark: ''
})
const formRules = {
  customer_name: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
  payment_method: [{ required: true, message: '请选择付款方式', trigger: 'change' }]
}

const statusMap = { pending: '待确认', confirmed: '已确认' }
const statusType = { pending: 'warning', confirmed: 'success' }
const payMethodMap = {
  cash: '现金',
  card: '刷卡',
  wechat: '微信',
  alipay: '支付宝',
  transfer: '银行转账'
}

async function fetchList() {
  loading.value = true
  try {
    const res = await paymentApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } catch {
    ElMessage.error('获取付款列表失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() {
  Object.assign(searchForm, { status: '', date_from: '', date_to: '' })
  handleSearch()
}

function handleAdd() {
  Object.assign(form, {
    customer_id: '', customer_name: '', contract_id: '',
    amount: 0, payment_method: '', remark: ''
  })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      await paymentApi.create({ ...form, type: 'payment' })
      ElMessage.success('创建成功')
      dialogVisible.value = false
      fetchList()
    } catch {
      ElMessage.error('创建失败')
    } finally {
      submitLoading.value = false
    }
  })
}

async function handleConfirm(row) {
  await ElMessageBox.confirm(`确认收款「¥${row.amount}」吗？`, '确认收款', { type: 'warning' })
  try {
    await paymentApi.audit(row.id, {})
    ElMessage.success('确认成功')
    fetchList()
  } catch {
    ElMessage.error('确认失败')
  }
}

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.status" placeholder="状态" clearable style="width:120px">
        <el-option v-for="(v, k) in statusMap" :key="k" :label="v" :value="k" />
      </el-select>
      <el-date-picker
        v-model="searchForm.date_from"
        type="date"
        value-format="YYYY-MM-DD"
        placeholder="开始日期"
        style="width:150px"
      />
      <el-date-picker
        v-model="searchForm.date_to"
        type="date"
        value-format="YYYY-MM-DD"
        placeholder="结束日期"
        style="width:150px"
      />
      <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="w-1 h-5 bg-rose-500 rounded-full inline-block"></span>
          <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%" stripe>
          <el-table-column prop="id" label="ID" width="70" align="center" />
          <el-table-column prop="customer_name" label="客户" min-width="110" />
          <el-table-column prop="contract_id" label="合同ID" width="90" align="center" />
          <el-table-column label="金额" width="120" align="right">
            <template #default="{ row }">
              <span class="text-green-600 font-semibold">¥{{ Number(row.amount || 0).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="付款方式" width="110" align="center">
            <template #default="{ row }">
              {{ payMethodMap[row.payment_method] || row.payment_method || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="statusType[row.status]" size="small">
                {{ statusMap[row.status] || row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
          <el-table-column prop="created_at" label="创建时间" min-width="160" />
          <el-table-column label="操作" width="100" fixed="right" align="center">
            <template #default="{ row }">
              <el-button
                v-if="row.status === 'pending'"
                size="small"
                type="success"
                text
                @click="handleConfirm(row)"
              >确认收款</el-button>
              <span v-else class="text-gray-400 text-sm">-</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>

    <!-- 新建收款 Dialog -->
    <el-dialog v-model="dialogVisible" title="新建收款记录" width="520px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-form-item label="客户姓名" prop="customer_name">
          <el-input v-model="form.customer_name" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="合同ID">
          <el-input v-model="form.contract_id" placeholder="关联合同ID（可选）" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="form.amount" :min="0.01" :precision="2" style="width:100%" />
        </el-form-item>
        <el-form-item label="付款方式" prop="payment_method">
          <el-select v-model="form.payment_method" placeholder="选择付款方式" style="width:100%">
            <el-option v-for="(v, k) in payMethodMap" :key="k" :label="v" :value="k" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
