<template>
  <div class="app-container home-dashboard">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="16" class="stat-row">
      <el-col
        :xs="24"
        :sm="12"
        :lg="6"
        v-for="card in statCards"
        :key="card.key"
      >
        <div class="stat-card">
          <div class="stat-icon" :class="card.iconClass">
            <component :is="card.icon" />
          </div>
          <div class="stat-meta">
            <div class="stat-title">{{ card.title }}</div>
            <div class="stat-value">
              <template v-if="card.prefix">{{ card.prefix }}</template
              >{{ formatNumber(card.value) }}
            </div>
          </div>
          <div class="stat-bg" :class="card.bgClass"></div>
        </div>
      </el-col>
    </el-row>

    <!-- 中部：下单统计 + 异常行为预警 -->
    <el-row :gutter="16" class="mid-row" style="margin-bottom: 14px">
      <el-col :xs="24" :lg="16">
        <div class="panel">
          <div class="panel-header">
            <div class="title">下单统计</div>
            <div class="actions">
              <el-select
                v-model="orderFilter"
                placeholder="请选择园所"
                clearable
                filterable
                remote
                style="width: 240px"
              >
                <el-option
                  v-for="school in schoolList"
                  :key="school._id"
                  :label="school.name"
                  :value="school._id"
                />
              </el-select>
              <el-select v-model="yearA" class="w120 ml8">
                <el-option
                  v-for="y in years"
                  :key="y"
                  :label="y + '年'"
                  :value="y"
                />
              </el-select>
            </div>
          </div>
          <div class="panel-body">
            <div ref="lineRef" class="chart"></div>
          </div>
        </div>
      </el-col>

      <el-col :xs="24" :lg="8">
        <div class="panel">
          <div class="panel-header">
            <div class="title">异常行为预警</div>
            <div class="actions">
              <el-button type="primary" plain @click="goAbnormal"
                >查看全部</el-button
              >
            </div>
          </div>
          <div class="panel-body notice-wrap">
            <div class="notice-item" v-for="(n, i) in notices" :key="i">
              <div class="dot">!</div>
              <div class="notice-content">
                <div class="notice-title">
                  <span style="font-size: 14px; color: red">高频下载预警</span>
                </div>
                <div style="font-size: 15px; margin-bottom: 4px">
                  {{ n.teacher_name }}: {{ n.reason }}
                </div>
                <div class="notice-desc">
                  {{ n.school_name }}
                  {{ moment(n.createdAt).format("YYYY-MM-DD HH:mm:ss") }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 底部：课件上传统计 -->
    <el-row :gutter="16" class="bottom-row">
      <el-col :span="24">
        <div class="panel">
          <div class="panel-header">
            <div class="title">课件上传统计</div>
            <div class="actions">
              <el-select v-model="yearB" class="w120">
                <el-option
                  v-for="y in years"
                  :key="y"
                  :label="y + '年'"
                  :value="y"
                />
              </el-select>
            </div>
          </div>
          <div class="panel-body">
            <div ref="barRef" class="chart"></div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Index">
import {
  ref,
  onMounted,
  onBeforeUnmount,
  nextTick,
  watch,
  getCurrentInstance,
} from "vue";
import * as echarts from "echarts";
import {
  Document,
  Collection,
  Money,
  ChatLineRound,
} from "@element-plus/icons-vue";
import { callCloudFunction } from "@/api/cloud";
import moment from "moment";
import { useRouter } from "vue-router";
import { shallowRef } from 'vue'

const { proxy } = getCurrentInstance();
const router = useRouter();

const schoolList = ref([]);
const statCards = ref([
  {
    key: "todayOrders",
    title: "今日下单数",
    value: 0,
    icon: Document,
    iconClass: "icon-blue",
    bgClass: "bg-blue",
    prefix: "",
  },
  {
    key: "todayAmount",
    title: "今日下单金额",
    value: 0,
    icon: Money,
    iconClass: "icon-purple",
    bgClass: "bg-purple",
    prefix: "",
  },
  {
    key: "totalOrders",
    title: "总下单数（年）",
    value: 0,
    icon: Collection,
    iconClass: "icon-green",
    bgClass: "bg-green",
    prefix: "",
  },
  {
    key: "totalAmount",
    title: "总下单金额（年）",
    value: 0,
    icon: ChatLineRound,
    iconClass: "icon-orange",
    bgClass: "bg-orange",
    prefix: "¥ ",
  },
]);
const notices = ref([]);

const curYear = new Date().getFullYear();
const years = Array.from({ length: 50 }, (_, i) => curYear - i).sort(
  (a, b) => b - a
);
const yearA = ref(curYear);
const yearB = ref(curYear);
const orderFilter = ref("");

const lineRef = ref(null),
  barRef = ref(null);
let lineChart = null,
  barChart = null;

const formatNumber = (n) =>
  (n ?? 0).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

/** 初始化图表通用方法 */
const initChart = (refDom, type = "line", color = "#14c9c9") => {
  const chart = echarts.init(refDom);
  const option =
    type === "line"
      ? {
          grid: { left: "4%", right: "3%", top: "15%", bottom: "12%" },
          tooltip: { trigger: "axis" },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: Array.from({ length: 12 }, (_, i) => i + 1 + "月"),
            axisLine: { lineStyle: { color: "#dcdfe6" } },
            axisLabel: { color: "#909399" },
          },
          yAxis: {
            type: "value",
            name: "单位：单",
            nameTextStyle: { color: "#909399" },
            axisLine: { show: false },
            splitLine: { lineStyle: { color: "#f0f2f5" } },
            axisLabel: { color: "#909399" },
          },
          series: [
            {
              type: "line",
              smooth: true,
              symbol: "circle",
              symbolSize: 6,
              lineStyle: { width: 2, color },
              itemStyle: { color },
              areaStyle: { opacity: 0.08, color },
              data: [],
            },
          ],
        }
      : {
          grid: { left: "3.5%", right: "2%", top: "15%", bottom: "11%" },
          tooltip: { trigger: "axis" },
          xAxis: {
            type: "category",
            data: Array.from({ length: 12 }, (_, i) => i + 1 + "月"),
            axisLine: { lineStyle: { color: "#dcdfe6" } },
            axisLabel: { color: "#909399" },
          },
          yAxis: {
            type: "value",
            name: "单位：个",
            nameTextStyle: { color: "#909399" },
            axisLine: { show: false },
            splitLine: { lineStyle: { color: "#f0f2f5" } },
            axisLabel: { color: "#909399" },
          },
          series: [
            {
              type: "bar",
              barWidth: 36,
              itemStyle: { borderRadius: [18, 18, 0, 0], color },
              data: [],
            },
          ],
        };
  chart.setOption(option);
  return chart;
};

