<template>
  <my-layout v-if="article" v-loading="loading">
    <layout-main>
      <div class="p-15px bg-white rounded-8px">
        <div class="flex items-center text-16px leading-24px font-semibold">
          <div active-title-bar>【文章-数据总览】</div>
          <div class="mx-8px max-w-1/2 truncate">{{ article.title }}</div>
          <div v-if="canPreview" class="px-10px border-1 border-blue-500 rounded-4px text-blue-500 text-14px leading-24px cursor-pointer font-normal hover:bg-blue-50" @click="preview(article)">预览</div>
        </div>
        <el-row class="mt-20px">
          <el-col v-for="col in countCol" :key="col.key" :span="6">
            <div class="text-center font-semibold">
              <div class="text-14px">{{ col.label }}</div>
              <div class="mt-10px text-18px">{{ count[col.key] || 0 }}</div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div v-loading="chartLoading" class="mt-15px p-15px bg-white rounded-8px">
        <div class="flex items-center justify-between mb-20px">
          <div active-title-bar class="flex-shrink-0 text-16px leading-24px font-semibold">趋势</div>
          <div class="flex items-center text-14px">
            <div class="mr-10px">统计日期：</div>
            <div class="mr-10px cursor-pointer hover:text-blue-500" :class="datesType === 7 ? 'text-blue-500' : ''" @click="toggleDatesType(7)">近7天</div>
            <div class="mr-10px cursor-pointer hover:text-blue-500" :class="datesType === 30 ? 'text-blue-500' : ''" @click="toggleDatesType(30)">近30天</div>
            <el-date-picker v-model="dates" :clearable="false" type="daterange"  :unlink-panels="true"
 range-separator="-" value-format="YYYY-MM-DD" @change="changeDates($event)" />
          </div>
        </div>
        <div ref="lineChartRef" class="h-240px"></div>
      </div>
      <div v-loading="tableLoading" class="mt-15px p-15px bg-white rounded-8px">
        <div class="flex items-center justify-between mb-20px">
          <div active-title-bar class="flex-shrink-0 text-16px leading-24px font-semibold">明细统计表</div>
          <el-radio-group v-model="type" @change="changeType">
            <el-radio-button class="w-100px" label="member" value="member">按发送员工</el-radio-button>
            <el-radio-button class="w-100px" label="customer" value="customer">按访问患者</el-radio-button>
          </el-radio-group>
        </div>
        <el-table stripe v-if="type == 'member'" :data="sendList">
          <el-table-column property="name" label="员工">
            <template #default="{ row: { _id, avatar } }">
              <div class="flex items-center">
                <img class="mr-10px h-40px w-40px" :src="avatar || avatarUrl" />
                <ww-user :openid="_id" />
                <!-- <div>{{ row._id }}</div> -->
              </div>
            </template>
          </el-table-column>
          <el-table-column property="count" label="发送次数" />
        </el-table>
        <template v-else>
          <el-table stripe :data="readList">
            <el-table-column property="unionid" label="访客ID" :min-width="360">
              <template #default="{ row: { unionid } }">
                <div class="truncate" :title="unionid">{{ unionid }}</div>
              </template>
            </el-table-column>
            <el-table-column property="count" label="访问次数" :width="240" />
          </el-table>
          <div class="p-15px flex justify-end border-t border-gray-200">
            <el-pagination layout="prev, pager, next, sizes, jumper" :current-page="page" :page-size="pageSize" :page-sizes="[10, 20, 50]" :total="total" @current-change="changePage" @size-change="changeSize"></el-pagination>
          </div>
        </template>
      </div>
    </layout-main>
    <el-dialog :model-value="visible" :width="width" title="文章预览" @close="close">
      <div class="px-15px pt-6px pb-12px text-16px text-dark-500 text-center font-semibold">{{ articleTitle }}</div>
      <iframe class="w-full" style="height: calc(100vh - 360px)" :srcdoc="iframeContent"></iframe>
      <template #footer>
        <div text-center>
          <el-button type="primary" plain class="w-100px" @click="close()">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </my-layout>
  <div v-else v-loading="loading" class="flex flex-col items-center justify-center" style="height: calc(100% - 60px)">
    <empty-data :top="0" title="获取文章详情失败" padding="0 0 15px" text-top="10px" :image-width="200"></empty-data>
  </div>
</template>
<script setup>
import { computed, ref, onActivated } from "vue";
import { useRoute, useRouter } from "vue-router";
import dayjs from "dayjs";
import { getArticle, getArticleStats, getArticleTrend, getArticleSendDetail, getReadDetail } from "@/api/knowledgeBase";
import useElPagination from "@/hooks/useElPagination";
import useLineChart from "@/hooks/useLineChart";
import { isURL } from "@/utils/common";
import usePreviewArticle from "./preview-article";
import EmptyData from "@/components/empty-data.vue";
import MyLayout, { LayoutMain } from "@/components/layout";

