<template>
  <div class="dashboard-container">
    <el-card shadow="never" class="mt-2">
      <div class="flex flex-wrap">
        <!-- 左侧问候语区域 -->
        <div class="flex-1 flex items-start">
          <img
            class="w80px h80px rounded-full"
            :src="userStore.userInfo.avatar"
          />
          <div class="ml-5">
            <p>{{ greetings }}</p>
            <p class="text-sm text-gray">
              今日天气晴朗，气温在15℃至25℃之间，东南风。
            </p>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 第一行 -->
    <el-row :gutter="10" class="mt-5">
      <el-col :span="10" :xs="24" class="mb-xs-3">
        <el-card shadow="never" class="h-full flex flex-col">
          <template #header>
            <div class="flex-x-between">
              <span class="text-gray">快捷访问</span>
              <el-tag type="danger" size="small">shortcut</el-tag>
            </div>
          </template>

          <div class="flex-x-between mt-2 text-sm text-gray">
            <span>最近访问</span>
          </div>
          <div class="flex-x-between mt-2 flex-1">
            <div class="flex flex-wrap gap-1">
              <el-button
                type="primary"
                text
                bg
                class="mb-1"
                size="small"
                @click="
                  router.push(
                    '/outpatient-emergency/index/outpatient-emergency-EMR'
                  )
                "
              >
                <i class="icon-system me-1"></i>
                门诊病历
              </el-button>
              <el-button
                type="primary"
                text
                bg
                class="mb-1"
                size="small"
                @click="
                  router.push(
                    '/outpatient-emergency/index/outpatient-diagnosis'
                  )
                "
              >
                <i class="icon-system me-1"></i>
                门诊诊断
              </el-button>
              <el-button
                type="primary"
                text
                bg
                class="mb-1"
                size="small"
                @click="router.push('/outpatient-emergency/index/prescription')"
              >
                <i class="icon-system me-1"></i>
                处方管理
              </el-button>
              <el-button
                type="primary"
                text
                bg
                class="mb-1"
                size="small"
                @click="
                  router.push(
                    '/outpatient-emergency/index/examination-request-form'
                  )
                "
              >
                <i class="icon-system me-1"></i>
                检查申请单
              </el-button>
            </div>
          </div>
          <div class="flex-x-between mt-2 text-sm text-gray">
            <span>自定义节点</span>
          </div>
          <div class="flex-x-between mt-2 flex-1">
            <div class="flex flex-wrap gap-1">
              <el-button
                type=""
                text
                bg
                class="mb-1"
                size="small"
                @click="
                  router.push('/residency/index/hospitalization-diagnosis')
                "
              >
                <i class="icon-system me-1"></i>
                诊断手术
              </el-button>
              <el-button
                type=""
                text
                bg
                class="mb-1"
                size="small"
                @click="
                  router.push(
                    '/outpatient-emergency/index/examination-request-form'
                  )
                "
              >
                <i class="icon-system me-1"></i>
                检查申请单
              </el-button>
              <el-button
                type=""
                text
                bg
                class="mb-1"
                size="small"
                @click="router.push('/outpatient-emergency/index/prescription')"
              >
                <i class="icon-system me-1"></i>
                处方管理
              </el-button>
              <el-button type="" text bg class="mb-1" size="small">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6" :xs="24">
        <el-skeleton :loading="visitStatsLoading" :rows="5" animated>
          <template #template>
            <el-card>
              <template #header>
                <div>
                  <el-skeleton-item variant="h3" style="width: 40%" />
                  <el-skeleton-item
                    variant="rect"
                    style="float: right; width: 1em; height: 1em"
                  />
                </div>
              </template>

              <div class="flex-x-between">
                <el-skeleton-item variant="text" style="width: 30%" />
                <el-skeleton-item
                  variant="circle"
                  style="width: 2em; height: 2em"
                />
              </div>
              <div class="mt-5 flex-x-between">
                <el-skeleton-item variant="text" style="width: 50%" />
                <el-skeleton-item variant="text" style="width: 1em" />
              </div>
            </el-card>
          </template>
          <template v-if="!visitStatsLoading">
            <el-card shadow="never" class="h-full flex flex-col">
              <template #header>
                <div class="flex-x-between">
                  <span class="text-gray">待诊量</span>
                  <el-tag type="primary" size="small">日</el-tag>
                </div>
              </template>

              <div class="flex-x-between mt-2 flex-1">
                <div class="flex-y-center">
                  <span class="text-lg">
                    {{ Math.round(transitionPvCount) }}
                  </span>
                  <span
                    :class="[
                      'text-xs',
                      'ml-2',
                      computeGrowthRateClass(visitStatsData.pvGrowthRate),
                    ]"
                  >
                    较昨日
                    <el-icon>
                      <Top v-if="visitStatsData.pvGrowthRate > 0" />
                      <Bottom v-else-if="visitStatsData.pvGrowthRate < 0" />
                    </el-icon>
                    {{ formatGrowthRate(visitStatsData.pvGrowthRate) }}
                  </span>
                </div>
                <div class="i-svg:browser w-8 h-8"></div>
              </div>

              <div class="flex-x-between mt-2 text-sm text-gray">
                <span>已就诊量</span>
                <span>{{ Math.round(transitionTotalPvCount) }}</span>
              </div>
            </el-card>
          </template>
        </el-skeleton>
      </el-col>

      <!-- 重要通知 -->
      <el-col :span="8" :xs="24" class="mb-xs-3">
        <el-card
          style="max-width: 480px"
          shadow="never"
          class="h-full flex flex-col"
        >
          <template #header>
            <div>
              <span class="text-gray">公告</span>
            </div>
          </template>
          <li>
            <el-link
              href="#"
              style="text-decoration: none; color: #333"
              class="mb-2"
            >
              医生工作站使用手册
            </el-link>
          </li>
          <li>
            <el-link
              href="#"
              style="text-decoration: none; color: #333"
              class="mb-2"
            >
              医生工作站操作视频
            </el-link>
          </li>
          <li>
            <el-link
              href="#"
              style="text-decoration: none; color: #333"
              class="mb-2"
            >
              新版本发布公告
            </el-link>
          </li>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mt-5">
      <!-- 访问趋势统计图 -->
      <el-col :xs="24" :span="16">
        <el-card>
          <template #header>
            <div class="flex-x-between">
              <span>接诊趋势</span>
              <el-radio-group v-model="visitTrendDateRange" size="small">
                <el-radio-button :value="7">近7天</el-radio-button>
                <el-radio-button :value="30">近30天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <ECharts :options="visitTrendChartOptions" height="400px" />
        </el-card>
      </el-col>
      <!-- 最新动态 -->
      <el-col :xs="24" :span="8">
        <el-card>
          <template #header>
            <div class="flex-x-between">
              <span class="header-title">新闻动态</span>
              <el-link
                type="primary"
                :underline="false"
                href="https://gitee.com/youlaiorg/vue3-element-admin/releases"
                target="_blank"
              >
                完整记录
                <el-icon class="link-icon"><TopRight /></el-icon>
              </el-link>
            </div>
          </template>

          <el-scrollbar height="400px">
            <el-timeline class="p-3">
              <el-timeline-item
                v-for="(item, index) in vesionList"
                :key="index"
                :timestamp="item.date"
                placement="top"
                :color="index === 0 ? '#67C23A' : '#909399'"
                :hollow="index !== 0"
                size="large"
              >
                <div
                  class="version-item"
                  :class="{ 'latest-item': index === 0 }"
                >
                  <div>
                    <el-text tag="strong">{{ item.title }}</el-text>
                    <el-tag
                      v-if="item.tag"
                      :type="index === 0 ? 'success' : 'info'"
                      size="small"
                    >
                      {{ item.tag }}
                    </el-tag>
                  </div>

                  <el-text class="version-content">{{ item.content }}</el-text>

                  <div v-if="item.link">
                    <el-link
                      :type="index === 0 ? 'primary' : 'info'"
                      :href="item.link"
                      target="_blank"
                      :underline="false"
                    >
                      详情
                      <el-icon class="link-icon"><TopRight /></el-icon>
                    </el-link>
                  </div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </el-scrollbar>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});

