<template>
  <div style="margin-top: 10px">
    <el-row :gutter="24" justify="space-around">
      <re-col
        v-for="(item, index) in chartData"
        :key="index"
        v-motion
        class="mb-18"
        :value="4"
        :md="12"
        :sm="12"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 80 * (index + 1)
          }
        }"
      >
        <el-card class="line-card" shadow="never">
          <div class="flex justify-between">
            <span class="text-md font-medium">
              {{ item.name }}
            </span>
            <div
              class="w-8 h-8 flex justify-center items-center rounded-md"
              :style="{
                backgroundColor: isDark ? 'transparent' : item.bgColor
              }"
            >
              <IconifyIconOffline
                :icon="item.icon"
                :color="item.color"
                width="18"
                height="18"
              />
            </div>
          </div>
          <div class="flex justify-between items-start mt-3">
            <div class="w-1/2">
              <ReNormalCountTo
                :duration="item.duration"
                :fontSize="'1.6em'"
                :startVal="100"
                :endVal="item.value"
              />
              <!-- <p class="font-medium text-green-500">{{ item.percent }}</p> -->
            </div>
            <!-- <ChartLine
              v-if="item.data.length > 1"
              class="w-1/2!"
              :color="item.color"
              :data="item.data"
            /> -->
            <!-- <ChartRound v-else class="w-1/2!" /> -->
          </div>
        </el-card>
      </re-col>

      <re-col
        v-motion
        class="mb-18"
        :value="18"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 400
          }
        }"
      >
        <el-card class="bar-card" shadow="never">
          <div class="flex justify-between">
            <span class="text-md font-medium">一周概览</span>
            <Segmented v-model="curWeek" :options="optionsBasis" />
          </div>
          <div class="flex justify-between items-start mt-3">
            <ChartBar
              :attendPerson="barChartData[curWeek].attendPerson"
              :arrivePerson="barChartData[curWeek].arrivePerson"
              :onlinePerson="barChartData[curWeek].onlinePerson"
            />
          </div>
        </el-card>
      </re-col>

      <re-col
        v-motion
        class="mb-[18px]"
        :value="6"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 480
          }
        }"
      >
        <el-card shadow="never">
          <div class="flex justify-between">
            <span class="text-md font-medium">基站项目分布</span>
          </div>
          <el-scrollbar height="373" class="mt-3 show-scrollbar">
            <div class="scroll-content">
              <div
                v-for="(item, index) in progressData"
                :key="index"
                :class="[
                  'flex',
                  'justify-between',
                  'items-start',
                  index === 0 ? 'mt-8' : 'mt-[2.15rem]'
                ]"
              >
                <el-progress
                  :indeterminate="true"
                  :text-inside="true"
                  :percentage="item.percentage"
                  :stroke-width="21"
                  :color="item.color"
                  striped
                  striped-flow
                  :duration="item.duration"
                >
                  <span style="margin-right: 5px">{{ item.ancNum }}</span>
                </el-progress>
                <span
                  class="text-nowrap ml-2 text-text_color_regular text-sm"
                  style="width: 120px"
                >
                  {{ item.projName }}
                </span>
              </div>
            </div>
          </el-scrollbar>
        </el-card>
      </re-col>

      <re-col
        v-motion
        class="mb-[18px]"
        :value="18"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 560
          }
        }"
      >
        <el-card shadow="never" class="h-[380px]">
          <div class="flex justify-between">
            <span class="text-md font-medium">数据统计</span>
          </div>
          <WelcomeTable class="mt-3" />
        </el-card>
      </re-col>

      <re-col
        v-motion
        class="mb-[18px]"
        :value="6"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 640
          }
        }"
      >
        <el-card shadow="never" class="h-[380px]">
          <div class="flex justify-between">
            <span class="text-md font-medium">最新动态</span>
          </div>
          <el-scrollbar max-height="504" class="mt-3">
            <el-timeline>
              <el-timeline-item
                v-for="(item, index) in tableData"
                :key="index"
                center
                placement="top"
                :icon="
                  markRaw(
                    useRenderFlicker({
                      background: randomGradient({
                        randomizeHue: true
                      })
                    })
                  )
                "
                :timestamp="dayjs(item.tm).format('YYYY-MM-DD hh:mm:ss')"
              >
                <p class="text-text_color_regular text-sm">
                  {{ `新增 1 条考勤记录，考勤人数 ${item.attendPerson}` }}
                </p>
              </el-timeline-item>
            </el-timeline>
          </el-scrollbar>
        </el-card>
      </re-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, markRaw, onMounted } from "vue";
