<template>
  <div class="home">
    <!--网站概况-->
    <a-row class="top-title search-form">
      <a-col :span="24" class="search-form-container">
        <div style="display: flex; align-items: center">
          <span class="t1"> 站点： </span>
          <select-site @set-site-info="changeUser" selectWidth="300px" />
          <a :href="siteDomain" class="web-link" target="_blank">{{ displaySiteDomain }}</a>
        </div>
      </a-col>
    </a-row>

    <!--基础信息-->
    <a-card title="网站概况">
      <a-row>
        <a-col class="border-right" :span="12">
          <a-spin :spinning="baseInfoLoading">
            <a-row class="web-info">
              <a-col :span="8">
                <div class="web-content">
                  <p class="title">交付状态</p>
                  <p class="content">
                    <span>{{ filter_Null_format(baseInfo.deliveryProgress) }}</span>
                  </p>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="web-content">
                  <p class="title">运行状态</p>
                  <p class="content">
                    <span v-if="baseInfo.runStatus == 0">创建失败</span><span v-if="baseInfo.runStatus == 1">正常运行</span
                    ><span v-if="baseInfo.runStatus == 2">运行异常</span>
                    <span v-if="baseInfo.runStatus == 3">站点停止</span>
                  </p>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="web-content">
                  <p class="title">网站运行</p>
                  <p class="content">
                    <span> {{ filter_Null_format(baseInfo.runDays) }}天 </span>
                  </p>
                </div>
              </a-col>
            </a-row>
          </a-spin>

          <a-steps size="small" style="margin-top: 30px; cursor: pointer" label-placement="vertical" v-model:current="current">
            <a-step disabled v-for="(item, index) in stepData" :key="index" style="cursor: pointer; width: 16.667%">
              <template #icon>
                <a-popover :title="item.title">
                  <template v-if="index < current">
                    <CheckCircle-Outlined :style="{ fontSize: '26px', color: 'green' }" />
                  </template>
                  <template v-else-if="index == current">
                    <ClockCircle-Outlined :style="{ fontSize: '26px', color: '#9b9696' }" />
                  </template>
                  <template v-else>
                    <Lock-Outlined :style="{ fontSize: '26px', color: '#e5e7eb' }" />
                  </template>
                </a-popover>
              </template>
            </a-step>
          </a-steps>
        </a-col>
        <a-col :span="12">
          <a-spin :spinning="baseInfoLoading">
            <a-row class="web-info">
              <a-col :span="8">
                <div class="web-content">
                  <p class="title">套餐类型</p>
                  <p class="content">
                    <span>{{ filter_Null_format(baseInfo.planName) }}</span>
                  </p>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="web-content">
                  <p class="title">创建时间</p>
                  <p class="content">
                    <span>{{ filter_Null_format(baseInfo.createTime) }}</span>
                  </p>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="web-content">
                  <p class="title">预计服务到期时间</p>
                  <p class="content">
                    <span>{{ filter_Null_format(baseInfo.endTime) }}</span>
                  </p>
                </div>
              </a-col>
            </a-row>
          </a-spin>
        </a-col>
      </a-row>
    </a-card>

    <a-row class="r3">
      <a-col :span="24">
        <a-card title="核心数据">
          <a-row class="r5" :gutter="[20, 20]">
            <a-col :span="4" class="border-right">
              <div class="wrap effect">
                <a-spin :spinning="coreInfoLoading">
                  <!--                  <router-link :to="{ path: '/inquiry/list', query: { timeType: 'thisWeek' } }">-->
                  <div class="fr">
                    <p class="title">本周询盘数</p>
                    <p class="theme-color">{{ formatNumber(currentWeekEnquiryCount) }}</p>
                  </div>
                  <!--                  </router-link>-->
                </a-spin>
              </div>
            </a-col>
            <a-col :span="4" class="border-right">
              <div class="wrap effect">
                <a-spin :spinning="coreInfoLoading">
                  <!--                  <router-link :to="{ path: '/inquiry/list', query: { timeType: 'thisMonth' } }">-->
                  <div class="fr">
                    <p class="title">本月询盘数</p>
                    <p class="theme-color">{{ formatNumber(currentMonthEnquiryCount) }}</p>
                  </div>
                  <!--                  </router-link>-->
                </a-spin>
              </div>
            </a-col>
            <a-col :span="4" class="border-right">
              <!--              <router-link :to="{ path: '/inquiry/list' }">-->
              <div class="wrap effect">
                <a-spin :spinning="coreInfoLoading">
                  <div class="fr">
                    <p class="title">累计询盘数</p>
                    <p class="theme-color">{{ formatNumber(totalEnquiryCount) }}</p>
                  </div>
                </a-spin>
              </div>
              <!--              </router-link>-->
            </a-col>
            <template v-if="planType == 'SEO'">
              <a-col :span="4" class="border-right">
                <div class="wrap blue">
                  <a-spin :spinning="coreInfoLoading">
                    <div class="fr">
                      <p class="title">SEO目标达成数</p>
                      <p>{{ formatNumber(appointWordCount) }}</p>
                    </div>
                  </a-spin>
                </div>
              </a-col>
              <a-col :span="4" class="border-right">
                <div class="wrap blue">
                  <a-spin :spinning="coreInfoLoading">
                    <div class="fr">
                      <p class="title">实际达成数</p>
                      <p>{{ formatNumber(currentAchieveCount) }}</p>
                    </div>
                  </a-spin>
                </div>
              </a-col>
              <a-col :span="4">
                <div class="wrap blue">
                  <a-spin :spinning="coreInfoLoading">
                    <div class="fr">
                      <p class="title">目标达成率</p>
                      <p>{{ achievePercent }}</p>
                    </div>
                  </a-spin>
                </div>
              </a-col>
            </template>
            <template v-else>
              <a-col :span="4" class="border-right">
                <div class="wrap blue">
                  <a-spin :spinning="coreInfoLoading">
                    <div class="fr">
                      <p class="title">本周流量</p>
                      <p>{{ formatNumber(thisWeekData.totalUsers) }}</p>
                    </div>
                  </a-spin>
                </div>
              </a-col>
              <a-col :span="4" class="border-right">
                <div class="wrap blue">
                  <a-spin :spinning="coreInfoLoading">
                    <div class="fr">
                      <p class="title">本月流量</p>
                      <p>{{ formatNumber(thisMonthData.totalUsers) }}</p>
                    </div>
                  </a-spin>
                </div>
              </a-col>
              <a-col :span="4">
                <div class="wrap blue">
                  <a-spin :spinning="coreInfoLoading">
                    <div class="fr">
                      <p class="title">累计流量</p>
                      <p>{{ formatNumber(allTimeData.totalUsers) }}</p>
                    </div>
                  </a-spin>
                </div>
              </a-col>
            </template>

            <a-col :span="24" style="margin-top: 10px">
              <a-table
                class="ant-table-striped"
                :loading="coreDetailLoading"
                :columns="columns"
                :pagination="false"
                :data-source="coreDataTable"
                :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
                bordered
              />
              <p style="color: #999; font-size: 13px">注：今日数据每小时更新一次。</p>
            </a-col>

            <a-row class="r5-1">
              <div class="fl">
                <a-button-group>
                  <a-button :type="timeChooseIndex == 7 ? 'primary' : 'default'" class="time-btn" @click="changeTime(7)">最近7天</a-button>
                  <a-button :type="timeChooseIndex == 30 ? 'primary' : 'default'" class="time-btn" @click="changeTime(30)">最近30天</a-button>
                  <a-button :type="timeChooseIndex == 180 ? 'primary' : 'default'" class="time-btn" @click="changeTime(180)">最近六个月</a-button>
                </a-button-group>
              </div>
              <a-col :span="24">
                <a-spin :spinning="chartsLoading" style="float: left; width: 100%">
                  <area-chart v-if="coreDataChart.x.length > 0" :dataSource="coreDataChart" />
                  <a-empty v-else style="float: right; width: 100%; margin-top: 110px" />
                </a-spin>
              </a-col>
            </a-row>
            <a-row class="r5-1" :gutter="[20, 20]">
              <a-col style="width: 20%" class="border-right">
                <div class="wrap">
                  <div class="fr">
                    <p class="title">日均访问量</p>
                    <p style="font-size: 25px">{{ formatNumber(averageVisit) }}</p>
                  </div>
                </div>
              </a-col>
              <a-col style="width: 20%" class="border-right">
                <div class="wrap">
                  <div class="fr">
                    <p class="title">平均访问时长</p>
                    <p style="font-size: 25px">{{ averageVisitDuration }}</p>
                  </div>
                </div>
              </a-col>
              <a-col style="width: 20%" class="border-right">
                <div class="wrap">
                  <div class="fr">
                    <p class="title">访客平均访问页面数</p>
                    <p style="font-size: 25px">{{ formatNumber(averageVisitPage) }}</p>
                  </div>
                </div>
              </a-col>
              <a-col style="width: 20%" class="border-right">
                <div class="wrap">
                  <div class="fr">
                    <p class="title">跳出率</p>
                    <p style="font-size: 25px">{{ bounceRate }}</p>
                  </div>
                </div>
              </a-col>
              <a-col style="width: 20%">
                <div class="wrap">
                  <div class="fr">
                    <p class="title">UV到询盘转化率</p>
                    <p style="font-size: 25px">{{ conversionRate }}</p>
                  </div>
                </div>
              </a-col>
            </a-row>
          </a-row>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup name="Adweb3Home">
  import areaChart from '/@/views/adweb/data/chart/areaChart.vue';
  import { getAction } from '/@/api/manage/manage';
  import { useUserStore } from '/@/store/modules/user';
  import selectSite from '/@/components/Adweb/selectSite.vue';
  import '/@/assets/less/home.less';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { onMounted, reactive, ref, h } from 'vue';

  import { LockOutlined, CheckCircleOutlined, LoadingOutlined, ClockCircleOutlined } from '@ant-design/icons-vue';

  const { createMessage } = useMessage();

  const current = ref(0);
  let stepData = ref([{ value: '', title: '', color: '', description: '', status: 0 }]);

  const columns = [
    {
      title: '指标',
      dataIndex: 'targetName',
    },
    {
      title: '今日',
      dataIndex: 'todayCount',
    },
    {
      title: '昨日',
      dataIndex: 'yesterdayCount',
      scopedSlots: { customRender: 'yesterdayCount' },
    },
    {
      title: '本周',
      dataIndex: 'currentWeekCount',
      scopedSlots: { customRender: 'currentWeekCount' },
    },
    {
      title: '上周',
      dataIndex: 'lastWeekCount',
    },
    {
      title: '本月',
      dataIndex: 'currentMonthCount',
    },
    {
      title: '上月',
      dataIndex: 'lastMonthCount',
    },
    {
      title: '全部',
      dataIndex: 'totalCount',
    },
  ];

  const userRole = ref('');
  const timeChooseIndex = ref(7);
  //网站概况

  const siteDomain = ref('');
  const displaySiteDomain = ref('临时链接');
  const siteCode = ref('');
  const siteStatus = ref(0);
  let baseInfo = reactive<any>({});
  const baseInfoLoading = ref(false);

  //物料完成情况
  // TODO

  //核心数据
  const coreInfoLoading = ref(false);
  const coreDetailLoading = ref(false);
  const chartsLoading = ref(false);
  const achievePercent = ref(0);
  const appointWordCount = ref(0);
  const currentAchieveCount = ref(0);
  const currentMonthEnquiryCount = ref(0);
  const currentWeekEnquiryCount = ref(0);
  const totalEnquiryCount = ref(0);
  let coreDataTable = ref([]);
  const coreDataChart = ref({
    x: [],
    uv: [],
    pv: [],
    enquiry: [],
  });
  const averageVisit = ref(0);
  const averageVisitDuration = ref(0);
  const averageVisitPage = ref(0);
  const bounceRate = ref(0);
  const conversionRate = ref(0);
  const planType = ref(null);

  const isShow = ref(false);

  onMounted(() => {
    userRole.value = useUserStore().roleList;
    showStep();
  });

  //改变站点
  function changeUser(selectedParamSiteInfo: any) {
    siteCode.value = selectedParamSiteInfo.code;
    siteDomain.value = selectedParamSiteInfo.domain;

    // 如果站点是演示站，则显示 https://www.******.com
    if (selectedParamSiteInfo.isDemo == 1) {
      displaySiteDomain.value = 'https://www.******.com';
    } else {
      displaySiteDomain.value = siteDomain.value;
    }

    siteStatus.value = selectedParamSiteInfo.status;

    getAllInfo();
  }

  function filter_Null_format(value) {
    if (value === '' || value === null || value === undefined) {
      return '--';
    } else {
      return value;
    }
  }

  //保证先获取到站点列表，获取到siteCode及siteId后再进行此方法
  function getAllInfo() {
    getBaseInfo();
    getCoreData();
    getCoreDataChart();
  }

  //获取基础信息
  const getBaseInfo = () => {
    let d = {
      siteCode: siteCode.value,
    };
    baseInfoLoading.value = true;
    getAction('/adweb/adwebSiteManage/siteBasicInfo', d).then(function (res) {
      baseInfoLoading.value = false;
      if (res.code == 200) {
        baseInfo = res.result;
        current.value = baseInfo.siteStatus;
        isShow.value = true;
        planType.value = baseInfo.planType;
        if (planType.value == 'SEO') {
          getAction('/seo/seoKeywordsRank/comprehensiveInfo?siteCode=' + siteCode.value).then(function (res) {
            if (res.code == 200) {
              currentAchieveCount.value = (res.result.achievedAppointKeywordNum || 0) + (res.result.achievedLongTailKeywordNum || 0);
              appointWordCount.value = (res.result.planKeywordNum || 0) + (res.result.planLongTailKeywordNum || 0);
              achievePercent.value =
                appointWordCount.value > 0 ? ((currentAchieveCount.value / appointWordCount.value) * 100).toFixed(2) + '%' : '0%';
            }
          });
        }
      } else {
        createMessage.error('获取站点基础信息失败，请刷新重试');
      }
    });
  };

  const yesterdayData = ref({});
  const todayData = ref({});
  const thisWeekData = ref({});
  const lastWeekData = ref({});
  const thisMonthData = ref({});
  const lastMonthData = ref({});
  const allTimeData = ref({});

  //获取核心数据
  function getCoreData() {
    let d = {
      siteCode: siteCode.value,
    };
    coreInfoLoading.value = true;
    getAction('/dmp-data/site-periodic/stats', d).then(function (res) {
      coreInfoLoading.value = false;
      if (res.code == 200) {
        yesterdayData.value = res.result.yesterday;
        todayData.value = res.result.today;
        thisWeekData.value = res.result.thisWeek;
        lastWeekData.value = res.result.lastWeek;
        thisMonthData.value = res.result.thisMonth;
        lastMonthData.value = res.result.lastMonth;
        allTimeData.value = res.result.allTime;
        // achievePercent.value = res.data.achievePercent;
        // appointWordCount.value = res.data.appointWordCount;
        // currentAchieveCount.value = res.data.currentAchieveCount;
        // currentMonthEnquiryCount.value = res.data.currentMonthEnquiryCount;
        // currentWeekEnquiryCount.value = res.data.currentWeekEnquiryCount;
        // totalEnquiryCount.value = res.data.totalEnquiryCount;
        // flowIndicator = res.data.flowIndicator;
        currentWeekEnquiryCount.value = thisWeekData.value.enquires;
        currentMonthEnquiryCount.value = thisMonthData.value.enquires;
        totalEnquiryCount.value = allTimeData.value.enquires;
        coreDataTable.value = [];
        coreDataTable.value.push(
          {
            targetName: '访客数(UV)',
            todayCount: todayData.value.totalUsers,
            yesterdayCount: yesterdayData.value.totalUsers,
            currentWeekCount: thisWeekData.value.totalUsers,
            lastWeekCount: lastWeekData.value.totalUsers,
            currentMonthCount: thisMonthData.value.totalUsers,
            lastMonthCount: lastMonthData.value.totalUsers,
            totalCount: allTimeData.value.totalUsers,
          },
          {
            targetName: '访问量(PV)',
            todayCount: todayData.value.pageViews,
            yesterdayCount: yesterdayData.value.pageViews,
            currentWeekCount: thisWeekData.value.pageViews,
            lastWeekCount: lastWeekData.value.pageViews,
            currentMonthCount: thisMonthData.value.pageViews,
            lastMonthCount: lastMonthData.value.pageViews,
            totalCount: allTimeData.value.pageViews,
          },
          {
            targetName: '询盘数',
            todayCount: todayData.value.enquires,
            yesterdayCount: yesterdayData.value.enquires,
            currentWeekCount: thisWeekData.value.enquires,
            lastWeekCount: lastWeekData.value.enquires,
            currentMonthCount: thisMonthData.value.enquires,
            lastMonthCount: lastMonthData.value.enquires,
            totalCount: allTimeData.value.enquires,
          },
          {
            targetName: '询盘转化率',
            todayCount: todayData.value.enquiryConversionRate,
            yesterdayCount: yesterdayData.value.enquiryConversionRate,
            currentWeekCount: thisWeekData.value.enquiryConversionRate,
            lastWeekCount: lastWeekData.value.enquiryConversionRate,
            currentMonthCount: thisMonthData.value.enquiryConversionRate,
            lastMonthCount: lastMonthData.value.enquiryConversionRate,
            totalCount: allTimeData.value.enquiryConversionRate,
          }
        );
      } else {
        createMessage.error('获取核心数据信息失败，请刷新重试');
      }
    });
  }

  //改变图表的时间维度
  function changeTime(time) {
    console.log(time);
    timeChooseIndex.value = time;
    getCoreDataChart();
  }

  //核心数据的面积图
  const getCoreDataChart = async () => {
    let d = {
      siteCode: siteCode.value,
      dateType: timeChooseIndex.value,
    };
    chartsLoading.value = true;
    const res = await getAction('/dmp-data/site-overview/stats', d);
    if (res.code == 200) {
      let r = res.result == null ? {} : res.result;
      averageVisit.value = r.dailyTotalUsers == null ? '0' : r.dailyTotalUsers;
      averageVisitDuration.value = r.avgTimeOnPage == null ? '0' : r.avgTimeOnPage;
      averageVisitPage.value = r.pageViewsPerSession == null ? '0' : r.pageViewsPerSession;
      bounceRate.value = r.bounceRate == null ? '0' : r.bounceRate;
      conversionRate.value = r.enquiryConversionRate == null ? '0' : r.enquiryConversionRate;
      let x = [],
        pv = [],
        uv = [],
        enquiry = [];
      if (r.dailyStats != null && r.dailyStats.length > 0) {
        for (let i in r.dailyStats) {
          x.push(r.dailyStats[i].date);
          pv.push(r.dailyStats[i].pageViews);
          uv.push(r.dailyStats[i].totalUsers);
          enquiry.push(r.dailyStats[i].enquires);
        }
      }
      coreDataChart.value.x = x;
      coreDataChart.value.pv = pv;
      coreDataChart.value.uv = uv;
      coreDataChart.value.enquiry = enquiry;
    } else {
      averageVisit.value = 0;
      averageVisitDuration.value = 0;
      averageVisitPage.value = 0;
      bounceRate.value = 0;
      coreDataChart.value.x = [];
      coreDataChart.value.pv = [];
      coreDataChart.value.uv = [];
      coreDataChart.value.enquiry = [];
      createMessage.error('获取核心数据图表信息失败，请刷新重试');
    }
    chartsLoading.value = false;
  };

  // 添加格式化数字的函数
  function formatNumber(num) {
    if (num === '' || num === null || num === undefined) {
      return '--';
    }
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  }

  function showStep() {
    stepData.value = [];

    getAction('/sys/dict/getDictItems/build_website_status', null)
      .then((res) => {
        if (res.code === 0) {
          stepData.value = res.result;
        }
      })
      .catch((e) => {
        createMessage.warning('获取数据失败！' + e.message());
      });
  }