import { dayjs } from "element-plus";
import LogAPI, { VisitStatsVO, VisitTrendVO } from "@/api/system/log.api";
import { useUserStore } from "@/store/modules/user";
import { formatGrowthRate } from "@/utils";
import { useTransition, useDateFormat } from "@vueuse/core";
import { Connection, Failed } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
const router = useRouter();

interface VersionItem {
  id: string;
  title: string; // 版本标题（如：v2.4.0）
  date: string; // 发布时间
  content: string; // 版本描述
  link: string; // 详情链接
  tag?: string; // 版本标签（可选）
}

const userStore = useUserStore();

// 当前通知公告列表
const vesionList = ref<VersionItem[]>([
  {
    id: "3",
    title:
      "我院当选全国中医院胸痛中心专家委员会副主任委员单位 助力全省中西医结合胸痛救治体系建设",
    date: "2025年04月28日 21:49",
    content:
      "4月25日-27日，由国家放射与治疗临床医学研究中心、苏州工业园区东方华夏心血管健康研究院、广东省胸痛中心协会、中国介入心脏病学杂志联合主办的第十四届中国胸痛中心大会在苏州召开。本届大会以“探索中西医结合救治模式，构建特色胸痛诊疗体系”为主题，旨在推动中医医院胸痛中心规范化建设，强化中西医协同救治能力。",
    link: "https://mp.weixin.qq.com/s/jcBVwmPiAhHLycxvWAL5pA",
    tag: "医院动态",
  },
  {
    id: "2",
    title: "我院专家参加中华中医药学会第七届岐黄论坛",
    date: "2025年04月28日21:49",
    content:
      "4月26日，由中华中医药学会主办的第七届岐黄论坛在京举行。本届论坛以“融合赋能，促进传承创新发展”为主题，邀请到两院院士、国医大师、国内知名专家等开展学术报告，我院副院长（主持行政工作）唐健元出席会议。",
    link: "https://mp.weixin.qq.com/s/QwoLdpNAWqXKzJJUbcjnAQ",
    tag: "学术会议",
  },
  {
    id: "1",
    title: "我院在成都中医药大学2025年五四表彰大会中荣获多项荣誉",
    date: "2025年05月04日 09:51",
    content:
      "为弘扬传承五四精神，凝聚青年力量，强化价值引领，深化育人成效，4月29日，成都中医药大学2025年五四表彰暨先进事迹交流会在百会堂演播大厅召开。学校党委书记张泽钧，党委副书记杨静，党委副书记、纪委书记郑学斌，党委常委、组织部部长赵凌出席会议，会议由校团委书记田晓放主持。",
    link: "https://mp.weixin.qq.com/s/H9_aLgnDF1m7M9kjsxtbMg",
    tag: "青春奋进",
  },
]);