import ReCol from "@/components/ReCol";
import { useDark, randomGradient, dayjs } from "./utils";
import WelcomeTable from "./components/table/index.vue";
import { ReNormalCountTo } from "@/components/ReCountTo";
import { useRenderFlicker } from "@/components/ReFlicker";
import { ChartBar, ChartLine, ChartRound } from "./components/charts";
import Segmented, { type OptionsType } from "@/components/ReSegmented";
import { chartData, barChartData, progressData, tableData } from "./data";
import { fetchHisAttend } from "@/api/attend";
import Attend from "@/model/attend.js";

defineOptions({
  name: "Welcome"
});

const vGlobal = window.vueGlobal;
const { isDark } = useDark();

const attends = ref([]);

const now = new Date();
const thisWeekBegin = new Date(
  now.getFullYear(),
  now.getMonth(),
  now.getDate() - now.getDay()
);
const thisWeekEnd = new Date(
  now.getFullYear(),
  now.getMonth(),
  now.getDate() - now.getDay() + 6
);
const lastWeekBegin = new Date(
  thisWeekBegin.getFullYear(),
  thisWeekBegin.getMonth(),
  thisWeekBegin.getDate() - 7
);
const lastWeekEnd = new Date(
  thisWeekBegin.getFullYear(),
  thisWeekBegin.getMonth(),
  thisWeekBegin.getDate() - 1
);

let curWeek = ref(1); // 0上周、1本周
const optionsBasis: Array<OptionsType> = [
  {
    label: "上周"
  },
  {
    label: "本周"
  }
];

const firstRun = () => {
  chartData.value[0].value = vGlobal.vecProject.length; //  项目总数量
  chartData.value[1].value = 0; //  运行项目数量
  chartData.value[2].value = 0; //  人员数量
  chartData.value[3].value = vGlobal.vecAnchor.length; //  基站数量
  chartData.value[4].value = 0; //  在线基站数
  chartData.value[5].value = vGlobal.vecTag.length; //  标签数量

  let cntProjRun = 0;
  progressData.value.splice(0);

  for (const proj of vGlobal.vecProject) {
    if (proj.status == 2) {
      continue;
    }
    cntProjRun++;

    chartData.value[2].value += proj.persons.length;
    let ancProjNum = 0;
    for (const anc of vGlobal.vecAnchor) {
      if (Number(anc.projId) == Number(proj.id)) {
        ancProjNum++;
      }
    }
    const percent = Math.floor((ancProjNum * 100.0) / vGlobal.vecAnchor.length);
    progressData.value.push({
      projName: proj.name,
      percentage: percent,
      duration: 5,
      color: "#41b6ff",
      ancNum: ancProjNum
    });
  }

  chartData.value[1].value = cntProjRun; //  运行项目数量
};

