<style scoped lang="scss">
.system-container {

  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
    overflow: auto;

    .el-table {
      flex: 1;
    }
  }
}

.page-pager {
  background-color: var(--el-color-white);
  height: 24px;
}
</style>
<template>
  <div class="system-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <el-form
          :model="state.formQuery"
          ref="queryRef"
          size="default" label-width="0px" class="mt5 mb5">
        <ext-select
            v-model="state.formQuery.stationId"
            placeholder="站点"
            url="washStation/list"
            url-method="post"
            label-key="stationName"
            value-key="stationId"
            data-key="list"
            clearable
            class="wd200 ml10"/>

        <el-input
            v-model="state.formQuery.statMonth"
            placeholder="统计月份 如 2026-05"
            clearable
            class="wd200 ml10"/>

        <el-button class="ml10" plain size="default" type="success" @click="loadData(true)">
          <SvgIcon name="ele-Search"/>
          查询
        </el-button>

        <el-input
            v-model="state.syncMonth"
            placeholder="同步月份 如 2026-05"
            clearable
            class="wd180 ml10"/>

        <el-button class="ml10" plain size="default" type="warning" @click="handleSyncMonthStat">
          <SvgIcon name="ele-RefreshRight"/>
          重新同步
        </el-button>
      </el-form>

      <el-table
          border
          stripe="stripe"
          :height="state.tableData.height"
          :data="state.tableData.data"
          v-loading="state.tableData.loading">
        <template #empty>
          <el-empty></el-empty>
        </template>
        <el-table-column
            v-for="field in state.columns"
            :key="field.prop"
            :label="field.label"
            :column-key="field.prop"
            :width="field.width"
            :min-width="field.minWidth"
            :fixed="field.fixed"
            :show-overflow-tooltip="!field.fixed&&field.width>150">

          <template #default="{row}">
            <template v-if="['totalIncome','totalRefund','crossIncome','crossExpend','consumption','platformFee'].includes(field.prop)">
              {{ u.fmt.fmtMoney(row[field.prop]) }}
            </template>
            <template v-else-if="['createTime','updateTime'].includes(field.prop)">
              {{ u.fmt.fmtDateTime(row[field.prop]) }}
            </template>
            <template v-else>
              <div>{{ row[field.prop] }}</div>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <ext-page class="page-pager" v-model:value="state.pageQuery" @change="loadData(false)"/>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="adminStatisticsMonthStat">
import {reactive, onMounted, ref, nextTick} from 'vue';
import {$body} from "/@/utils/request";
import u from '/@/utils/u'
import {Msg} from "/@/utils/message";

import ExtPage from '/@/components/form/ExtPage.vue'
import ExtSelect from "/@/components/form/ExtSelect.vue";

const queryRef = ref();

const state = reactive({
  syncMonth: '',
  formQuery: {
    stationId: '',
    statMonth: ''
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false
  },
  columns: [
    {label: '统计月份', width: 120, prop: 'statMonth', fixed: 'left', resizable: true},
    {label: '站点名称', width: 180, prop: 'stationName', resizable: true},
    {label: '总收入（元）', width: 140, prop: 'totalIncome', resizable: true},
    {label: '退款金额（元）', width: 140, prop: 'totalRefund', resizable: true},
    {label: '跨店收入（元）', width: 140, prop: 'crossIncome', resizable: true},
    {label: '跨店支出（元）', width: 140, prop: 'crossExpend', resizable: true},
    {label: '消费金额（元）', width: 140, prop: 'consumption', resizable: true},
    {label: '平台服务费（元）', width: 150, prop: 'platformFee', resizable: true},
    {label: '充值笔数', width: 100, prop: 'rechargeCount', resizable: true},
    {label: '退款笔数', width: 100, prop: 'refundCount', resizable: true},
    {label: '注册人数', width: 100, prop: 'registrations', resizable: true},
    {label: '活跃用户数', width: 110, prop: 'activeUserCount', resizable: true},
    {label: '订单数量', width: 100, prop: 'ordersCount', resizable: true},
    {label: '创建时间', width: 180, prop: 'createTime', resizable: true},
  ],
})

onMounted(() => {
  // 默认查询上月数据
  const now = new Date();
  const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  const lastMonthStr = lastMonth.getFullYear() + '-' + String(lastMonth.getMonth() + 1).padStart(2, '0');
  state.formQuery.statMonth = lastMonthStr;
  state.syncMonth = lastMonthStr;

  loadData();

  nextTick(() => {
    let bodyHeight = document.body.clientHeight;
    let queryHeight = queryRef.value.$el.clientHeight;
    state.tableData.height = bodyHeight - queryHeight - 320
  })
});

const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  $body(`/month-stat/list`, {...state.formQuery, ...state.pageQuery}).then((res: any) => {
    let {list, total} = res;
    state.tableData.data = list || [];
    state.pageQuery.total = total || 0;
    state.tableData.loading = false;
  }).catch(e => {
    console.error(e)
    state.tableData.loading = false;
  })
};

const handleSyncMonthStat = () => {
  if (!state.syncMonth) {
    Msg.message('请输入同步月份', 'warning');
    return;
  }
  Msg.confirm(`确认重新同步 ${state.syncMonth} 的统计数据吗？将同步所有站点的数据。`, '重新同步月统计').then(() => {
    Msg.showLoading('同步中...');
    $body(`/month-stat/sync`, {statMonth: state.syncMonth}).then(() => {
      Msg.message("同步完成");
      Msg.hideLoading();
      loadData(true);
    }).catch(e => {
      Msg.hideLoading();
    })
  })
};
</script>