</script>

<style lang="less">
  .home {
    .ant-select {
      color: #fff;

      .ant-select-selection {
        background-color: transparent;
      }

      .ant-select-arrow {
        color: #fff;
      }
    }
  }
</style>

<style scoped lang="less">
  p,
  span {
    color: #000;
    margin: 0;
  }

  .theme-color {
    color: @primary-color;
  }

  .title {
    font-size: 18px;
    color: #000;
  }
</style>

<style lang="less">
  .pop-wrap {
    .ant-popover-inner-content {
      padding: 0;
    }

    .wrap {
      width: 400px;
      padding: 20px 20px;
      background-position: bottom right;

      p {
        line-height: 1.8;

        i {
          color: @primary-color;
          margin-right: 10px;
        }
      }

      .name {
        font-size: 18px;
        margin-bottom: 20px;
      }

      .job {
        font-size: 15px;
        color: #9f9f9f;
      }

      .ant-col-8 {
        text-align: right;
      }
    }
  }

  .faban {
    .ant-modal {
      .ant-modal-content {
        background-color: transparent;
        box-shadow: none;

        .ant-modal-close {
          top: 70px;
          right: -10px;

          .ant-modal-close-x {
            width: auto;
            height: auto;
          }
        }

        .self-close {
          i {
            color: #fff;
            border: 1px solid #fff;
            width: 25px;
            height: 25px;
            display: block;
            line-height: 25px;
          }
        }

        .ant-modal-body {
          .top-bg {
            background: url('../../../../assets/home/faban/topbg.png') no-repeat;
            min-height: 242px;
            background-size: 100% 100%;
            display: flex;
            justify-content: center;
            align-items: flex-end;
            font-size: 38px;
            padding-bottom: 60px;

            p {
              color: #fff;
            }
          }

          .info-wrap {
            background: #fff;
            padding: 0 40px;
            overflow: hidden;
            border-bottom-left-radius: 15px;
            border-bottom-right-radius: 15px;
            margin-top: -1px;

            p {
              position: relative;
              padding-left: 30px;
              margin-bottom: 5px;
              letter-spacing: 1px;

              &:before {
                content: '';
                position: absolute;
                left: 0;
                width: 15px;
                height: 15px;
                background: url('../../../../assets/home/faban/dot.svg');
                background-repeat: no-repeat;
                top: 3px;
              }
            }

            img {
              width: 70px;
              float: right;
              padding: 40px 0;
            }
          }
        }
      }
    }
  }
</style>

<style lang="less" scoped>
  .time-btn {
    &.ant-btn-default {
      color: #666;
      background: #f5f5f5;
      border-color: #d9d9d9;

      &:hover {
        color: @primary-color;
        border-color: @primary-color;
      }
    }
  }

  // 添加表格头部样式
  :deep(.ant-table-thead > tr > th) {
    background: #e6f7ff !important;
    font-weight: 700; // 字重改为700
    color: rgba(13, 62, 122, 1) !important; // 字体颜色调整
  }

  // 添加斑马线样式
  :deep(.table-striped) {
    background-color: #fafafa;
  }
</style>