const statAttend = () => {
  let i = 0,
    j = 0;
  for (i = 0; i < 2; i++) {
    const weekData = barChartData.value[i];
    for (j = 0; j < 7; j++) {
      weekData.attendPerson[j] = 0;
      weekData.arrivePerson[j] = 0;
      weekData.onlinePerson[j] = 0;
    }
  }

  let idx = 0;
  let curAtDate = new Date(
    lastWeekBegin.getFullYear(),
    lastWeekBegin.getMonth(),
    lastWeekBegin.getDate() + 2
  );
  let numDay = 0;
  console.log("numDay 0", numDay, curAtDate);

  for (const attend of attends.value) {
    while (Number(attend["tm"]) > curAtDate.getTime()) {
      numDay++;
      curAtDate = new Date(
        lastWeekBegin.getFullYear(),
        lastWeekBegin.getMonth(),
        lastWeekBegin.getDate() + numDay + 2
      );
    }
    console.log("numDay", numDay, curAtDate);

    let weekIdx = Math.floor(numDay / 7);
    let dayIdx = numDay % 7;

    let cntArrive = 0;
    let cntOnline = 0;
    for (const item of attend.items) {
      if (Number(item["confirm"])) {
        cntArrive++;
      }
      if (Number(item["rssi"]) != 0) {
        cntOnline++;
      }
    }

    const weekData = barChartData.value[weekIdx];
    console.log("barChartData", barChartData.value, weekIdx, weekData);
    weekData.attendPerson[dayIdx] += attend.items.length;
    weekData.arrivePerson[dayIdx] += cntArrive;
    weekData.onlinePerson[dayIdx] += cntOnline;
  }
};

const schedule = () => {
  chartData.value[4].value = 0;
  for (const v of vGlobal.vecAnchor) {
    if (v.isOnline) {
      chartData.value[4].value++;
    }
  }

  const queryParams = {
    beginTime: lastWeekBegin.getTime(),
    endTime: thisWeekEnd.getTime(),
    sortMode: 1
  };
  fetchHisAttend(queryParams).then(res => {
    if (res.success) {
      attends.value = [];
      tableData.value = [];

      for (const item of res.items) {
        const obj = JSON.parse(item.jstr);
        const attend = new Attend(obj);
        attends.value.push(attend);
        attend.ancAddr = Number(item["ancAddr"]) || 0;

        let cntArrive = 0;
        let cntOnline = 0;
        for (const item of attend.items) {
          if (Number(item["confirm"])) {
            cntArrive++;
          }
          if (Number(item["rssi"]) != 0) {
            cntOnline++;
          }
        }

        tableData.value.push({
          tm: attend.tm,
          projName: vGlobal.getProjName(attend.projId),
          locName: vGlobal.getLocName(attend.projId, attend.locId),
          ancAddr: attend.ancAddr,
          attendPerson: attend.items.length,
          arrivePerson: cntArrive,
          onlinePerson: cntOnline,
          items: attend.items
        });

        tableData.value.reverse();
      }

      statAttend();
    }
  });
};

onMounted(() => {
  const ci = setInterval(() => {
    if (vGlobal.isInited()) {
      clearInterval(ci);
      firstRun();

      schedule();
      // setInterval(() => {
      //   schedule();
      // }, 1000 * 10);
    }
  }, 100);
});
</script>

<style lang="scss" scoped>
// 移除过度使用的!important，改用更具体的选择器提高优先级
:deep(.el-card) {
  --el-card-border-color: none;

  .el-progress--line {
    width: 85%;
  }

  .el-progress-bar__innerText {
    font-size: 15px;
  }

  // 修复滚动条显示问题
  .el-scrollbar:not(.show-scrollbar) .el-scrollbar__bar {
    display: none;
  }

  .el-timeline-item {
    margin: 0 6px;
  }
}

// 增强滚动条样式兼容性
.el-scrollbar__wrap {
  overflow-x: hidden;
}

:deep(.el-scrollbar__bar.is-vertical) {
  right: 0 !important;
  width: 6px;
  opacity: 0.6; /* 确保可见性 */
}

// 修复卡片间距问题
.line-card,
.bar-card {
  margin-bottom: -48px;
}

// 确保动画兼容性
:deep(.v-motion) {
  backface-visibility: hidden; /* 解决动画闪烁问题 */
}
</style>