// 当前时间（用于计算问候语）
const currentDate = new Date();

// 问候语：根据当前小时返回不同问候语
const greetings = computed(() => {
  const hours = currentDate.getHours();
  const nickname = userStore.userInfo.nickname;
  if (hours >= 6 && hours < 8) {
    return "晨起披衣出草堂，轩窗已自喜微凉🌅！";
  } else if (hours >= 8 && hours < 12) {
    return `上午好，${nickname}！`;
  } else if (hours >= 12 && hours < 18) {
    return `下午好，${nickname}！`;
  } else if (hours >= 18 && hours < 24) {
    return `晚上好，${nickname}！`;
  } else {
    return "偷偷向银河要了一把碎星，只等你闭上眼睛撒入你的梦中，晚安🌛！";
  }
});

// 访客统计数据加载状态
const visitStatsLoading = ref(true);
// 访客统计数据
const visitStatsData = ref<VisitStatsVO>({
  todayUvCount: 12,
  uvGrowthRate: 0.2,
  totalUvCount: 12,
  todayPvCount: 12,
  pvGrowthRate: 0.2,
  totalPvCount: 34,
});

// 数字过渡动画
const transitionUvCount = useTransition(
  computed(() => visitStatsData.value.todayUvCount),
  {
    duration: 1000,
    transition: [0.25, 0.1, 0.25, 1.0], // CSS cubic-bezier
  }
);

