<template>
  <div class="absolute w-1070px h-2338px top-432px right-80px flex flex-col gap-y-20px" style="transform: translateX(110%)">
    <!-- Queue Time -->
    <div class="park-rpanel-item h-571px">
      <div class="park-item-title">Queue Time</div>
      <div class="text-32px text-#A7B7CA leading-45px mb-28px">
        Average waiting time
        <span class="text-42px text-#fff leading-51px"
          >{{ dataSource.queueTime?.avg ?? 'N/A' }}min</span
        >
      </div>
      <div class="flex flex-col gap-y-29px">
        <div v-for="item in queueTimeList" :key="item.name" class="flex items-center gap-x-10px">
          <div class="w-300px truncate text-32px text-#A7B7CA leading-45px">
            {{ item.name }}
          </div>
          <div class="flex-1 h-12px rounded-10px bg-#B3B3B333">
            <div
              class="bar h-12px rounded-10px transition duration-300"
              :style="{ width: item.percentage + '%' }"
            ></div>
          </div>
          <div class="w-110px text-36px leading-44px">{{ item.value }}min</div>
        </div>
      </div>
    </div>

    <!-- Happiness Meters -->
    <div class="park-rpanel-item h-609px flex flex-col">
      <div class="park-item-title">Happiness Meters</div>
      <div class="flex items-center gap-10px">
        <img width="40" height="40" src="@/assets/images/emoji4.png" alt="happiness" />
        <span class="text-32px text-#A7B7CA leading-45px">Happiness index</span>
        <span class="num text-48px leading-59px text-downcolor">{{
          dataSource.happinessMeters.value ?? 'N/A'
        }}</span>
        <span v-if="dataSource.happinessMeters.preValue">
          <img
            v-if="dataSource.happinessMeters.preValue > 0"
            src="@/assets/images/up-arrow.svg"
            alt="up"
          />
          <img v-else src="@/assets/images/down-arrow.svg" alt="down" />
        </span>
        <span
          class="num text-36px"
          :class="dataSource.happinessMeters.preValue > 0 ? 'text-upcolor' : 'text-downcolor'"
          >{{ dataSource.happinessMeters.preValue }}</span
        >
      </div>
      <div class="mt-16px mb-14px text-36px leading-50px">Happiness index</div>
      <div class="flex-1">
        <Bar :options="happinessMetersBar" />
      </div>
    </div>

    <!-- Sentiment -->
    <div class="park-rpanel-item h-372px">
      <div class="park-item-title">Sentiment</div>
      <div class="flex items-center gap-64px mt-14px mb-12px">
        <div class="text-32px text-#A7B7CA leading-45px">
          Positive
          <span class="text-42px text-#fff leading-51px">{{
            dataSource.sentiment?.positiveCount ?? 'N/A'
          }}</span>
        </div>
        <div class="text-32px text-#A7B7CA leading-45px">
          Negative
          <span class="text-42px text-#fff leading-51px">{{
            dataSource.sentiment?.negativeCount ?? 'N/A'
          }}</span>
        </div>
      </div>
      <div class="flex gap-60px">
        <div class="flex items-center">
          <img src="@/assets/images/emoji4.png" alt=""/>
          <span class="num text-36px text-#E4E4E4 leading-44px mr-22px"
            >{{ dataSource.sentiment?.positiveRate ?? 'N/A' }}%</span
          >
          <span v-if="dataSource.sentiment?.positiveTrend" class="flex items-center">
            <img
              v-if="dataSource.sentiment?.positiveTrend > 0"
              src="@/assets/images/up-arrow.svg"
              alt="up"
            />
            <img v-else src="@/assets/images/down-arrow.svg" alt="up" />
            <span
              class="num text-24px leading-30px"
              :class="dataSource.sentiment?.positiveTrend > 0 ? 'text-upcolor' : 'text-downcolor'"
              >{{ dataSource.sentiment?.positiveTrend }}%</span
            >
          </span>
        </div>
        <div class="flex items-center">
          <img src="@/assets/images/emoji2.png" alt=""/>
          <span class="num text-36px text-#E4E4E4 leading-44px mr-22px"
            >{{ dataSource.sentiment?.neutralRate ?? 'N/A' }}%</span
          >
          <span v-if="dataSource.sentiment?.neutralRate" class="flex items-center">
            <img
              v-if="dataSource.sentiment?.neutralRate > 0"
              src="@/assets/images/up-arrow.svg"
              alt="up"
            />
            <img v-else src="@/assets/images/down-arrow.svg" alt="up" />
            <span
              class="num text-24px leading-30px"
              :class="dataSource.sentiment?.neutralRate > 0 ? 'text-upcolor' : 'text-downcolor'"
              >{{ dataSource.sentiment?.neutralRate }}%</span
            >
          </span>
        </div>
        <div class="flex items-center">
          <img src="@/assets/images/emoji5.png" alt=""/>
          <span class="num text-36px text-#E4E4E4 leading-44px mr-22px"
            >{{ dataSource.sentiment?.negativeRate }}%</span
          >
          <span v-if="dataSource.sentiment?.negativeTrend" class="flex items-center">
            <img
              v-if="dataSource.sentiment?.negativeTrend > 0"
              src="@/assets/images/up-arrow.svg"
              alt="up"
            />
            <img v-else src="@/assets/images/down-arrow.svg" alt="up" />
            <span
              class="num text-24px leading-30px"
              :class="dataSource.sentiment?.negativeTrend > 0 ? 'text-upcolor' : 'text-downcolor'"
              >{{ dataSource.sentiment?.negativeTrend }}%</span
            >
          </span>
        </div>
      </div>
      <div
        class="w-full h-122px mt-20px border border-solid border-#285377 rounded-10px truncate text-32px text-#C5EDF99F flex items-center box-border px-22px gap-30px"
      >
        <span v-for="item in dataSource.sentiment?.tags?.split(',') || []" :key="item">{{
          item
        }}</span>
      </div>
    </div>

    <!-- Revenue -->
    <div class="park-rpanel-item h-726px flex flex-col">
      <div class="park-item-title mb-14px">Revenue</div>
      <div class="flex gap-90px mb-40px">
        <div class="flex-1">
          <div class="text-36px text-#A7B7CA leading-50px mb-10px">Retail revenue</div>
          <div class="flex items-center">
            <span class="num text-48px leading-60px mr-23px"
              >{{ dataSource.reveneData?.retailRevenue ?? 'N/A'
              }}<span class="text-32px">AED</span></span
            >
            <span v-if="dataSource.reveneData?.retailRevenueRate" class="flex items-center">
              <img
                v-if="dataSource.reveneData?.retailRevenueRate > 0"
                src="@/assets/images/up-arrow.svg"
                alt="up"
              />
              <img v-else src="@/assets/images/down-arrow.svg" alt="down" />
              <span
                class="num text-32px"
                :class="
                  dataSource.reveneData?.retailRevenueRate > 0 ? 'text-upcolor' : 'text-downcolor'
                "
                >{{ dataSource.reveneData?.retailRevenueRate }}</span
              >
            </span>
          </div>
          <!-- <div class="w-full h-12px bg-#1669B424 rounded-30px mt-16px">
            <div class="h-12px rounded-30px bg-#4CA3FF" :style="{ width: retailRevenueBarWidth }" />
          </div> -->
        </div>
        <div class="flex-1">
          <div class="text-36px text-#A7B7CA leading-50px mb-10px">Ticket revenue</div>
          <div class="flex items-center">
            <span class="num text-48px leading-60px mr-23px"
              >{{ dataSource.reveneData?.ticketRevenue ?? 'N/A'
              }}<span class="text-32px">AED</span></span
            >
            <span v-if="dataSource.reveneData?.ticketRevenueRate" class="flex items-center">
              <img
                v-if="dataSource.reveneData?.ticketRevenueRate > 0"
                src="@/assets/images/up-arrow.svg"
                alt="up"
              />
              <img v-else src="@/assets/images/down-arrow.svg" alt="down" />
              <span
                class="num text-32px"
                :class="
                  dataSource.reveneData?.ticketRevenueRate > 0 ? 'text-upcolor' : 'text-downcolor'
                "
                >{{ dataSource.reveneData?.ticketRevenueRate }}</span
              >
            </span>
          </div>
          <!-- <div class="w-full h-12px bg-#1669B424 rounded-30px mt-16px">
            <div class="h-12px rounded-30px bg-#4CA3FF" :style="{ width: ticketRevenueBarWidth }" />
          </div> -->
        </div>
      </div>
      <div class="flex-1">
        <Bar :options="revenueTrendAnalysisBar" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, inject, reactive, watch } from 'vue';
