<template>
  <section class="panel">
    <div class="panel-toolbar">
      <el-form class="stats-filter" label-position="top">
        <el-form-item label="周期">
          <el-segmented :options="quickOptions" @update:model-value="applyQuickRange" />
        </el-form-item>
        <el-form-item label="开始">
          <el-input v-model="filterDraft.from" placeholder="2026-06-01" />
        </el-form-item>
        <el-form-item label="结束">
          <el-input v-model="filterDraft.to" placeholder="2026-07-01" />
        </el-form-item>
        <el-form-item label="门店 ID">
          <el-input v-model="filterDraft.storeId" inputmode="numeric" />
        </el-form-item>
        <el-form-item label="保洁员">
          <el-select
            v-model="filterDraft.cleanerUserId"
            class="filter-select"
            clearable
            filterable
            placeholder="保洁员"
          >
            <el-option
              v-for="cleaner in cleaners"
              :key="cleaner.id"
              :label="cleanerLabel(cleaner)"
              :value="cleaner.id"
            >
              <div class="option-row">
                <strong>{{ cleaner.nickname || compactText(cleaner.id) }}</strong>
                <span>{{ cleaner.maskedPhone || '未留手机' }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-button type="primary" :icon="Search" @click="emitFilter">查询</el-button>
      </el-form>
      <el-tooltip content="刷新统计">
        <el-button :icon="RefreshCw" :loading="loading" circle @click="$emit('refresh')" />
      </el-tooltip>
    </div>

    <div class="stats-body" v-loading="loading">
      <section class="metric-grid compact" aria-label="统计概览">
        <div class="metric">
          <span>任务总数</span>
          <strong>{{ statistics.summary.taskTotal }}</strong>
        </div>
        <div class="metric">
          <span>待验收</span>
          <strong>{{ statistics.summary.pendingReview }}</strong>
        </div>
        <div class="metric">
          <span>待结算</span>
          <strong>{{ money(statistics.summary.pendingSettlementCents) }}</strong>
        </div>
        <div class="metric">
          <span>已发放</span>
          <strong>{{ money(statistics.summary.paidSettlementCents) }}</strong>
        </div>
      </section>

      <div class="stats-grid">
        <section class="stat-block">
          <header>
            <h3>任务状态</h3>
            <span>{{ money(statistics.summary.rewardCents) }}</span>
          </header>
          <el-table :data="statistics.byStatus" size="small">
            <el-table-column prop="status" label="状态" />
            <el-table-column prop="total" label="数量" width="90" />
            <el-table-column prop="rewardCents" label="奖励" width="120">
              <template #default="{ row }">{{ money(row.rewardCents) }}</template>
            </el-table-column>
          </el-table>
        </section>

        <section class="stat-block">
          <header>
            <h3>结算口径</h3>
            <span>待发 {{ money(statistics.summary.confirmedSettlementCents) }}</span>
          </header>
          <el-table :data="statistics.settlements" size="small">
            <el-table-column prop="status" label="状态" />
            <el-table-column prop="total" label="单数" width="90" />
            <el-table-column prop="rewardCents" label="金额" width="120">
              <template #default="{ row }">{{ money(row.rewardCents) }}</template>
            </el-table-column>
          </el-table>
        </section>
      </div>

      <section class="stat-block">
        <header>
          <h3>每日趋势</h3>
          <span>任务 / 待验 / 发放</span>
        </header>
        <div class="trend-list">
          <div v-for="row in statistics.trend" :key="row.date" class="trend-row">
            <div class="trend-date">{{ row.date }}</div>
            <div class="trend-track" aria-label="每日任务趋势">
              <span class="trend-bar" :style="{ width: trendWidth(row.taskTotal) }" />
            </div>
            <div class="trend-meta">
              <strong>{{ row.taskTotal }}</strong>
              <span>待验 {{ row.pendingReview }}</span>
              <span>完成 {{ row.completed }}</span>
              <span>驳回 {{ row.rejected }}</span>
              <span>奖励 {{ money(row.rewardCents) }}</span>
              <span>发放 {{ money(row.paidSettlementCents) }}</span>
            </div>
          </div>
          <el-empty v-if="statistics.trend.length === 0" description="暂无趋势数据" :image-size="72" />
        </div>
      </section>

      <section class="stat-block">
        <header>
          <h3>门店明细</h3>
          <span>按待验收优先</span>
        </header>
        <el-table :data="statistics.byStore" size="small">
          <el-table-column prop="storeName" label="门店" min-width="150" />
          <el-table-column prop="taskTotal" label="任务" width="90" />
          <el-table-column prop="pendingReview" label="待验" width="90" />
          <el-table-column prop="completed" label="完成" width="90" />
          <el-table-column prop="rejected" label="驳回" width="90" />
          <el-table-column prop="rewardCents" label="奖励" width="120">
            <template #default="{ row }">{{ money(row.rewardCents) }}</template>
          </el-table-column>
        </el-table>
      </section>

      <section class="stat-block">
        <header>
          <h3>成员分账</h3>
          <span>按待结算金额排序</span>
        </header>
        <el-table :data="statistics.members" size="small">
          <el-table-column prop="cleanerName" label="保洁员" min-width="150">
            <template #default="{ row }">
              <div class="stack">
                <strong>{{ row.cleanerName || compactText(row.cleanerUserId) }}</strong>
                <span>ID {{ row.cleanerUserId }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="taskCount" label="任务" width="90" />
          <el-table-column prop="pendingSettlementCents" label="待结算" width="130">
            <template #default="{ row }">{{ money(row.pendingSettlementCents) }}</template>
          </el-table-column>
          <el-table-column prop="settledRewardCents" label="已结算" width="130">
            <template #default="{ row }">{{ money(row.settledRewardCents) }}</template>
          </el-table-column>
        </el-table>
      </section>
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { RefreshCw, Search } from '@lucide/vue';
import { compactText, money } from '../format';
import type { CleaningStatistics, ManagedUser } from '../types';

const props = defineProps<{
  loading: boolean;
  statistics: CleaningStatistics;
  filters: { from: string; to: string; storeId: string; cleanerUserId: string };
  cleaners: ManagedUser[];
}>();

const emit = defineEmits<{
  refresh: [];
  filter: [{ from: string; to: string; storeId: string; cleanerUserId: string }];
}>();

const filterDraft = reactive({ ...props.filters });
const quickOptions = [
  { label: '今日', value: 'today' },
  { label: '近7天', value: '7d' },
  { label: '本月', value: 'month' }
];
const maxTrendTotal = computed(() => Math.max(1, ...props.statistics.trend.map((row) => row.taskTotal)));

watch(
  () => props.filters,
  (value) => Object.assign(filterDraft, value),
  { deep: true }
);

function emitFilter() {
  emit('filter', {
    from: filterDraft.from.trim(),
    to: filterDraft.to.trim(),
    storeId: filterDraft.storeId.trim(),
    cleanerUserId: filterDraft.cleanerUserId.trim()
  });
}

function cleanerLabel(cleaner: ManagedUser) {
  return `${cleaner.nickname || compactText(cleaner.id)} / ${cleaner.maskedPhone || '未留手机'}`;
}

function applyQuickRange(value: string | number | boolean) {
  const now = new Date();
  const end = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
  let start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  if (value === '7d') {
    start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 6);
  }
  if (value === 'month') {
    start = new Date(now.getFullYear(), now.getMonth(), 1);
  }
  filterDraft.from = formatDate(start);
  filterDraft.to = formatDate(end);
  emitFilter();
}

function formatDate(date: Date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

function trendWidth(total: number) {
  return `${Math.max(6, Math.round((total / maxTrendTotal.value) * 100))}%`;
}
</script>