// Variables
const route = useRoute();
const router = useRouter();
const article = ref(null);
const count = ref({});
const dates = ref([]);
const datesType = ref(7);
const loading = ref(true);
const chartLoading = ref(false);
const tableLoading = ref(false);
const sendList = ref([]);

const total = ref(0);
const readList = ref([]);
const legendData = ref(["发送次数", "查看次数"]);
const lineChartRef = ref();
const type = ref("member");
const webLink = computed(() => article.value && article.value.link && isURL(article.value.link));
const canPreview = computed(() => webLink.value || article.value.content);
const { content: iframeContent, close, preview, visible, width, articleTitle } = usePreviewArticle();
// Methods
// Constants
const avatarUrl = new URL("@/assets/icons/default-avatar.png", import.meta.url).href;
const countCol = [
  { label: "发送次数", key: "sendCount" },
  { label: "查看次数", key: "readCount" },
  { label: "今日发送次数", key: "todaySendCount" },
  { label: "今日查看次数", key: "todayReadCount" },
];

// Functions
const { xAxisData, seriesData } = useLineChart(lineChartRef, { legendData, grid: { right: 40, left: 20 } });
const { page, pageSize, changePage, changeSize } = useElPagination(getReadRecord);

const getArticleById = async (id) => {
  const { success, data } = await getArticle({ id, corpId: sessionStorage.getItem("corpId") });
  if (success) article.value = data.data;
};

const getStats = async () => {
  const { success, data } = await getArticleStats({ articleId: route.params.id, corpId: sessionStorage.getItem("corpId") });
  if (success) count.value = data.data;
  else count.value = {};
};

const getTrend = async () => {
  chartLoading.value = true;
  const { success, data } = await getArticleTrend({
    articleId: route.params.id,
    corpId: sessionStorage.getItem("corpId"),
    startTime: dates.value[0],
    endTime: dates.value[1],
  });
  xAxisData.value = getAllDatesInRange(dates.value[0], dates.value[1]);
  if (success) {
    const read = data && data.read ? data.read : {};
    const send = data && data.send ? data.send : {};
    seriesData.value = [xAxisData.value.map((i) => send[i] || 0), xAxisData.value.map((i) => read[i] || 0)];
  } else {
    seriesData.value = [[], []];
  }
  chartLoading.value = false;
};

const getAllDatesInRange = (startDate, endDate) => {
  const dates = [];
  let currentDate = dayjs(startDate);
  while (currentDate.isBefore(dayjs(endDate)) || currentDate.isSame(dayjs(endDate))) {
    dates.push(currentDate.format("YYYY-MM-DD"));
    currentDate = currentDate.add(1, "day");
  }
  return dates;
};

const changeDates = (dates) => {
  const [startDate, endDate] = dates;
  const start = dayjs(startDate);
  const end = dayjs(endDate);
  datesType.value = end.diff(start, "day");
  getTrend();
};

const toggleDatesType = (day) => {
  datesType.value = day;
  dates.value = [dayjs().subtract(day, "day").format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")];
  getTrend();
};

const getSendRecord = async () => {
  tableLoading.value = true;
  const { data } = await getArticleSendDetail({
    articleId: route.params.id,
    corpId: sessionStorage.getItem("corpId"),
  });
  sendList.value =
    data && Array.isArray(data.list)
      ? data.list.map((i) => ({
          _id: i._id,
          count: i.count,
          avatar: i.avatarInfo && i.avatarInfo[0] && i.avatarInfo[0].avatar ? i.avatarInfo[0].avatar : "",
        }))
      : [];
  tableLoading.value = false;
};

async function getReadRecord() {
  tableLoading.value = true;
  const { data } = await getReadDetail({
    articleId: route.params.id,
    corpId: sessionStorage.getItem("corpId"),
    page: page.value,
    pageSize: pageSize.value,
  });
  readList.value = data && Array.isArray(data.list) ? data.list : [];
  total.value = data && data.total > 0 ? data.total : 0;
  tableLoading.value = false;
}

const changeType = (val) => {
  type.value = val;
  if (type.value == "member") getSendRecord();
  else {
    page.value = 1;
    getReadRecord();
  }
};

const init = async (id) => {
  loading.value = true;
  if (id) {
    await getArticleById(id);
    if (article.value) {
      dates.value = [dayjs().subtract(7, "day").format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")];
      datesType.value = 7;
      type.value = "member";
      getStats();
      getTrend();
      getSendRecord();
    }
  } else {
    article.value = null;
  }
  loading.value = false;
};

// Lifecycle Hook
onActivated(() => {
  const articleId = article.value ? article.value._id : "";
  if (articleId !== route.params.id || !route.params.id) init(route.params.id);
});
</script>