const resize = () => {
  lineChart?.resize();
  barChart?.resize();
};

onBeforeUnmount(() => {
  window.removeEventListener("resize", resize);
  lineChart?.dispose();
  barChart?.dispose();
});

// 顶部卡片
const updateStatCards = (data) => {
  statCards.value.forEach((card) => {
    switch (card.title) {
      case "今日下单数":
        card.value = data.ri_xiadan;
        break;
      case "今日下单金额":
        card.value = data.ri_jine;
        break;
      case "总下单数（年）":
        card.value = data.nian_xiadan;
        break;
      case "总下单金额（年）":
        card.value = data.nian_jine;
        break;
    }
  });
};

// 获取数据接口
const fetchData = async () => {
  const resCards = await callCloudFunction("database", {
    page: "home",
    action: "findCountAndTotal",
  });
  updateStatCards(resCards.data);

  const resNotices = await callCloudFunction("database", {
    page: "home",
    action: "findBehaviorAlarm",
  });
  notices.value = resNotices.data;
};

// 下单统计
const fetchOrderChart = async () => {
  const res = await callCloudFunction("database", {
    page: "home",
    action: "findOrderCountByMonth",
    data: { year: yearA.value, schoolId: orderFilter.value || "" },
  });
  const monthData = Array(12).fill(0);
  res.data.forEach(
    (item) => (monthData[parseInt(item.month.split("-")[1]) - 1] = item.count)
  );
  lineChart?.setOption({ series: [{ data: monthData }] });
};

// 上传统计
const fetchFileChart = async () => {
  const res = await callCloudFunction("database", {
    page: "home",
    action: "findFileCount",
    data: { year: yearB.value },
  });
  const monthData = Array(12).fill(0);
  res.data.forEach(
    (item) => (monthData[parseInt(item.month.split("-")[1]) - 1] = item.count)
  );
  barChart?.setOption({ series: [{ data: monthData }] });
};

// 监听变化
watch([yearA, orderFilter], fetchOrderChart);
watch(yearB, fetchFileChart);

// 初始化
const getSchoolList = async () => {
  try {
    const { data } = await proxy.$models.wx_school.list({
      filter: {},
      pageSize: 10000,
      pageNumber: 1,
      getCount: true,
      envType: "prod",
    });
    schoolList.value = data.records;
  } catch (e) {
    console.error(e);
  }
};