import { Receiver } from '@/utils/sseReceiver';
import { getIDBData, addIDBData } from '@/utils/database';

import Bar from '@/components/charts/Bar.vue';
import type { EChartsOption } from 'echarts';
import type { Ref } from 'vue';

import icon0 from '@/assets/images/emoji0.png';
import icon1 from '@/assets/images/emoji1.png';
import icon2 from '@/assets/images/emoji2.png';
import icon3 from '@/assets/images/emoji3.png';
import icon4 from '@/assets/images/emoji4.png';
import dayjs from 'dayjs';

interface IQueueTime {
  date: string;
  parkCode: string;
  project: string;
  queueTime: number;
}

interface IHappinessMeters {
  date: string;
  happinessMeters: number;
  parkCode: string;
  project: string;
  sentiment: string;
}

interface ISentiment {
  analysisDate: string;
  id: number;
  negativeCount: number;
  negativeRate: number;
  negativeTrend: number;
  neutralCount: number;
  neutralRate: number;
  neutralTrend: number;
  parkCode: string;
  positiveCount: number;
  positiveRate: number;
  positiveTrend: number;
  syncTraceId: string;
  synchTime: string;
  tags: string;
}

const parkCode = inject<Ref<string, string>>('parkCode');
const dataSource = reactive<{
  reveneData?: {
    retailRevenue: number;
    retailRevenueRate: number;
    ticketRevenue: number;
    ticketRevenueRate: number;
    lists: {
      id: number;
      parkCode: string;
      reportDate: string;
      retailRevenue: number;
      syncTraceId: number;
      synchTime: string;
      ticketRevenue: number;
    }[];
  };
  queueTime: { avg: number; list: IQueueTime[] };
  happinessMeters: {
    list: IHappinessMeters[];
    preValue: number;
    value: number;
  };
  sentiment?: ISentiment;
}>({
  reveneData: undefined,
  queueTime: {
    avg: 0,
    list: [],
  },
  happinessMeters: {
    list: [],
    preValue: 0,
    value: 0,
  },
  sentiment: undefined,
});

