<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-date-picker
            v-model="state.formQuery.startDate"
            type="date"
            placeholder="开始日期"
            value-format="YYYY-MM-DD"
            clearable
            class="wd200 ml10"/>

        <el-date-picker
            v-model="state.formQuery.endDate"
            type="date"
            placeholder="结束日期"
            value-format="YYYY-MM-DD"
            clearable
            class="wd200 ml10"/>

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

        <el-date-picker
            v-model="state.syncDateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledSyncDate"
            class="wd260 ml10"/>

        <el-button class="ml10" plain size="default" type="warning" @click="handleSyncDailyStat" :loading="state.syncing">
          <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'].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="adminStatisticsDailyStat">
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({
  syncDateRange: [] as string[],
  syncing: false,
  formQuery: {
    stationId: '',
    startDate: '',
    endDate: ''
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false
  },
  columns: [
    {label: '统计日期', width: 120, prop: 'statDate', 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: 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 yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  const yesterdayStr = yesterday.toISOString().split('T')[0];
  state.syncDateRange = [yesterdayStr, yesterdayStr];

  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(`/daily-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 disabledSyncDate = (date: Date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  // 不允许选择今天及以后
  return date.getTime() >= today.getTime();
};

const handleSyncDailyStat = () => {
  if (!state.syncDateRange || state.syncDateRange.length !== 2) {
    Msg.message('请选择同步日期范围', 'warning');
    return;
  }
  const [startDate, endDate] = state.syncDateRange;
  const days = Math.floor((new Date(endDate).getTime() - new Date(startDate).getTime()) / 86400000) + 1;
  if (days > 30) {
    Msg.message('同步日期范围不能超过30天', 'warning');
    return;
  }
  const rangeLabel = startDate === endDate ? startDate : `${startDate} ~ ${endDate}`;
  Msg.confirm(
    `确认重新同步 ${rangeLabel}（共${days}天）的统计数据吗？将同步所有站点的数据。`,
    '批量同步日统计'
  ).then(() => {
    state.syncing = true;
    Msg.showLoading(`批量同步中（共${days}天）...`);
    $body(`/daily-stat/batch-sync`, { startDate, endDate }).then(() => {
      Msg.message(`同步完成（共${days}天）`);
      Msg.hideLoading();
      state.syncing = false;
      loadData(true);
    }).catch(e => {
      Msg.hideLoading();
      state.syncing = false;
    })
  })
};
</script>
