<template>
  <Card
    :tab-list="tabListTitle"
    v-bind="$attrs"
    :active-tab-key="activeKey"
    @tabChange="onTabChange"
    v-if="!isAdmin(role)"
  >
    <template #tabBarExtraContent>
      <div class="extra-date">
        <template v-for="(item, index) in dateList" :key="item.value">
          <span
            @click="quickQueryDate(index, item.value, role === 'CUSTOMER_USER' && 'customer')"
            :class="{ active: index === activeIndex }"
            >{{ item.label }}</span
          >
        </template>
        <DatePicker
          @change="
            (_, DateString) => onDateChange(_, DateString, role === 'CUSTOMER_USER' && 'customer')
          "
          v-model:value="dateValue"
        />
      </div>
    </template>
    <!-- <div v-if="activeKey === '1'">
      <CustomerAlarmMessage
        v-if="role === 'CUSTOMER_USER'"
        type="CUSTOMER_ALARM_STATISTICAL"
        :customerList="customerAlarmList"
      />
      <VisitAnalysis v-else :alarmList="state.alarmList" />
    </div> -->
    <div v-if="activeKey === '2'">
      <!-- 柱形图 -->
      <CustomerAlarmMessage
        v-if="role === 'CUSTOMER_USER'"
        type="CUSTOMER_MESSAGE_STATISTICAL"
        :customerList="customerMessageList"
      />
      <VisitAnalysisBar
        v-else
        :dataPointList="state.dataPointList"
        :messageList="state.messageList"
      />
    </div>
  </Card>
  <div v-if="isAdmin(role)">
    <Card
      v-bind="$attrs"
      title="租户趋势"
      style="height: 26.75rem"
      :bodyStyle="{ padding: '0 24px' }"
    >
      <template #extra>
        <div class="extra-date">
          <template v-for="(item, index) in TenantOrCustomerDateList" :key="item.value">
            <span
              @click="quickQueryTenantOrCustomerTime(index, item.value, 'tenant')"
              :class="{ active: index === activeTenantIndex }"
              >{{ item.label }}</span
            >
          </template>
          <DatePicker.RangePicker
            @change="onDateTenantChange"
            size="small"
            v-model:value="tenantDateValue"
          />
        </div>
      </template>
      <TenantTrend :tenantTrendList="tenantTrendList" />
    </Card>
    <!-- <Card
      v-bind="$attrs"
      title="客户趋势"
      style="height: 26.75rem"
      :bodyStyle="{ padding: '0 24px' }"
    >
      <template #extra>
        <div class="extra-date">
          <template v-for="(item, index) in TenantOrCustomerDateList" :key="item.value">
            <span
              @click="quickQueryTenantOrCustomerTime(index, item.value)"
              :class="{ active: index === activeCustomerIndex }"
              >{{ item.label }}</span
            >
          </template>
          <DatePicker.RangePicker
            @change="onDateCustomerChange"
            size="small"
            v-model:value="customerDateValue"
          />
        </div>
      </template>
      <CustomerTrend :customerTrendList="customerTrendList" />
    </Card> -->
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { Card, DatePicker } from 'ant-design-vue';
  // import VisitAnalysis from './VisitAnalysis.vue';
  import VisitAnalysisBar from './VisitAnalysisBar.vue';
  import { isAdmin } from '/@/enums/roleEnum';
  import { useWebSocket } from '@vueuse/core';
  import { getAuthCache } from '/@/utils/auth';
  import { JWT_TOKEN_KEY } from '/@/enums/cacheEnum';
  import { formatToDateTime } from '/@/utils/dateUtil';
  // import CustomerTrend from './CustomerTrend.vue';
  import TenantTrend from './TenantTrend.vue';
  import CustomerAlarmMessage from './CustomerAlarmMessage.vue';
  import { useDate } from '../hooks/useDate';
  import { getTrendData } from '/@/api/dashboard';
  import { useGlobSetting } from '/@/hooks/setting';

  defineExpose({
    isAdmin,
  });
  const props = defineProps<{
    role: string;
  }>();
  const activeKey = ref('2');
  let entityId = null;
  // 图表tab切换选项卡 1965 1280 1861 836
  const tabListTitle = [
    // {
    //   key: '1',
    //   tab: '告警数统计',
    // },
    {
      key: '2',
      tab: '消息量统计',
    },
  ];
  // 快速选择日期
  const activeIndex = ref(3);
  const dateValue = ref();
  const dateList = ref([
    { label: '1小时', value: 3600000 },
    { label: '1天', value: 86400000 },
    { label: '7天', value: 604800000 },
    { label: '30天', value: 2592000000 },
  ]);

  // web Socket
  const token: string = getAuthCache(JWT_TOKEN_KEY);
  const { socketUrl } = useGlobSetting();
  const state = reactive({
    server: `${socketUrl}${token}`,
    alarmList: new Array<[number, string]>(),
    alarmItem: new Array<[number, string]>(),
    dataPointList: new Array<[number, string]>(),
    messageList: new Array<[number, string]>(),
    dataPoint: new Array<[number, string]>(),
    MsgCount: new Array<[number, string]>(),
  });
  const { send, close } = useWebSocket(state.server, {
    async onConnected() {
      if (isAdmin(props.role)) return;
      let content =
        JSON.parse(window.localStorage.getItem('entityId')) ||
        JSON.parse(window.sessionStorage.getItem('entityId'));
      entityId = content;
      const sendValue = JSON.stringify({
        entityDataCmds: [
          {
            query: {
              entityFilter: {
                type: 'singleEntity',
                singleEntity: entityId,
              },
              pageLink: {
                pageSize: 1024,
                page: 0,
                sortOrder: {
                  key: {
                    type: 'ENTITY_FIELD',
                    key: 'createdTime',
                  },
                  direction: 'DESC',
                },
              },
              entityFields: [
                {
                  type: 'ENTITY_FIELD',
                  key: 'name',
                },
                {
                  type: 'ENTITY_FIELD',
                  key: 'label',
                },
                {
                  type: 'ENTITY_FIELD',
                  key: 'additionalInfo',
                },
              ],
              latestValues: [
                {
                  type: 'TIME_SERIES',
                  key: 'transportMsgCountHourly',
                },
                {
                  type: 'TIME_SERIES',
                  key: 'transportDataPointsCountHourly',
                },
              ],
            },
            cmdId: activeKey.value,
          },
        ],
      });
      const sendValue1 = JSON.stringify({
        entityDataCmds: [
          {
            cmdId: activeKey.value,
            historyCmd: {
              keys: ['transportMsgCountHourly', 'transportDataPointsCountHourly'],
              startTs: Date.now() - 2592000000,
              endTs: Date.now(),
              interval: 86400000,
              agg: 'SUM',
            },
          },
        ],
      });
      send(sendValue);
      send(sendValue1);
    },
    onMessage(_, e) {
      const { data, update } = JSON.parse(e.data);
      if (activeKey.value === '1') {
        if (data) {
          const { createdAlarmsCountHourly } = data.data[0].latest.TIME_SERIES;
          state.alarmItem = [createdAlarmsCountHourly.ts, createdAlarmsCountHourly.value];
          state.alarmList.push([createdAlarmsCountHourly.ts, createdAlarmsCountHourly.value]);
        }
        if (update) {
          const { createdAlarmsCountHourly } = update[0].timeseries;
          const newArray: any = [];
          for (const item of createdAlarmsCountHourly) {
            newArray.push([item.ts, item.value]);
          }
          state.alarmList = newArray;
        }
      } else {
        if (data) {
          if (data) {
            const { transportDataPointsCountHourly, transportMsgCountHourly } =
              data.data[0].latest.TIME_SERIES;
            state.dataPoint = [
              transportDataPointsCountHourly?.ts,
              transportDataPointsCountHourly?.value,
            ];
            state.MsgCount = [
              transportDataPointsCountHourly?.ts,
              transportDataPointsCountHourly?.value,
            ];
            state.dataPointList.push([
              transportDataPointsCountHourly?.ts,
              transportDataPointsCountHourly?.value,
            ]);
            state.messageList.push([transportMsgCountHourly?.ts, transportMsgCountHourly?.value]);
          }
        }
        if (update) {
          const { transportDataPointsCountHourly, transportMsgCountHourly } = update[0].timeseries;
          const newArray: any[] = [];
          const newArray1: any[] = [];
          for (const item of transportDataPointsCountHourly) {
            newArray.push([item.ts, item.value]);
          }
          for (const item of transportMsgCountHourly) {
            newArray1.push([item.ts, item.value]);
          }
          state.dataPointList = newArray;
          state.messageList = newArray1;
        }
      }
    },
    onDisconnected() {
      console.log('断开连接了');
      close();
    },
  });

  // 切换tab页
  function onTabChange(key: string) {
    activeKey.value = key;
    activeIndex.value = 3;
    dateValue.value = '';
    const sendValue = JSON.stringify({
      entityDataCmds: [
        {
          cmdId: activeKey.value,
          historyCmd: {
            keys:
              activeKey.value === '1'
                ? ['createdAlarmsCountHourly']
                : ['transportMsgCountHourly', 'transportDataPointsCountHourly'],
            startTs: Date.now() - 2592000000,
            endTs: Date.now(),
            interval: 86400000,
            agg: 'SUM',
          },
        },
      ],
    });
    if (key === '2') {
      const sendMessageValue = JSON.stringify({
        entityDataCmds: [
          {
            query: {
              entityFilter: {
                type: 'singleEntity',
                singleEntity: entityId,
              },
              pageLink: {
                pageSize: 1024,
                page: 0,
                sortOrder: {
                  key: {
                    type: 'ENTITY_FIELD',
                    key: 'createdTime',
                  },
                  direction: 'DESC',
                },
              },
              entityFields: [
                {
                  type: 'ENTITY_FIELD',
                  key: 'name',
                },
                {
                  type: 'ENTITY_FIELD',
                  key: 'label',
                },
                {
                  type: 'ENTITY_FIELD',
                  key: 'additionalInfo',
                },
              ],
              latestValues: [
                {
                  type: 'TIME_SERIES',
                  key: 'transportMsgCountHourly',
                },
                {
                  type: 'TIME_SERIES',
                  key: 'transportDataPointsCountHourly',
                },
              ],
            },
            cmdId: activeKey.value,
          },
        ],
      });
      send(sendMessageValue);
    }
    send(sendValue);
  }
  // 选择日期
  async function onDateChange(_, dateString, roleType = '') {
    console.log(_, dateString, roleType);
    activeIndex.value = -1;
    const dateTime = Number(formatToDateTime(dateString, 'x'));
    if (!dateString) return;
    if (roleType === 'customer') {
      if (activeKey.value === '1') {
        const data = await getTrendData({
          startTs: dateTime,
          endTs: dateTime + 86400000,
          interval: 7200000,
          trend: 'CUSTOMER_ALARM_STATISTICAL',
        });
        customerAlarmList.value = data;
      } else if (activeKey.value === '2') {
        const data = await getTrendData({
          startTs: dateTime,
          endTs: dateTime + 86400000,
          interval: 7200000,
          trend: 'CUSTOMER_MESSAGE_STATISTICAL',
        });
        customerMessageList.value = data;
      }
    } else {
      // 动态发送ws数据
      const sendValue = JSON.stringify({
        entityDataCmds: [
          {
            cmdId: activeKey.value,
            historyCmd: {
              keys:
                activeKey.value === '1'
                  ? ['createdAlarmsCountHourly']
                  : ['transportMsgCountHourly', 'transportDataPointsCountHourly'],
              startTs: dateTime,
              endTs: dateTime + 86400000,
              interval: 7200000,
              limit: 12,
              agg: 'SUM',
            },
          },
        ],
      });
      send(sendValue);
    }
  }
  const customerAlarmList = ref([]);
  const customerMessageList = ref([]);
  // 快速选择时间
  async function quickQueryDate(index: number, value: number, roleType = '') {
    if (activeIndex.value === index) return;
    activeIndex.value = index;
    dateValue.value = '';
    let interval = 300000;
    if (value === 86400000) {
      interval = 7200000;
    } else if (value === 604800000 || value === 2592000000) {
      interval = 86400000;
    }
    if (roleType === 'customer') {
      if (activeKey.value === '1') {
        const data = await getTrendData({
          startTs: Date.now() - value,
          endTs: Date.now(),
          interval,
          trend: 'CUSTOMER_ALARM_STATISTICAL',
        });
        customerAlarmList.value = data;
      } else if (activeKey.value === '2') {
        const data = await getTrendData({
          startTs: Date.now() - value,
          endTs: Date.now(),
          interval,
          trend: 'CUSTOMER_MESSAGE_STATISTICAL',
        });
        customerMessageList.value = data;
      }
    } else {
      // 动态发送ws数据
      const sendValue = JSON.stringify({
        entityDataCmds: [
          {
            cmdId: activeKey.value,
            historyCmd: {
              keys:
                activeKey.value === '1'
                  ? ['createdAlarmsCountHourly']
                  : ['transportMsgCountHourly', 'transportDataPointsCountHourly'],
              startTs: Date.now() - value,
              endTs: Date.now(),
              interval,
              agg: 'SUM',
            },
          },
        ],
      });
      send(sendValue);
    }
  }
  const {
    tenantDateValue,
    // customerDateValue,
    tenantTrendList,
    // customerTrendList,
    activeTenantIndex,
    // activeCustomerIndex,
    TenantOrCustomerDateList,
    quickQueryTenantOrCustomerTime,
    onDateTenantChange,
    // onDateCustomerChange,
  } = useDate();
</script>

<style lang="less">
  .center {
    display: flex;
    justify-content: center;
    font-size: 16px;
  }

  .active {
    color: #0960bd;
    font-weight: 500;
  }

  .extra-date {
    display: flex;
    align-items: center;
    justify-content: space-between;

    span {
      margin-right: 20px;
      cursor: pointer;
    }
  }
</style>