const transitionTotalUvCount = useTransition(
  computed(() => visitStatsData.value.totalUvCount),
  {
    duration: 1200,
    transition: [0.25, 0.1, 0.25, 1.0],
  }
);

const transitionPvCount = useTransition(
  computed(() => visitStatsData.value.todayPvCount),
  {
    duration: 1000,
    transition: [0.25, 0.1, 0.25, 1.0],
  }
);

const transitionTotalPvCount = useTransition(
  computed(() => visitStatsData.value.totalPvCount),
  {
    duration: 1200,
    transition: [0.25, 0.1, 0.25, 1.0],
  }
);

// 访问趋势日期范围（单位：天）
const visitTrendDateRange = ref(7);
// 访问趋势图表配置
const visitTrendChartOptions = ref();

/**
 * 获取访客统计数据
 */
const fetchVisitStatsData = () => {
  LogAPI.getVisitStats()
    .then((data) => {
      visitStatsData.value = data;
    })
    .finally(() => {
      visitStatsLoading.value = false;
    });
};

/**
 * 获取访问趋势数据，并更新图表配置
 */
const fetchVisitTrendData = () => {
  const startDate = dayjs()
    .subtract(visitTrendDateRange.value - 1, "day")
    .toDate();
  const endDate = new Date();

  LogAPI.getVisitTrend({
    startDate: dayjs(startDate).format("YYYY-MM-DD"),
    endDate: dayjs(endDate).format("YYYY-MM-DD"),
  }).then((data) => {
    updateVisitTrendChartOptions(data);
  });
};

/**
 * 更新访问趋势图表的配置项
 *
 * @param data - 访问趋势数据
 */
const updateVisitTrendChartOptions = (data: VisitTrendVO) => {
  console.log("Updating visit trend chart options");

  visitTrendChartOptions.value = {
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["门诊接诊量", "急诊接诊量"],
      bottom: 0,
    },
    grid: {
      left: "1%",
      right: "5%",
      bottom: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: data.dates,
    },
    yAxis: {
      type: "value",
      splitLine: {
        show: true,
        lineStyle: {
          type: "dashed",
        },
      },
    },
    series: [
      {
        name: "门诊接诊量",
        type: "line",
        data: data.pvList,
        areaStyle: {
          color: "rgba(64, 158, 255, 0.1)",
        },
        smooth: true,
        itemStyle: {
          color: "#4080FF",
        },
        lineStyle: {
          color: "#4080FF",
        },
      },
      {
        name: "急诊接诊量",
        type: "line",
        data: data.ipList,
        areaStyle: {
          color: "rgba(103, 194, 58, 0.1)",
        },
        smooth: true,
        itemStyle: {
          color: "#67C23A",
        },
        lineStyle: {
          color: "#67C23A",
        },
      },
    ],
  };
};

/**
 * 根据增长率计算对应的 CSS 类名
 *
 * @param growthRate - 增长率数值
 */
const computeGrowthRateClass = (growthRate?: number): string => {
  if (!growthRate) {
    return "text-[--el-color-info]";
  }
  if (growthRate > 0) {
    return "text-[--el-color-danger]";
  } else if (growthRate < 0) {
    return "text-[--el-color-success]";
  } else {
    return "text-[--el-color-info]";
  }
};

// 监听访问趋势日期范围的变化，重新获取趋势数据
watch(
  () => visitTrendDateRange.value,
  (newVal) => {
    console.log("Visit trend date range changed:", newVal);
    fetchVisitTrendData();
  },
  { immediate: true }
);

// 组件挂载后加载访客统计数据和通知公告数据
onMounted(() => {
  fetchVisitStatsData();
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  padding: 24px;

  .github-corner {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    border: 0;
  }

  .version-item {
    padding: 16px;
    margin-bottom: 12px;
    background: var(--el-fill-color-lighter);
    border-radius: 8px;
    transition: all 0.2s;

    &.latest-item {
      background: var(--el-color-primary-light-9);
      border: 1px solid var(--el-color-primary-light-5);
    }
    &:hover {
      transform: translateX(5px);
    }
    .version-content {
      margin-bottom: 12px;
      font-size: 13px;
      line-height: 1.5;
      color: var(--el-text-color-secondary);
    }
  }
}
</style>