// 获取数据
const setData = () => {
  if (parkCode?.value) {
    getIDBData('Revenue,' + parkCode.value).then((res) => {
      dataSource.reveneData = res?.value;
    });

    getIDBData('Park_Queue_Time' + parkCode.value).then((res) => {
      dataSource.queueTime.list = res?.value;
    });
    getIDBData('Park_Queue_Time' + parkCode.value + '_avg').then((res) => {
      dataSource.queueTime.avg = res?.value;
    });

    getIDBData('Park_Happiness_Meters' + parkCode.value).then((res) => {
      dataSource.happinessMeters.list = res?.value;
    });
    getIDBData('Park_Happiness_Meters' + parkCode.value + '_value').then((res) => {
      dataSource.happinessMeters.value = res?.value;
    });
    getIDBData('Park_Happiness_Meters' + parkCode.value + '_preValue').then((res) => {
      dataSource.happinessMeters.preValue = res?.value;
    });

    getIDBData('Sentiment' + parkCode.value).then((res) => {
      dataSource.sentiment = res?.value;
    });
  }
};

watch(
  () => parkCode?.value,
  () => {
    setData();
  },
);

setData();
// 获取websoket
const ws = Receiver.getInstance(import.meta.env.VITE_APP_SOCKET_SERVER + '/kpi/ws/data');
ws.onMessage(async (message) => {
  if (message.module.includes('Park_Queue_Time')) {
    addIDBData(message.module + '_avg', message.value);
  }
  if (message.module.includes('Park_Happiness_Meters')) {
    addIDBData(message.module + '_value', message.value);
    addIDBData(message.module + '_preValue', message.preValue);
  }
  setData();
});

// 进度条宽度
// const retailRevenueBarWidth = computed(() => {
//   if (dataSource.reveneData) {
//     return (
//       (
//         (dataSource.reveneData.retailRevenue /
//           (dataSource.reveneData.retailRevenue + dataSource.reveneData.ticketRevenue)) *
//         100
//       ).toFixed(2) + '%'
//     );
//   }
//   return 0;
// });
// const ticketRevenueBarWidth = computed(() => {
//   if (dataSource.reveneData) {
//     return (
//       (
//         (dataSource.reveneData.ticketRevenue /
//           (dataSource.reveneData.ticketRevenue + dataSource.reveneData.ticketRevenue)) *
//         100
//       ).toFixed(2) + '%'
//     );
//   }
//   return 0;
// });

// 排队时间列表
const queueTimeList = computed(() => {
  const list = (dataSource.queueTime.list || []).sort((a, b) => b.queueTime - a.queueTime).slice(0, 5);
  // 取最大值或1h为100%基准
  const maxTime = Math.max(...list.map((item) => item.queueTime), 60);
  return list.map((item) => ({
    name: item.project,
    value: item.queueTime,
    percentage: (item.queueTime / maxTime) * 100,
  }));
});

