<script setup lang="ts">
defineOptions({
  name: "Welcome"
});
import { ref, markRaw, reactive, onMounted } from "vue";
import dayjs from "dayjs";
import ReCol from "@/components/ReCol";
import { useRouter } from "vue-router";
import ChartBar from "./components/ChartBar.vue";
import { useRenderFlicker } from "@/components/ReFlicker";
import { useDark, cloneDeep, randomGradient, isString } from "@pureadmin/utils";

import GroupLine from "@iconify-icons/ri/stack-line";
import Question from "@iconify-icons/ri/question-answer-line";
import CheckLine from "@iconify-icons/ri/chat-check-line";
import { getUserQueryStatisticsAPI } from "@/api/user";
import { QueryCodeLogInfo } from "types/code";
import { getCodeLogListAPI } from "@/api/code";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { $t } from "@/plugins/i18n";
const router = useRouter();
const { isDark } = useDark();
const getRandomIntBetween = (min: number, max: number) => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

/** 数据统计 */
const tableData = Array.from({ length: 30 }).map((_, index) => {
  return {
    id: index + 1,
    requiredNumber: getRandomIntBetween(13500, 19999),
    questionNumber: getRandomIntBetween(12600, 16999),
    resolveNumber: getRandomIntBetween(13500, 17999),
    satisfaction: getRandomIntBetween(95, 100),
    date: dayjs().subtract(index, "day").format("YYYY-MM-DD")
  };
});

/**用户统计 */
const userStatisticsData = reactive({
  /**今日统计 */
  today_count: 0,
  /**当月统计 */
  this_month_count: 0,
  /**上月统计 */
  last_month_count: 0,
  /**最近14天内成功查询统计 */
  before_14day_count_success: [
    {
      /**日期 */
      date: "",
      /**查询次数 */
      count: 0
    }
  ],
  /**最近14天内失败查询统计 */
  before_14day_count_fail: [
    {
      /**日期 */
      date: "",
      /**查询次数 */
      count: 0
    }
  ]
});
/**日期列表 */
const dates = ref<string[]>([]);
/**成功查询列表 */
const successData = ref<number[]>([]);
/**失败查询列表 */
const failData = ref<number[]>([]);
/**获取用户统计信息 */
const getUserStatistics = async () => {
  const res = await getUserQueryStatisticsAPI();
  if (res.success) {
    Object.assign(userStatisticsData, res.data);
    dates.value = res.data.before_14day_count_success.map(item => item.date);
    successData.value = res.data.before_14day_count_success.map(
      item => item.count
    );
    failData.value = res.data.before_14day_count_fail.map(item => item.count);
  }
};

/**活动列表 */
const codeLogList = ref<QueryCodeLogInfo[]>([]);

/**获取日历活动 */
const getActivityCalendar = async () => {
  let [startTime, endTime] = date.value;
  const res = await getCodeLogListAPI({
    page: 1,
    pageSize: 99999999999,
    startTime: startTime,
    endTime: endTime
  });
  if (res.success) {
    codeLogList.value = res.data.result;
    codeLogList.value = cloneDeep(codeLogList.value)
      .map((item: QueryCodeLogInfo) => {
        return Object.assign(item, {
          operation_time: `${dayjs(item.operation_time).format("YYYY年MM月DD日 HH:mm:ss")}`
        });
      })
      .sort((a: QueryCodeLogInfo, b: QueryCodeLogInfo) => {
        return b.operation_time < a.operation_time ? -1 : 1;
      });
  }
};

/**最近时间选择 */
const shortcuts = [
  {
    text: "上周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: "上个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: "三个月前",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    }
  },
  {
    text: "半年前",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
      return [start, end];
    }
  },
  {
    text: "一年前",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
      return [start, end];
    }
  },
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 3);
      return [start, end];
    }
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 15);
      return [start, end];
    }
  },
  {
    text: "最近三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 45);
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 45);
      return [start, end];
    }
  },
  {
    text: "最近半年",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 90);
      return [start, end];
    }
  },
  {
    text: "最近一年",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 180);
      return [start, end];
    }
  }
];
/**日期选择器时间 */
const date = ref();
/**日期选择器变化 */
const onChange = async (e: any) => {
  await getActivityCalendar();
};
/**处理详情 */
const onClickDetails = (row: QueryCodeLogInfo) => {
  let params = { detailsId: row.id };
  Object.keys(params).forEach(param => {
    if (!isString(params[param])) {
      params[param] = params[param].toString();
    }
  });
  useMultiTagsStoreHook().handleTags("push", {
    path: "/code/log/details/:detailsId",
    name: "QueryCodedetails",
    params: params,
    meta: {
      title: $t("menus:QueryCodedetails")
    },
    dynamicLevel: 1
  });
  router.push({
    name: "QueryCodedetails",
    params: params
  });
};
/**挂载执行 */
onMounted(async () => {
  // 获取当前日期
  const currentDate = new Date();

  // 获取前三个月的日期
  let threeDaysAgo = new Date(currentDate);
  threeDaysAgo.setDate(currentDate.getDate() - 1);
  let threeDaysAgoTimestamp = threeDaysAgo.getTime();
  date.value = [threeDaysAgoTimestamp, currentDate.getTime()];
  await getUserStatistics();
  await getActivityCalendar();
});
</script>

