<script setup lang="ts">
import { reactive, onMounted, ref, nextTick } from "vue";
import { getMonthStatList, syncMonthStat } from "@/api/stat";
import { getStationList } from "@/api/station";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessage, ElMessageBox } from "element-plus";

defineOptions({ name: "AdminMonthStat" });

const queryRef = ref();

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

onMounted(() => {
  const now = new Date();
  const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  state.syncMonth = lastMonth.getFullYear() + "-" + String(lastMonth.getMonth() + 1).padStart(2, "0");

  loadStations();
  loadData();
  nextTick(() => {
    const bodyHeight = document.body.clientHeight;
    const queryHeight = queryRef.value?.$el?.clientHeight || 0;
    state.tableData.height = bodyHeight - queryHeight - 260;
  });
});

const loadStations = () => {
  getStationList({ pageNum: 1, pageSize: 200 }).then((res: any) => {
    state.stationOptions = res?.list || res?.records || [];
  }).catch(() => {});
};

const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  const params: any = { ...state.pageQuery };
  if (state.formQuery.stationId) params.stationId = state.formQuery.stationId;
  if (state.formQuery.statMonth) params.statMonth = state.formQuery.statMonth;

  getMonthStatList(params)
    .then((res: any) => {
      state.tableData.data = res?.list || res?.records || [];
      state.pageQuery.total = res?.total || 0;
    })
    .catch(() => {
      state.tableData.data = [];
      ElMessage.error("加载月统计数据失败");
    })
    .finally(() => {
      state.tableData.loading = false;
    });
};

const handleSizeChange = (size: number) => {
  state.pageQuery.pageSize = size;
  loadData(true);
};

const handleCurrentChange = (page: number) => {
  state.pageQuery.pageNum = page;
  loadData();
};

const handleSearch = () => loadData(true);

const handleReset = () => {
  state.formQuery = { stationId: "", statMonth: "" };
  loadData(true);
};

const handleSyncMonthStat = () => {
  if (!state.syncMonth) {
    ElMessage.warning("请输入同步月份");
    return;
  }
  ElMessageBox.confirm(
    `确认重新同步 ${state.syncMonth} 的统计数据吗？将同步所有站点的数据。`,
    "重新同步月统计",
    { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
  ).then(() => {
    const loading = ElMessage({ message: "同步中...", type: "info", duration: 0 });
    syncMonthStat({ statMonth: state.syncMonth })
      .then(() => {
        loading.close();
        ElMessage.success("同步完成");
        loadData(true);
      })
      .catch(() => {
        loading.close();
        ElMessage.error("同步失败");
      });
  }).catch(() => {});
};

const formatMoney = (value: number) => {
  if (value === null || value === undefined) return "¥0.00";
  return `¥${(value / 100).toFixed(2)}`;
};

const moneyFields = ["totalIncome", "totalRefund", "crossIncome", "crossExpend", "consumption", "platformFee"];
</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <template #header>
        <span class="card-header">月统计</span>
      </template>
      <el-form ref="queryRef" :model="state.formQuery" inline class="search-form">
        <el-form-item label="站点">
          <el-select
            v-model="state.formQuery.stationId"
            placeholder="选择站点"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in state.stationOptions"
              :key="item.stationId"
              :label="item.stationName"
              :value="item.stationId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="统计月份">
          <el-input
            v-model="state.formQuery.statMonth"
            placeholder="如 2026-05"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon('ri/search-line')"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button
            :icon="useRenderIcon('ri/refresh-line')"
            @click="handleReset"
          >
            重置
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="state.syncMonth"
            placeholder="同步月份 如 2026-05"
            clearable
            style="width: 200px"
          />
          <el-button
            type="warning"
            :icon="useRenderIcon('ri/loop-right-line')"
            @click="handleSyncMonthStat"
            style="margin-left: 8px"
          >
            重新同步
          </el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="state.tableData.loading"
        :data="state.tableData.data"
        :height="state.tableData.height"
        border
        stripe
      >
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
        <el-table-column
          v-for="col in state.tableData.columns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :width="col.width"
          :fixed="(col as any).fixed"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <template v-if="moneyFields.includes(col.prop)">
              {{ formatMoney(row[col.prop]) }}
            </template>
            <template v-else>
              {{ row[col.prop] }}
            </template>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="state.pageQuery.pageNum"
          v-model:page-size="state.pageQuery.pageSize"
          :total="state.pageQuery.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.page-container {
  padding: 20px;
}

.card-header { font-size: 16px; font-weight: 600; }

.search-form {
  margin-bottom: 16px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
