<script lang="ts" setup>
import { AnalysisChartCard, AnalysisOverview } from '@vben/common-ui';
import {
  SvgBellIcon,
  SvgCakeIcon,
  SvgCardIcon,
  SvgDownloadIcon,
} from '@vben/icons';

import AnalyticsTrends from './analytics-trends.vue';
import AnalyticsVisitsData from './analytics-visits-data.vue';
import AnalyticsVisitsSales from './analytics-visits-sales.vue';
import AnalyticsVisitsSource from './analytics-visits-source.vue';
import { ref, onMounted } from 'vue';
import { DatePicker, message } from 'ant-design-vue';
import { Radio } from 'ant-design-vue';
import {
  getIndexCount,
  getStatisticsCurrDay,
  getStatistics,
} from '#/api/analytics/index';
import { getVisitorList } from '#/api/property/resident/passRecordManagement';
const overviewItems = ref<any[]>([
  {
    icon: SvgCardIcon,
    title: '今日通行量',
    totalTitle: '总通行量',
    totalValue: 0,
    value: 0,
  },
  {
    icon: SvgCakeIcon,
    title: '今日车流量',
    totalTitle: '总车流量',
    totalValue: 0,
    value: 0,
  },
  {
    icon: SvgDownloadIcon,
    title: '今日预警数量',
    totalTitle: '总预警量',
    totalValue: 0,
    value: 0,
  },
  {
    icon: SvgBellIcon,
    title: '今日工单数量',
    totalTitle: '总工单量',
    totalValue: 0,
    value: 0,
  },
]);

//tab选择
const meterType = ref<Number>(1);
// 月份选择
const selectedDate = ref<any>(null);
const paramDate = ref(null);

const statisticsList = ref<any>();
const workList = ref<any>();
const statusDataList = ref<any>();
const analyticsTrendsRef = ref<InstanceType<typeof AnalyticsTrends> | null>(
  null,
);
const handleDateChange = (date: any) => {
  paramDate.value = date.format('YYYY-MM');
  console.log('meterType', meterType);
  // 调用子组件的方法
  if (
    analyticsTrendsRef.value &&
    analyticsTrendsRef.value.getMeterRecordTrend
  ) {
    analyticsTrendsRef.value.getMeterRecordTrend(paramDate, meterType);
  }
};

const handleMeterTypeChange = (e: Event) => {
  if (!selectedDate.value) {
    message.warning('请选择月份');
    return;
  }
  paramDate.value = selectedDate.value.format('YYYY-MM');
  // 调用子组件的方法
  if (
    analyticsTrendsRef.value &&
    analyticsTrendsRef.value.getMeterRecordTrend
  ) {
    analyticsTrendsRef.value.getMeterRecordTrend(paramDate, meterType);
  }
};

// 通行量
async function getPersonCount() {
  const date = new Date();
  const nowDate = date
    .toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    })
    .replace(/\//g, '-');

  const historyData = {
    pageNum: 1,
    pageSize: 10,
    begTime: '2025-09-01',
    endTime: nowDate,
  };

  const todayData = {
    pageNum: 1,
    pageSize: 10,
    begTime: nowDate,
    endTime: nowDate,
  };

  const historyTotal = await getVisitorList(historyData);
  const todayTotal = await getVisitorList(todayData);
  overviewItems.value[0].totalValue = historyTotal.total;
  overviewItems.value[0].value = todayTotal.total;
}

// 工单数量
async function getIndex() {
  const res = await getIndexCount();
  overviewItems.value[3].value = res.workOrdersToday;
  overviewItems.value[3].totalValue = res.workOrdersTotal;
  overviewItems.value[0].value = res.visitorsToday;
  overviewItems.value[0].totalValue = res.visitorsTotal;
  workList.value = res.satisfactionChartList;
  statusDataList.value = res.statusChartVoChartList;
}
// 车流量
async function getCarCount() {
  const startDate = new Date();
  startDate.setHours(0, 0, 0, 0);
  const endDate = new Date();
  endDate.setHours(23, 59, 59, 999);
  // 转换为正确的 ISO 格式，考虑时区偏移
  const toLocalISOString = (date: Date) => {
    const localTime = new Date(date.getTime());
    return localTime.toISOString().slice(0, -1) + 'Z';
  };
  const response = await fetch(
    'https://server.cqnctc.com:6081/web/thirdParty/queryInParkData',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json, text/plain, */*',
      },
      body: JSON.stringify({
        pageReq: {
          pageNum: 1,
          pageSize: 10,
        },
        plNos: ['PFN000000012', 'PFN000000022', 'PFN000000025'],
        parkInBeginTime: toLocalISOString(startDate),
        parkInEndTime: toLocalISOString(endDate),
        orgId: 10012,
        parkOrderTypes: [100, 200, 201, 300, 500],
        terminalSource: 50,
        remark: '',
      }),
    },
  );
  const result = await response.json();
  overviewItems.value[1].value = result.data.todayCount;

  overviewItems.value[1].totalValue = result.data.allCount;
}
// 预警
async function getStatisticsCurrDayCount() {
  const res = await getStatisticsCurrDay();
  let total = 0;
  for (const item of res) {
    total += item.total;
  }
  overviewItems.value[2].value = total;
}
async function getStatisticsCount() {
  const res = await getStatistics();
  let total = 0;
  for (const item of res) {
    total += item.total;
  }
  overviewItems.value[2].totalValue = total;
  statisticsList.value = res;
}
// 电量

onMounted(() => {
  getIndex();
  getCarCount();
  getPersonCount();
  getStatisticsCurrDayCount();
  getStatisticsCount();
});
</script>

<template>
  <div class="p-5">
    <AnalysisOverview :items="overviewItems" />
    <!-- <AnalysisChartsTabs :tabs="chartTabs" class="mt-5">
      <template #trends>
        <AnalyticsTrends />
      </template>
      <template #visits>
        <AnalyticsVisits />
      </template>
    </AnalysisChartsTabs> -->
    <div class="mt-5 rounded-lg bg-white">
      <div
        class="flex items-center justify-between p-5"
        style="width: 100%; height: 100px"
      >
        <Radio.Group
          size="large"
          v-model:value="meterType"
          @change="handleMeterTypeChange"
        >
          <Radio.Button value="1">电量</Radio.Button>
          <Radio.Button value="2">水量</Radio.Button>
        </Radio.Group>
        <DatePicker
          v-model:value="selectedDate"
          picker="month"
          placeholder="请选择月份"
          style="width: 150px"
          @change="handleDateChange"
        />
      </div>
      <div>
        <AnalyticsTrends
          :meterType="meterType"
          ref="analyticsTrendsRef"
          :selected-date="selectedDate"
        />
      </div>
    </div>

    <div class="mt-5 w-full md:flex">
      <AnalysisChartCard class="mt-5 md:mr-4 md:mt-0 md:w-1/3" title="预警类型">
        <AnalyticsVisitsData :statisticsData="statisticsList" />
      </AnalysisChartCard>
      <AnalysisChartCard
        class="mt-5 md:mr-4 md:mt-0 md:w-1/3"
        title="设备使用状态"
      >
        <AnalyticsVisitsSource :statusData="statusDataList" />
      </AnalysisChartCard>
      <AnalysisChartCard class="mt-5 md:mt-0 md:w-1/3" title="工单类型">
        <AnalyticsVisitsSales :workData="workList" />
      </AnalysisChartCard>
    </div>
  </div>
</template>
