<template>
  <div class="store-page">
    <Breadcrumb />

    <userCard />

    <a-card title="乐跑次数明细" style="margin-top: 15px;">
      <AppQueryFilter>
      <a-row class="queryForm app-query-form">
        <a-col :flex="'1000px'">
          <a-form :model="queryData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="biz_type" label="变动类型">
                  <a-select v-model="queryData.biz_type" allow-clear placeholder="全部类型" style="width: 100%">
                    <a-option value="">全部</a-option>
                    <a-option v-for="item in typeOptions" :key="item.value" :value="item.value">{{ item.label }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="remark" label="备注搜索">
                  <a-input v-model="queryData.remark" no-trim allow-clear placeholder="请输入备注关键词" style="width: 100%" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="queryTime" label="变动时间">
                  <a-range-picker v-model="queryData.queryTime" show-time format="YY-MM-DD HH:mm" value-format="x" style="width: 100%" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="reset">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      </AppQueryFilter>

      <a-alert v-if="notice" style="margin-bottom: 15px;">{{ notice }}</a-alert>

      <a-table
        :data="data"
        :loading="loading"
        :bordered="false"
        :scroll="{ x: 980 }"
        :summary="tableSummary"
        :pagination="{
          showPageSize: true,
          showJumper: true,
          showTotal: true,
          pageSize: pagination.pagesize,
          current: pagination.current,
          total: pagination.total
        }"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #columns>
          <a-table-column title="时间" :width="170">
            <template #cell="{ record }">{{ stramptoTime(record.created_at) }}</template>
          </a-table-column>
          <a-table-column title="类型" data-index="biz_type" :width="160">
            <template #cell="{ record }">{{ typeLabel(record.biz_type) }}</template>
          </a-table-column>
          <a-table-column title="变动值" :width="100">
            <template #cell="{ record }">
              <a-tag :color="Number(record.delta) >= 0 ? 'green' : 'red'">
                {{ Number(record.delta) >= 0 ? `+${record.delta}` : record.delta }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="变动前" data-index="balance_before" :width="100" />
          <a-table-column title="变动后" data-index="balance_after" :width="100" />
          <!-- <a-table-column title="业务单号" data-index="biz_id" :width="220" ellipsis tooltip /> -->
          <a-table-column title="备注" data-index="remark" :width="220" ellipsis tooltip />
        </template>
        <template #summary-cell="{ column }">
          <template v-if="column.title === '时间'">
            <strong>合计</strong>
          </template>
          <template v-else-if="column.title === '变动值'">
            <a-tag :color="Number(summary.total_delta) >= 0 ? 'green' : 'red'">
              {{ formatDelta(summary.total_delta) }}
            </a-tag>
          </template>
          <template v-else-if="column.title === '备注'">
            <span class="summary-muted">共 {{ summary.total_records }} 条</span>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { Notification } from '@arco-design/web-vue'
import { getMyCountLedger } from '@/api/lepao'
import userCard from '@/components/userCard/userCard.vue'
import { useRoute } from 'vue-router'
import { getNotice, getSemesterTimestamps } from '@/utils/util'


const loading = ref(false)
const data = ref([])
const summary = ref({
  total_delta: 0,
  total_records: 0
})
const tableSummary = () => [{}]
const formatDelta = (value) => {
  const num = Number(value) || 0
  return num >= 0 ? `+${num}` : `${num}`
}
const pagination = reactive({
  total: 0,
  current: 1,
  pagesize: 20
})
const queryData = reactive({
  biz_type: '',
  remark: '',
  queryTime: []
})
const notice = ref('')

const typeOptions = [
  { label: '乐跑扣除', value: 'run_consume' },
  { label: '乐跑返还', value: 'run_refund' },
  { label: '购买增加', value: 'purchase' },
  { label: '购买退款', value: 'purchase_refund' },
  { label: '赠送冻结', value: 'gift_send_lock' },
  { label: '赠送驳回返还', value: 'gift_send_refund' },
  { label: '接收赠送', value: 'gift_receive' },
  { label: '系统调整', value: 'admin_adjust' }
]

const typeLabel = (value) => typeOptions.find(item => item.value === value)?.label || value || '-'
const stramptoTime = (time) =>
  new Date(time).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })

const fetchData = async () => {
  loading.value = true
  try {
    const [start, end] = queryData.queryTime || []
    const res = await getMyCountLedger({
      current: pagination.current,
      pagesize: pagination.pagesize,
      biz_type: queryData.biz_type,
      remark: queryData.remark,
      start_time: start,
      end_time: end
    })
    if (!res || res.code !== 0) {
      return Notification.error({
        title: '获取次数明细失败',
        content: res?.msg ?? '请稍后再试'
      })
    }
    data.value = res.data || []
    summary.value = res.summary || { total_delta: 0, total_records: 0 }
    pagination.total = res.pagination?.total || 0
  } catch (error) {
    Notification.error({
      title: '获取次数明细失败',
      content: error.message || '请稍后再试'
    })
  } finally {
    loading.value = false
  }
}

const search = () => {
  pagination.current = 1
  fetchData()
}

const reset = () => {
  queryData.biz_type = ''
  queryData.remark = ''
  queryData.queryTime = getSemesterTimestamps()
  pagination.current = 1
  fetchData()
}

const handlePageChange = (page) => {
  pagination.current = page
  fetchData()
}

const handlePageSizeChange = (size) => {
  pagination.pagesize = size
  pagination.current = 1
  fetchData()
}

const GetNotice = async () => {
  const { path } = useRoute()
  const res = await getNotice(path)
  notice.value = res
}

onMounted(() => {
  queryData.queryTime = getSemesterTimestamps()
  fetchData()
  GetNotice()
})
</script>

<style scoped lang="less">
@import '@/styles/store-theme.less';

.queryForm {
  @media (min-width: (@app-breakpoint-md + 1px)) {
    margin-bottom: 16px;
  }
}

.summary-muted {
  color: var(--color-text-3);
  font-size: 13px;
}
</style>