function goAbnormal() {
  router.push("/abnormal");
}

onMounted(async () => {
  await nextTick();
  lineChart = initChart(lineRef.value, "line", "#14c9c9");
  barChart = initChart(barRef.value, "bar", "#4b9bf5");
  window.addEventListener("resize", resize);

  getSchoolList();
  fetchData();
  fetchOrderChart();
  fetchFileChart();
});
</script>

<style scoped lang="scss">
.home-dashboard {
  --card-radius: 16px;
  --panel-radius: 10px;
  --text-muted: #909399;
  --border: #ebeef5;

  .w120 {
    width: 120px;
  }
  .ml8 {
    margin-left: 8px;
  }

  .stat-row {
    margin-bottom: 12px;
  }

  .stat-card {
    position: relative;
    display: flex;
    align-items: center;
    gap: 14px;
    background: #fff;
    border: 1px solid var(--border);
    border-radius: var(--card-radius);
    padding: 18px 18px;
    overflow: hidden;
    min-height: 96px;

    .stat-icon {
      width: 44px;
      height: 44px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      flex: 0 0 44px;
      svg {
        width: 24px;
        height: 24px;
      }
    }
    .icon-blue {
      background: #6bb2ff;
    }
    .icon-purple {
      background: #9b8cff;
    }
    .icon-green {
      background: #6ad5b5;
    }
    .icon-orange {
      background: #ffb265;
    }

    .stat-meta {
      display: flex;
      flex-direction: column;
      .stat-title {
        color: var(--text-muted);
        font-size: 13px;
      }
      .stat-value {
        font-size: 22px;
        font-weight: 700;
        margin-top: 6px;
        color: #1f2d3d;
      }
    }

    .stat-bg {
      position: absolute;
      right: -10px;
      bottom: -55px;
      width: 120px;
      height: 120px;
      filter: blur(0.4px);
      opacity: 0.25;
      border-radius: 20px;
      transform: rotate(60deg);
    }
    .bg-blue {
      background: linear-gradient(135deg, #d7ebff, #eaf4ff);
    }
    .bg-purple {
      background: linear-gradient(135deg, #e8e4ff, #f3f1ff);
    }
    .bg-green {
      background: linear-gradient(135deg, #dcfff5, #effff9);
    }
    .bg-orange {
      background: linear-gradient(135deg, #ffe9d2, #fff4ea);
    }
  }

  .panel {
    background: #fff;
    border: 1px solid var(--border);
    border-radius: var(--panel-radius);
    overflow: hidden;
    .panel-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px 14px;
      border-bottom: 1px solid var(--border);
      .title {
        font-weight: 600;
        color: #1f2d3d;
      }
      .actions {
        display: flex;
        align-items: center;
      }
    }
    .panel-body {
      height: 270px;
    }
  }

  .chart {
    width: 100%;
    height: 270px;
  }

  .notice-wrap {
    padding: 10px 12px;
    max-height: 250px; /* 限制高度，可以根据你的UI调整 */
    overflow-y: auto; /* 出现竖向滚动条 */
    .notice-item {
      display: flex;
      gap: 10px;
      padding: 10px 8px;
      border: 1px solid #ffe2e2;
      background: #fff9f9;
      border-radius: 8px;
      & + .notice-item {
        margin-top: 10px;
      }
      .dot {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background: #ff4d4f;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        font-size: 12px;
        flex: 0 0 20px;
      }
      .notice-content {
        .notice-title {
          display: flex;
          gap: 8px;
          align-items: center;
          margin-bottom: 4px;
        }
        .level {
          color: #ff4d4f;
          background: #ffecec;
          padding: 2px 6px;
          border-radius: 10px;
          font-size: 12px;
        }
        .text {
          color: #333;
          font-weight: 600;
        }
        .notice-desc {
          color: var(--text-muted);
          font-size: 12px;
        }
      }
    }
    /* 可选：美化滚动条 */
    &::-webkit-scrollbar {
      width: 6px;
    }
    &::-webkit-scrollbar-thumb {
      background: #ccc;
      border-radius: 4px;
    }
    &::-webkit-scrollbar-track {
      background: #f5f5f5;
    }
  }

  /* 自适应优化 */
  @media (max-width: 768px) {
    .chart {
      height: 240px;
    }
    .panel-header {
      padding: 10px 12px !important;
    }
    .stat-card {
      padding: 14px;
      min-height: 88px;
    }
  }
}
</style>