<template>
  <div>
    <el-row :gutter="24" justify="space-around">
      <re-col
        v-motion
        class="mb-[18px]"
        :value="8"
        :md="12"
        :sm="12"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 80
          }
        }"
      >
        <el-card class="line-card" shadow="never">
          <div class="flex justify-between">
            <span class="text-md font-medium"> 今日查询 </span>
            <div
              class="w-8 h-8 flex justify-center items-center rounded-md"
              :style="{
                backgroundColor: isDark ? 'transparent' : '#effaff'
              }"
            >
              <IconifyIconOffline
                :icon="GroupLine"
                color="#41b6ff"
                width="18"
              />
            </div>
          </div>
          <div class="flex justify-center items-start mt-3">
            <div class="w-1/2 text-center">
              <h2 class="font-bold text-blue-500">
                {{ userStatisticsData.today_count }}
              </h2>
            </div>
          </div>
        </el-card>
      </re-col>
      <re-col
        v-motion
        class="mb-[18px]"
        :value="8"
        :md="12"
        :sm="12"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 80
          }
        }"
      >
        <el-card class="line-card" shadow="never">
          <div class="flex justify-between">
            <span class="text-md font-medium"> 当月查询 </span>
            <div
              class="w-8 h-8 flex justify-center items-center rounded-md"
              :style="{
                backgroundColor: isDark ? 'transparent' : '#fff5f4'
              }"
            >
              <IconifyIconOffline :icon="Question" color="#e85f33" width="18" />
            </div>
          </div>
          <div class="flex justify-center items-start mt-3">
            <div class="w-1/2 text-center">
              <h2 class="font-bold text-blue-500">
                {{ userStatisticsData.this_month_count }}
              </h2>
            </div>
          </div>
        </el-card>
      </re-col>
      <re-col
        v-motion
        class="mb-[18px]"
        :value="8"
        :md="12"
        :sm="12"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 80
          }
        }"
      >
        <el-card class="line-card" shadow="never">
          <div class="flex justify-between">
            <span class="text-md font-medium"> 上月查询 </span>
            <div
              class="w-8 h-8 flex justify-center items-center rounded-md"
              :style="{
                backgroundColor: isDark ? 'transparent' : '#eff8f4'
              }"
            >
              <IconifyIconOffline
                :icon="CheckLine"
                color="#26ce83"
                width="18"
              />
            </div>
          </div>
          <div class="flex justify-center items-start mt-3">
            <div class="w-1/2 text-center">
              <h2 class="font-bold text-blue-500">
                {{ userStatisticsData.last_month_count }}
              </h2>
            </div>
          </div>
        </el-card>
      </re-col>

      <re-col
        v-motion
        class="mb-[18px]"
        :value="16"
        :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>
          </div>
          <div class="flex justify-between items-start mt-3">
            <ChartBar
              :dates="dates"
              :successData="successData"
              :failData="failData"
            />
          </div>
        </el-card>
      </re-col>
      <re-col
        v-motion
        class="mb-[18px]"
        :value="8"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 640
          }
        }"
      >
        <el-card shadow="never">
          <div class="flex justify-between flex-wrap">
            <el-date-picker
              v-model="date"
              type="daterange"
              unlink-panels
              format="YYYY年MM月DD日"
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="x"
              :shortcuts="shortcuts"
              @change="onChange"
            />
            <div class="text-md font-medium mt-3 text-center w-full">
              查询动态
            </div>
          </div>
          <el-scrollbar max-height="500" class="mt-3 !h-[518px]">
            <el-timeline v-if="codeLogList.length">
              <el-timeline-item
                v-for="(item, index) in codeLogList"
                :key="index"
                class="ml-2"
                center
                placement="top"
                :icon="
                  markRaw(
                    useRenderFlicker({
                      background: randomGradient({
                        randomizeHue: true
                      })
                    })
                  )
                "
                :timestamp="
                  item.operation_time as unknown as unknown as unknown as string
                "
                @click="onClickDetails(item)"
              >
                <p class="text-text_color_regular text-sm">
                  <el-tag type="primary" effect="plain">
                    {{ item.department_name }}
                  </el-tag>
                  ——
                  <el-tag type="warning" effect="plain">
                    {{ item.operator_nickname }}
                  </el-tag>
                  {{
                    `查询了${item.query_count}条数据，成功匹配${item.result_count}条,耗时${item.cost_time.toFixed(2)}ms`
                  }}
                </p>
              </el-timeline-item>
            </el-timeline>
            <el-empty v-else description="暂无查询动态" class="!h-[540px]" />
          </el-scrollbar>
        </el-card>
      </re-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-card) {
  --el-card-border-color: none;

  /* 解决概率进度条宽度 */
  .el-progress--line {
    width: 85%;
  }

  /* 解决概率进度条字体大小 */
  .el-progress-bar__innerText {
    font-size: 15px;
  }

  /* 隐藏 el-scrollbar 滚动条 */
  .el-scrollbar__bar {
    display: none;
  }

  /* el-timeline 每一项上下、左右边距 */
  .el-timeline-item {
    margin: 0 6px;
  }
}

.main-content {
  margin: 20px 20px 0 !important;
}
</style>
