<template>
  <div>
    <el-form inline>
      <el-form-item label="日期">
        <el-date-picker v-model="dateRange" type="daterange" start-placeholder="开始" end-placeholder="结束" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="停车场">
        <el-select v-model="lotId" clearable placeholder="全部" style="width:180px">
          <el-option v-for="l in lotList" :key="l.ID" :label="l.lot_name" :value="l.ID" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetch">{{ $t.value.Search }}</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="list" border show-summary :summary-method="summaries">
      <el-table-column label="日期" prop="date" width="120" />
      <el-table-column label="停车场" prop="parking_lot" width="140" />
      <el-table-column label="现金" width="100"><template #default="{row}">¥{{ row.cash.toFixed(2) }}</template></el-table-column>
      <el-table-column label="免密" width="100"><template #default="{row}">¥{{ row.free.toFixed(2) }}</template></el-table-column>
      <el-table-column label="总收入" width="120"><template #default="{row}">¥{{ row.total.toFixed(2) }}</template></el-table-column>
      <el-table-column label="笔数" prop="count" width="80" />
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getRevenueReport } from '@/api/report'
import { obtainPullOverList } from '@/api/pullOver'

const dateRange = ref([]), lotId = ref(null), list = ref([]), lotList = ref([])

function summaries({ columns, data }) {
  const sums = { 2: 0, 3: 0, 4: 0, 5: 0 }
  data.forEach(r => { sums[2] += r.cash; sums[3] += r.free; sums[4] += r.total; sums[5] += r.count })
  return columns.map((col, i) => {
    if (i < 2) return i === 0 ? '合计' : ''
    return i === 5 ? sums[i] : '¥' + sums[i].toFixed(2)
  })
}

async function fetch() {
  const [s, e] = dateRange.value && dateRange.value.length === 2 ? dateRange.value : ['', '']
  const r = await getRevenueReport({ start_date: s, end_date: e, parking_lot_id: lotId.value || '' })
  if (r.code === 0) list.value = r.data || []
}

onMounted(async () => {
  const today = new Date().toISOString().slice(0, 10)
  dateRange.value = [today, today]
  const l = await obtainPullOverList({ page: 1, pageSize: 100 })
  if (l.code === 0) lotList.value = l.data?.list || []
  fetch()
})
</script>
