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

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

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

// ─── Recharge Dialog ────────────────────────────────────────────────────────
const rechargeVisible = ref(false)
const rechargeLoading = ref(false)
const rechargeFormRef = ref(null)
const rechargeForm = reactive({ customer_account_id: null, customer_id: null, amount: 0, pay_method: '' })
const rechargeRules = {
  amount: [{ required: true, message: '请输入充值金额', trigger: 'blur' }]
}
const payMethods = [
  { label: '现金', value: 'cash' },
  { label: '微信', value: 'wechat' },
  { label: '支付宝', value: 'alipay' },
  { label: '银行转账', value: 'bank' },
  { label: '储值卡', value: 'card' }
]

// ─── Transaction History Dialog ─────────────────────────────────────────────
const txVisible = ref(false)
const txLoading = ref(false)
const txData = ref([])
const txTotal = ref(0)
const txAccountId = ref(null)
const txPagination = reactive({ page: 1, per_page: 20 })

const txTypeMap = { 1: '充值', 2: '消费', 3: '退款', 4: '积分变动' }
const txTypeType = { 1: 'success', 2: 'warning', 3: 'danger', 4: 'info' }

// ─── Main List ──────────────────────────────────────────────────────────────
async function fetchList() {
  loading.value = true
  try {
    const res = await customerAccountApi.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, { customer_id: '' }); handleSearch() }

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

// ─── Recharge ───────────────────────────────────────────────────────────────
function handleRecharge(row) {
  Object.assign(rechargeForm, { customer_account_id: row.id, customer_id: row.customer_id, amount: 0, pay_method: '' })
  rechargeVisible.value = true
}

async function submitRecharge() {
  if (!rechargeFormRef.value) return
  await rechargeFormRef.value.validate(async (valid) => {
    if (!valid) return
    rechargeLoading.value = true
    try {
      await customerAccountApi.recharge(rechargeForm)
      ElMessage.success('充值成功')
      rechargeVisible.value = false
      fetchList()
    } finally { rechargeLoading.value = false }
  })
}

// ─── Transaction History ────────────────────────────────────────────────────
function handleViewTx(row) {
  txAccountId.value = row.id
  txPagination.page = 1
  txVisible.value = true
  fetchTxList()
}

async function fetchTxList() {
  txLoading.value = true
  try {
    const res = await accountTransactionApi.getList({ customer_account_id: txAccountId.value, ...txPagination })
    txData.value = res.data?.list || res.data?.data || []
    txTotal.value = res.data?.total || 0
  } finally { txLoading.value = false }
}

function handleTxPageChange(val) { txPagination.page = val; fetchTxList() }
function handleTxSizeChange(val) { txPagination.per_page = val; txPagination.page = 1; fetchTxList() }

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-input v-model="searchForm.customer_id" placeholder="客户ID" style="width:160px" 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>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column label="客户姓名" min-width="120">
            <template #default="{ row }">{{ row.customer?.name || '-' }}</template>
          </el-table-column>
          <el-table-column prop="cash_balance" label="现金余额" min-width="120" align="right" />
          <el-table-column prop="card_balance" label="储值卡余额" min-width="120" align="right" />
          <el-table-column prop="points" label="积分" min-width="100" align="right" />
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" text @click="handleRecharge(row)">充值</el-button>
              <el-button size="small" type="primary" text @click="handleViewTx(row)">查看流水</el-button>
            </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>

    <!-- Recharge Dialog -->
    <el-dialog v-model="rechargeVisible" title="账户充值" width="480px" destroy-on-close>
      <el-form ref="rechargeFormRef" :model="rechargeForm" :rules="rechargeRules" label-width="90px">
        <el-form-item label="客户ID">
          <el-input :model-value="rechargeForm.customer_id" disabled />
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input-number v-model="rechargeForm.amount" :min="0.01" :precision="2" :step="100" style="width:100%" />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="rechargeForm.pay_method" placeholder="请选择支付方式" style="width:100%">
            <el-option v-for="m in payMethods" :key="m.value" :label="m.label" :value="m.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rechargeVisible = false">取消</el-button>
        <el-button type="primary" :loading="rechargeLoading" @click="submitRecharge">确定</el-button>
      </template>
    </el-dialog>

    <!-- Transaction History Dialog -->
    <el-dialog v-model="txVisible" title="账户流水" width="800px" destroy-on-close>
      <el-table v-loading="txLoading" :data="txData" border stripe style="width:100%">
        <el-table-column label="类型" width="110" align="center">
          <template #default="{ row }">
            <el-tag :type="txTypeType[row.type]" size="small">{{ txTypeMap[row.type] || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" min-width="100" align="right" />
        <el-table-column prop="balance_after" label="变动后余额" min-width="120" align="right" />
        <el-table-column prop="description" label="描述" min-width="180" show-overflow-tooltip />
        <el-table-column prop="created_at" label="时间" min-width="160" />
      </el-table>
      <el-pagination v-model:current-page="txPagination.page" v-model:page-size="txPagination.per_page" :total="txTotal" :page-sizes="[10, 20, 50]" layout="total,sizes,prev,pager,next,jumper" background style="margin-top:12px" @current-change="handleTxPageChange" @size-change="handleTxSizeChange" />
    </el-dialog>
  </div>
</template>
