<template>
  <div class="w-full h-full pt-85px px-80px pb-80px box-border">
    <img src="@/assets/images/logo.png" alt="logo" />

    <!-- 上部分 Revenue&Attendance -->
    <Title title="Revenue&Attendance" :time="endDate" class="mt-25px mb-40px" />
    <div class="flex justify-between">
      <div class="flex items-center">
        <span class="text-42px">Revenue generated</span>
        <span class="num text-48px ml-17px"
          >{{ formatNumber(dataSource.revenueTrackingData?.revenueGenerated) }}
          AED
        </span>
      </div>
      <div class="flex items-center">
        <span class="text-42px">Onsite concierge revenue</span>
        <span class="num text-48px ml-17px"
          >{{ formatNumber(dataSource.revenueTrackingData?.onsiteConciergeRevenue) }} AED</span
        >
      </div>
    </div>
    <div class="flex items-center mt-43px mb-20px">
      <span class="text-42px">Attendance</span>
      <span class="num text-48px ml-17px">{{
        formatNumber(dataSource.revenueTrackingData?.attendanceTotal)
      }}</span>
    </div>
    <div class="w-full h-424px">
      <Bar :options="attendanceBarOption" />
    </div>
    <div class="w-full h-182px flex gap-40px mt-50px">
      <img src="@/assets/images/nomal.svg" alt="" />
      <div
        class="flex-1 bg-[url(@/assets/images/l-item-bg.svg)] bg-no-repeat flex items-center justify-between box-border px-30px overflow-hidden"
      >
        <div class="w-275px text-42px text-#A5D8FC shrink-0">AP visitors</div>
        <div>
          <div class="w-226px num text-#fff text-42px leading-50px shrink-0">
            {{ formatNumber(dataSource.visitorSegmentationData?.apVisitors?.total) }}
          </div>
          <div class="text-#A7B7CA text-36px leading-50px">Total</div>
        </div>
        <div class="flex-1 overflow-x-auto" ref="scrollContainer1">
          <div class="flex items-center gap-70px mr-70px" ref="scrollContent1">
            <div
              v-for="item in dataSource.visitorSegmentationData?.apVisitors?.lists || []"
              :key="item.parkCode"
              class="shrink-0"
            >
              <div class="num text-#36AEFF text-42px leading-50px">
                {{ formatNumber(item.current) }}
                <span
                  v-if="item.pre"
                  class="text-24px text-upcolor"
                  :class="item.pre < 0 ? 'text-downcolor' : ''"
                >
                  {{ item.pre > 0 ? '+' : '' }}{{ item.pre }}
                </span>
              </div>
              <div class="text-#A7B7CA text-36px leading-50px">
                {{ item.parkCode }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="w-full h-182px flex gap-40px mt-18px">
      <img src="@/assets/images/VIP.svg" alt="" />
      <div
        class="flex-1 bg-[url(@/assets/images/l-item-bg.svg)] bg-no-repeat flex items-center justify-between box-border px-30px overflow-hidden"
      >
        <div class="w-275px text-42px text-#A5D8FC shrink-0">AP visitors</div>
        <div class="w-226px shrink-0">
          <div class="num text-#fff text-42px leading-50px shrink-0">
            {{ dataSource.visitorSegmentationData?.vipVisitors?.total }}
          </div>
          <div class="text-#A7B7CA text-36px leading-50px">Total</div>
        </div>
        <div class="flex-1 overflow-x-auto" ref="scrollContainer2">
          <div class="flex gap-70px items-center" ref="scrollContent2">
            <div
              v-for="item in dataSource.visitorSegmentationData?.vipVisitors?.lists || []"
              :key="item.parkCode"
              class="shrink-0"
            >
              <div class="num text-#36AEFF text-42px leading-50px flex">
                {{ formatNumber(item.current) }}
                <span
                  v-if="item.pre"
                  class="text-24px text-upcolor ml-8px"
                  :class="item.pre < 0 ? 'text-downcolor' : ''"
                >
                  {{ item.pre > 0 ? '+' : '' }}{{ item.pre }}
                </span>
              </div>
              <div class="text-#A7B7CA text-36px leading-50px">
                {{ item.parkCode }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 下部分 Concierge -->
    <Title title="Concierge" :time="endDate" class="mt-50px mb-40px" />
    <div class="flex items-center">
      <span class="text-42px">Revenue generated</span>
      <span class="num text-48px ml-17px"
        >{{ dataSource.conciergeByDepartmentData?.revenueGenerated ?? 'N/A' }} AED</span
      >
    </div>

    <div class="flex items-center justify-between mt-40px">
      <div
        v-for="item in ['MD', 'MX', 'DCT', 'YAM']"
        :key="item"
        class="cus-btn"
        :class="activeType === item ? 'active' : ''"
        @click="handleConciergeClick(item)"
      >
        {{ item }}
      </div>
    </div>

    <div class="grid grid-cols-4 mt-40px gap-y-40px">
      <div v-for="item in revenueTypeList" :key="item.name">
        <div class="num text-48px text-#36AEFF leading-60px">
          {{ item.value }}
        </div>
        <div class="text-42px leading-60px mt-10px">{{ item.name }}</div>
      </div>
    </div>
    <!-- 分割线 -->
    <div class="w-full h-3px bg-#30527c my-50px"></div>

    <!-- 聊天机器人列表 -->
    <div class="flex flex-col gap-27px">
      <div
        v-for="item in chatbotList"
        :key="item.name"
        class="chatbot-item flex items-center gap-10px cursor-pointer"
        :class="{ active: activeChatbot === item.name }"
      >
        <img
          v-if="activeChatbot === item.name"
          src="@/assets/images/chatbot-active.svg"
          width="138"
          height="140"
          alt=""
        />
        <img v-else src="@/assets/images/chatbot.svg" width="138" height="140" alt="" />
        <div
          class="h-140px flex-1 bg-[url(@/assets/images/chatbot-bg.svg)] bg-no-repeat bg-contain box-border flex items-center px-30px"
          :class="{ 'ctx-active': activeChatbot === item.name }"
        >
          <div class="w-493px mr-30px text-42px">{{ item.name }}</div>
          <div
            class="flex-1 h-34px box-border border-solid border-#40657E border-1px box-border p-8px relative"
          >
            <div class="flex justify-between gap-4px">
              <div v-for="item in 8" :key="item" class="flex-1 h-18px bg-#14335B" />
            </div>
            <div
              class="flex justify-between gap-4px mt--18px relative"
              :style="{ clipPath: `inset(0 ${100 - item.percent}% 0 0)` }"
            >
              <div v-for="item in 8" :key="item" class="flex-1 h-18px bg-#2F99EE" />
            </div>
          </div>
          <div class="w-115px ml-30px num text-48px">{{ item.value }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import type { EChartsOption } from 'echarts';
import { GetConciergeByDepartment, GetRevenueTracking, GetVisitorSegmentation } from '@/api';
import { formatNumber } from '@/utils';
import { useAutoScroll } from '@/hooks/useAutoScroll';
import { useRequest } from 'vue-hooks-plus';

import Title from '@/components/Title.vue';
import Bar from '@/components/charts/Bar.vue';

import type { IRevenueTracking, IVisitorSegmentation, IConciergeByDepartment } from '@/api';
import dayjs from 'dayjs';

// 收入类型
const activeType = ref('MD');
// 机器人
const activeChatbot = ref('');
// 数据源
const dataSource = reactive<{
  revenueTrackingData?: IRevenueTracking;
  visitorSegmentationData?: IVisitorSegmentation;
  conciergeByDepartmentData?: IConciergeByDepartment;
}>({
  revenueTrackingData: undefined,
  visitorSegmentationData: undefined,
  conciergeByDepartmentData: undefined,
});
// 截止日期
const endDate = ref(dayjs().format('YYYY-MM-DD'));

// 滚动区域
const scrollContainer1 = ref<HTMLElement | null>(null);
const scrollContainer2 = ref<HTMLElement | null>(null);
const scrollContent1 = ref<HTMLElement | null>(null);
const scrollContent2 = ref<HTMLElement | null>(null);

useAutoScroll(scrollContainer1, scrollContent1, { direction: 'right' });
useAutoScroll(scrollContainer2, scrollContent2, { direction: 'right' });

// 考勤统计柱状图
const attendanceBarOption = computed((): EChartsOption => {
  const { attendance = [] } = dataSource.revenueTrackingData || {};
  return {
    title: {
      text: 'Attendance',
      left: 0,
      top: 0,
      textStyle: {
        color: '#A7B7CA',
        fontSize: '24px',
        fontFamily: 'PingFangSC-Regular, sans-serif',
        lineHeight: 34,
      },
    },
    grid: {
      left: '10px',
      right: '0%',
      bottom: '3%',
      top: '20%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: attendance.map((item) => item.parkCode),
        axisLabel: {
          color: '#fff',
          fontFamily: 'PingFangSC-Regular, sans-serif',
          fontSize: 36,
          interval: 0,
        },
        axisLine: {
          lineStyle: {
            color: '#456189',
          },
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        axisLabel: {
          color: '#9caabc',
          fontFamily: 'URWGothic-Book',
          fontSize: 36,
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: '#456189',
          },
        },
      },
    ],
    series: [
      {
        type: 'bar',
        data: attendance.map((item) => item.attendance),
        barWidth: 18,
        itemStyle: {
          color: '#42CAFF',
        },
      },
    ],
  };
});

// 收入类型列表
const revenueTypeList = computed(() => {
  const data = dataSource.conciergeByDepartmentData;
  return [
    { name: 'Call SLA', value: data?.callSla ? data.callSla + '%' : 'N/A' },
    { name: 'Call offered', value: data?.callOffered || 'N/A' },
    { name: 'Call waiting', value: data?.callWaiting || 'N/A' },
    { name: 'Call capacity', value: data?.callCapacity || 'N/A' },
    { name: 'Call occupancy', value: data?.callOccupancy || 'N/A' },
    { name: 'Call abandonment', value: data?.callAbandonment || 'N/A' },
    { name: 'Call AHT', value: data?.callAht ? data.callAht + 'mins' : 'N/A' },
    { name: 'Call CSAT', value: data?.callCast ? data.callCast + '%' : 'N/A' },
  ];
});

// 聊天机器人
const chatbotList = computed(() => {
  return [
    {
      name: 'Chatbot SLA',
      value: (dataSource.conciergeByDepartmentData?.chatbotSla || 'N/A-') + '%',
      percent: 80,
    },
    {
      name: 'Chatbot contacts offered',
      value: dataSource.conciergeByDepartmentData?.chatbotContactsOffered || 'N/A',
      percent: 90,
    },
    {
      name: 'Chatbot transfers',
      value: dataSource.conciergeByDepartmentData?.chatbotTransfers || 'N/A',
      percent: 40,
    },
  ];
});

const { data: MD } = useRequest(GetConciergeByDepartment, {
  defaultParams: ['MD'],
  pollingInterval: import.meta.env.VITE_APP_POLLING_INTERVAL,
});

const { data: MX } = useRequest(GetConciergeByDepartment, {
  defaultParams: ['MX'],
  pollingInterval: import.meta.env.VITE_APP_POLLING_INTERVAL,
});

const { data: DCT } = useRequest(GetConciergeByDepartment, {
  defaultParams: ['DCT'],
  pollingInterval: import.meta.env.VITE_APP_POLLING_INTERVAL,
});

const { data: YAM } = useRequest(GetConciergeByDepartment, {
  defaultParams: ['YAM'],
  pollingInterval: import.meta.env.VITE_APP_POLLING_INTERVAL,
});

watch(
  () => activeType.value,
  (val) => {
    // 切换类型，重新获取concierge数据
    if (val === 'MD') {
      dataSource.conciergeByDepartmentData = MD.value;
    }
    if (val === 'MX') {
      dataSource.conciergeByDepartmentData = MX.value;
    }
    if (val === 'DCT') {
      dataSource.conciergeByDepartmentData = DCT.value;
    }
    if (val === 'YAM') {
      dataSource.conciergeByDepartmentData = YAM.value;
    }
  },
);

// 获取数据
const getData = () => {
  endDate.value = dayjs().format('YY/MM/DD');
  GetRevenueTracking().then((res) => {
    dataSource.revenueTrackingData = res;
  });
  GetVisitorSegmentation().then((res) => {
    dataSource.visitorSegmentationData = res;
  });
  GetConciergeByDepartment(activeType.value).then((res) => {
    dataSource.conciergeByDepartmentData = res;
  });
};

let autoScrollTimer: NodeJS.Timeout | null = null;
// 自动切换部门
const autoScrollConcierge = () => {
  const list = ['MD', 'MX', 'DCT', 'YAM'];
  let index = list.indexOf(activeType.value);
  autoScrollTimer = setInterval(() => {
    index = (index + 1) % list.length;
    activeType.value = list[index];
  }, 1000 * 10);
};

let timer1: NodeJS.Timeout | null = null;
let timer2: NodeJS.Timeout | null = null;
// 手动点击
const handleConciergeClick = (type: string) => {
  activeType.value = type;
  clearInterval(autoScrollTimer!);
  timer1 = setTimeout(
    () => {
      autoScrollConcierge();
    },
    1000 * 60 * 3,
  );
};

onMounted(() => {
  getData();
  // 轮询数据
  timer2 = setInterval(getData, Number(import.meta.env.VITE_APP_POLLING_INTERVAL));
  autoScrollConcierge();
});

onUnmounted(() => {
  timer1 && clearTimeout(timer1);
  clearInterval(timer2!);
  clearInterval(autoScrollTimer!);
});
</script>

<style lang="less" scoped>
.cus-btn {
  width: 392px;
  height: 74px;
  background: url(@/assets/images/btn-bg.svg) no-repeat center;
  cursor: pointer;
  font-size: 42px;
  color: #99a8be;
  text-align: center;
  line-height: 74px;

  &.active {
    color: #fff;
    background: url(@/assets/images/btn-bg-active.svg) no-repeat center;
  }
}

.ctx-active {
  background: url(@/assets/images/chatbot-bg-active.svg) no-repeat center;
}
</style>