// 幸福指数柱状图
const happinessMetersBar = computed((): EChartsOption => {
  const list = dataSource.happinessMeters.list || [];
  return {
    grid: {
      left: '5%',
      right: 100,
      bottom: '0%',
      top: '0%',
    },
    yAxis: {
      type: 'category',
      data: list.map((item) => item.project),
      axisLabel: {
        color: '#A7B7CA',
        fontFamily: 'PingFangSC-Regular, sans-serif',
        fontSize: '32px',
      },
      axisLine: {
        show: false,
      },
      splitLine: {
        show: false,
      },
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        show: false,
      },
      minInterval: 1,
      min: 0,
      max: 5,
      splitLine: {
        show: false,
      },
    },
    series: [
      {
        data: list.map((item) => {
          return {
            value: item.happinessMeters,
            itemStyle: {
              // 渐变色
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops:
                  // 分值5~4 绿色渐变 <4 蓝色渐变
                  item.happinessMeters >= 4
                    ? [
                        {
                          offset: 0,
                          color: '#3DB346',
                        },
                        {
                          offset: 1,
                          color: '#A7EDA4',
                        },
                      ]
                    : [
                        {
                          offset: 0,
                          color: '#3ABAFF',
                        },
                        {
                          offset: 1,
                          color: '#78DDFF',
                        },
                      ],
              },
            },
          };
        }),
        type: 'bar',
        barWidth: 18,
        label: {
          show: true,
          position: 'right',
          color: '#fff',
          fontFamily: 'PingFangSC-Medium, sans-serif',
          fontSize: 36,
          formatter: (params) => {
            const value = Number(params?.value || 0);
            if (value >= 0 && value <= 0.9) {
              return `${params.value} {a|}`;
            }
            if (value > 0.9 && value <= 1.9) {
              return `${params.value} {b|}`;
            }
            if (value > 0.9 && value <= 2.9) {
              return `${params.value} {c|}`;
            }

            if (value > 2.9 && value < 3.9) {
              return `${params.value} {d|}`;
            }

            return `${params.value} {e|}`;
          },
          rich: {
            a: {
              backgroundColor: {
                image: icon0,
              },
            },
            b: {
              backgroundColor: {
                image: icon1,
              },
            },
            c: {
              backgroundColor: {
                image: icon2,
              },
            },
            d: {
              backgroundColor: {
                image: icon3,
              },
            },
            e: {
              backgroundColor: {
                image: icon4,
              },
            },
          },
        },
      },
    ],
  };
});

// 收入趋势分析
const revenueTrendAnalysisBar = computed((): EChartsOption => {
  const list = dataSource.reveneData?.lists || [];
  return {
    title: {
      text: 'Revenue trend analysis',
      left: 0,
      top: 0,
      textStyle: {
        color: '#fff',
        fontSize: '36px',
        fontFamily: 'PingFangSC-Medium, sans-serif',
        lineHeight: 50,
      },
    },
    legend: {
      right: 0,
      top: 0,
      textStyle: {
        color: '#9BAEC1',
        fontSize: 24,
        fontFamily: 'PingFangSC-Regular, sans-serif',
      },
    },
    grid: {
      left: '18px',
      right: '0%',
      bottom: '3%',
      top: '20%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: [...new Set(list.map((item) => dayjs(item.reportDate).format('MM.DD')))],
        axisLabel: {
          color: '#fff',
          fontFamily: 'PingFangSC-Regular, sans-serif',
          fontSize: 24,
        },
        axisLine: {
          lineStyle: {
            color: '#456189',
          },
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        axisLabel: {
          color: '#9caabc',
          fontFamily: 'PingFangSC-Regular, sans-serif',
          fontSize: 24,
        },
        minInterval: 1,
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: '#304c76',
          },
        },
      },
    ],
    series: [
      {
        name: 'Retail',
        type: 'bar',
        stack: 'total',
        data: list.map((item) => item.retailRevenue),
        barWidth: 18,
        itemStyle: {
          color: '#2E90FF',
        },
      },
      {
        name: 'Ticket',
        type: 'bar',
        stack: 'total',
        data: list.map((item) => item.ticketRevenue),
        barWidth: 18,
        itemStyle: {
          color: '#1AFF90',
        },
      },
    ],
  };
});
</script>

<style lang="less" scoped>
.bar {
  background: linear-gradient(90deg, #51ffff 0%, #3abaff 77%, #ffffff 100%);
}
</style>
