<template>
  <div class="mian">
    <div class="title">
      <div class="left">
        <div class="left-first" id="time">--:--:--</div>
        <div class="left-second" id="date">----</div>
      </div>
      <div class="center">南川区综合服务中心数智管理平台物业驾驶舱</div>
      <div class="right">
        <div>{{ weekDay }}</div>
        <div>晴</div>
        <div>40℃</div>
        <div class="logout" @click="logout">
          <img
            src="../../../assets/return.png"
            style="width: 1.5rem; height: 1.5rem"
          />
          <div>退出</div>
        </div>
      </div>
    </div>
    <div class="header">
      <div class="header-item">
        <span class="header-label">今年用电量</span>
        <span class="header-value orange">{{powerYear}}</span>
        <span class="header-unit">KW·h</span>
      </div>
      <div class="header-item">
        <span class="header-label">本月用电总量</span>
        <span class="header-value green">{{powerMonth}}</span>
        <span class="header-unit">KW·h</span>
      </div>
      <div class="header-item">
        <span class="header-label">今年用水总量</span>
        <span class="header-value blue">2600</span>
        <span class="header-unit">万吨</span>
      </div>
      <div class="header-item">
        <span class="header-label">本月用水总量</span>
        <span class="header-value purple">30</span>
        <span class="header-unit">万吨</span>
      </div>
      <div class="header-item">
        <span class="header-label">设备总数</span>
        <span class="header-value green">{{total}}</span>
        <span class="header-unit">台</span>
      </div>
    </div>
    <div class="contents">
      <div class="content">
        <div class="content-left">
          <div class="first">
            <div
              ref="barChart"
              class="bar-chart"
              style="width: 100%; height:242px;"
              @click="goWorkOrder"
            ></div>
          </div>
          <div class="second">
            <div ref="powerChart" class="power-chart" @click="goVisitor"></div>
          </div>
          <div class="third">
            <div ref="envChart" class="env-chart" @click="goCar"></div>
          </div>
        </div>
        <div class="content-center">
          <div class="content-center-first">
            <div class="first-item">
              <div class="item"></div>
            </div>
          </div>
          <div class="content-center-second">
            <div style="position: relative;left: 2%;padding-top: 10%">
              <div class="offline">离线</div>
              <div class="online">在线</div>
            </div>
            <div>
              <EchartsUI
                ref="water"
                height="100%"
                width="150px"
              />
            </div>
            <div>
              <EchartsUI
                ref="electricity"
                height="100%"
                width="150px"
              />
            </div>
            <div>
              <EchartsUI
                ref="accessControl"
                height="100%"
                width="150px"
              />
            </div>
            <div>
              <EchartsUI
                ref="camera"
                height="100%"
                width="150px"
              />
            </div>
          </div>
        </div>
        <div class="content-right">
          <div class="first">
            <div class="mt-8" style="position: relative">
              <div
                class="flex items-center justify-between p-5"
              >
                <Radio.Group v-model:value="timeUnit" size="small">
                  <Radio.Button value="1" style="background-color: transparent;color: #fff">电量</Radio.Button>
                </Radio.Group>
                <DatePicker
                  v-model:value="selectedDate"
                  picker="month"
                  placeholder="请选择月份"
                  style="width: 130px;height: 25px;background-color: transparent;"
                  @change="handleDateChange"
                  class="white-text-datepicker"
                />
              </div>
              <div v-if="timeUnit == 1">
                <AnalyticsTrends
                  ref="analyticsTrendsRef"
                  :selected-date="selectedDate"
                  @getPowerDate="fetchPowerDate"
                  @click="goPower"
                />
              </div>
            </div>
          </div>
          <div class="second" @click="goWarningProcessing">
            <div class="second-box">
              <div class="box-content" v-for="(item,index) in warning" :key="index">
                <div class="box-content-label">{{ item.typeName }}</div>
                <div class="box-content-num">{{item.total}}</div>
              </div>
            </div>
          </div>
          <div class="third" @click="goReservationRecords">
            <div class="third-item">
              <div class="third-title">会议室总数</div>
              <div class="third-num">{{todayMeetCount?.meetCount}}</div>
            </div>
            <div class="third-item">
              <div class="third-title">当日预约会议室总数</div>
              <div class="third-num">{{todayMeetCount?.timeQuantity}}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {getStatistics,getworkOrder,getTodayMeetCount,getHydropower,getAccessControl,getCamera,queryTwentyfourRunningDatasByPlNos,getVisitorCount} from '#/api/analytics';
import AnalyticsTrends from './analytics-trends.vue';
import { computed } from 'vue';
import { Radio } from 'ant-design-vue';
import {EchartsUI, useEcharts} from "@vben/plugins/echarts";

//预警类型
const warning = ref([])
async function getWarning() {
  warning.value = await getStatistics();
}
//tab选择
const timeUnit = ref(1);
// 月份选择
const selectedDate = ref<any>(null);
const paramDate = ref(null);

const analyticsTrendsRef = ref<InstanceType<typeof AnalyticsTrends> | null>(
  null,
);
const handleDateChange = (date: any) => {
  paramDate.value = date.format('YYYY-MM');
  // 调用子组件的方法
  if (
    analyticsTrendsRef.value &&
    analyticsTrendsRef.value.getMeterRecordTrend
  ) {
    analyticsTrendsRef.value.getMeterRecordTrend(paramDate);
  }
};
//会议室
const todayMeetCount = ref();
const handleTodayMeetCount = async () => {
  todayMeetCount.value = await getTodayMeetCount();
};
// 水
const water = ref();
const waterTotal = ref();
const { renderEcharts: renderWater } = useEcharts(water);
async function fetchWater() {
  const data = await getHydropower()
  waterTotal.value = data.water.off + data.water.on;
  const waterData = [
    { name: '离线', value: data.water.off },
    { name: '在线', value: data.water.on }
  ];
  renderWater({
    title: {
      text: '水',
      left: 'center',
      top: 'bottom',
      padding: [0, 0, 15, 0],
      textStyle: {
        color: '#fff',
        fontSize: 16,
      }
    },
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 5,
          borderColor: '#fff',
          borderWidth: 1
        },
        label: {
          show: true,
          position: 'center',
          formatter: `${waterTotal.value}`,
          fontSize: 14,
          color: '#fff',
          fontWeight: 'bold'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
          }
        },
        labelLine: {
          show: false
        },
        data:waterData
      }
    ]
  })
}
// 电
const electricity = ref();
const electricityTotal = ref();
const { renderEcharts: renderElectricity } = useEcharts(electricity);
async function fetchElectricity() {
  const data = await getHydropower()
  electricityTotal.value = data.power.off + data.power.on;
  const electricityData = [
    { name: '离线', value: data.power.off },
    { name: '在线', value: data.power.on }
  ];
  renderElectricity({
    title: {
      text: '电',
      left: 'center',
      top: 'bottom',
      padding: [0, 0, 15, 0],
      textStyle: {
        color: '#fff',
        fontSize: 16,
      }
    },
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 5,
          borderColor: '#fff',
          borderWidth: 1
        },
        label: {
          show: true,
          position: 'center',
          formatter: `${electricityTotal.value}`,
          fontSize: 14,
          color: '#fff',
          fontWeight: 'bold'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
          }
        },
        labelLine: {
          show: false
        },
        data:electricityData
      }
    ]
  })
}
// 门禁
const accessControl = ref();
const accessControlTotal = ref();
const { renderEcharts: renderAccessControl } = useEcharts(accessControl);
async function fetchAccessControl() {
  const data = await getAccessControl()
  accessControlTotal.value = data.off + data.on;
  const accessControlData = [
    { name: '离线', value: data.off },
    { name: '在线', value: data.on }
  ];
  renderAccessControl({
    title: {
      text: '门禁',
      left: 'center',
      top: 'bottom',
      padding: [0, 0, 15, 0],
      textStyle: {
        color: '#fff',
        fontSize: 16,
      }
    },
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 5,
          borderColor: '#fff',
          borderWidth: 1
        },
        label: {
          show: true,
          position: 'center',
          formatter: `${accessControlTotal.value}`,
          fontSize: 14,
          color: '#fff',
          fontWeight: 'bold'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
          }
        },
        labelLine: {
          show: false
        },
        data:accessControlData
      }
    ]
  })
}
// 摄像头
const camera = ref();
const cameraTotal = ref();
const { renderEcharts: renderCamera } = useEcharts(camera);
async function fetchCamera() {
  const data = await getCamera()
  cameraTotal.value = data.off + data.on;
  const cameraData = [
    { name: '离线', value: data.off },
    { name: '在线', value: data.on }
  ];
  renderCamera({
    title: {
      text: '摄像头',
      left: 'center',
      top: 'bottom',
      padding: [0, 0, 15, 0],
      textStyle: {
        color: '#fff',
        fontSize: 16,
      }
    },
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 5,
          borderColor: '#fff',
          borderWidth: 1
        },
        label: {
          show: true,
          position: 'center',
          formatter: `${cameraTotal.value}`,
          fontSize: 14,
          color: '#fff',
          fontWeight: 'bold'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
          }
        },
        labelLine: {
          show: false
        },
        data:cameraData
      }
    ]
  })
}
const total = computed(() => {
  return Number(waterTotal.value) + Number(electricityTotal.value) + Number(cameraTotal.value) + Number(accessControlTotal.value);
});
//顶部 电
const powerMonth = ref();
const powerYear = ref();
function fetchPowerDate(data) {
  powerMonth.value = data.day.nowMonth.total;
  powerYear.value = data.month.nowYear.total;
}


import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import 'echarts-gl';
import {
  addChartToResizeManager,
  removeChartFromResizeManager,
} from '#/utils/echartsResize';
import { useFlexibleRem } from '#/utils/useFlexibleRem';
import {DatePicker} from "ant-design-vue";
useFlexibleRem();
// 路由
const router = useRouter();
// 图表实例
const barChart = ref<HTMLElement>();
const powerChart = ref<HTMLElement>();
const envChart = ref<HTMLElement>();

// 定时器
let timer: number | null = null;
// 星期几
const weekDay = ref('');
// 图表实例
let powerChartInstance: echarts.ECharts | null = null;
let envChartInstance: echarts.ECharts | null = null;

// 退出方法
const logout = () => {
  router.push('/analytics');
};
const goWorkOrder = () => {
  router.push('/property/business/workOrders');
};
const goVisitor = () => {
  router.push('/property/visitorManagement/visitorInvitation');
};
const goPower = () => {
  router.push('/energy/electricEnergy/elctricitySituation');
};
const goCar = () => {
  router.push('/sis/passRecord/carPassRecordManagement');
};
const goReservationRecords = () => {
  router.push('/property/roomBooking/conferenceReservationRecords');
};
const goWarningProcessing = () => {
  router.push('/sis/videoWarning/videoWarningProcessing');
};
// 更新时间
const updateTime = () => {
  const now = new Date();
  const time = now.toLocaleTimeString('zh-CN', { hour12: false });
  const date =
    now.getFullYear() +
    '.' +
    String(now.getMonth() + 1).padStart(2, '0') +
    '.' +
    String(now.getDate()).padStart(2, '0');

  // 获取星期几
  const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
  weekDay.value = '星期' + weekDays[now.getDay()];

  const timeElement = document.getElementById('time');
  const dateElement = document.getElementById('date');

  if (timeElement) timeElement.innerText = time;
  if (dateElement) dateElement.innerText = date;
};

//工单
const initBarChart = async () => {
  if (!barChart.value) return;
  const myChart = echarts.init(barChart.value);
  const workOrder = await getworkOrder();
  const title = workOrder.map((item) => {return item.type})
  const statuses = ['已派单', '处理中', '已完成', '创建工单'];
  const seriesData = statuses.map(status => {
    return {
      name: status,
      type: 'bar',
      emphasis: { focus: 'series' },
      data: workOrder.map(item => item.statusCounts[status])
    };
  });
  myChart.setOption({
    tooltip: {},
    legend: {
      data: statuses,
      top: 10,
      textStyle: {
        color: '#fff'
      }
    },
    grid: { left: 40, right: 20, top: 50, bottom: 25 },
    xAxis: { data: title ,axisLabel: { color: '#fff' },},
    yAxis: {axisLabel: { color: '#fff' },},
    series:seriesData,
  });
};

// 访客
const initPowerChart = async () => {
  if (!powerChart.value) return;
  const chart = echarts.init(powerChart.value);
  const res = await getVisitorCount()
  const visitorData = [];
  const invitationData = [];
  res.forEach(item => {
    const { type, todayCounts } = item;
    Object.entries(todayCounts).forEach(([date, count]) => {
      const dataItem = { date, value: count };
      if (type === "访客") {
        visitorData.push(dataItem);
      } else if (type === "邀约") {
        invitationData.push(dataItem);
      }
    });
  });
  const dates = visitorData.map(item => item.date);
  const visitor = visitorData.map(item => item.value);
  const invitation = invitationData.map(item => item.value);
  console.log(dates,1,visitor,2,invitation)
  const option = {
    tooltip: { trigger: 'axis' },
    grid: { left: 40, right: 20, top: 50, bottom: 20 },
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: { lineStyle: { color: '#3ec6ff' } },
      axisLabel: { color: '#fff' },
    },
    yAxis: {
      type: 'value',
      axisLine: { lineStyle: { color: '#3ec6ff' } },
      axisLabel: { color: '#fff' },
      splitLine: { lineStyle: { color: '#1e90ff22' } },
    },
    series: [
      {
        name: '访客',
        data: visitor,
        type: 'line',
        smooth: true,
        itemStyle: { color: '#b388ff' },
        lineStyle: { width: 3 },
        areaStyle: { color: 'rgba(179,136,255,0.2)' },
        symbol: 'circle',
        symbolSize: 0,
      },
      {
        name: '邀约',
        data: invitation,
        type: 'line',
        smooth: true,
        itemStyle: { color: '#ffb300' },
        lineStyle: { width: 3 },
        areaStyle: { color: 'rgba(255,179,0,0.15)' },
        symbol: 'circle',
        symbolSize: 0,
      },
    ],
  };
  chart.setOption(option);
  powerChartInstance = chart;
  addChartToResizeManager(chart);
};

// 人流车流
const initEnvChart = async () => {
  if (!envChart.value) return;
  const data = await queryTwentyfourRunningDatasByPlNos()
  const inCounts = data.data.inCounts
  const staticTimeStrs = data.data.staticTimeStrs
  const chart = echarts.init(envChart.value);
  const option = {
    tooltip: { trigger: 'axis' },
    grid: { left: 40, right: 20, top: 40, bottom: 30 },
    xAxis: {
      type: 'category',
      data: staticTimeStrs,
      axisLine: { lineStyle: { color: '#3ec6ff' } },
      axisLabel: { color: '#fff' },
    },
    yAxis: {
      type: 'value',
      axisLine: { lineStyle: { color: '#3ec6ff' } },
      axisLabel: { color: '#fff' },
      splitLine: { lineStyle: { color: '#1e90ff22' } },
    },
    series: [
      {
        name: '车流',
        data: inCounts,
        type: 'line',
        smooth: true,
        itemStyle: { color: '#b388ff' },
        lineStyle: { width: 3 },
        areaStyle: { color: 'rgba(179,136,255,0.2)' },
        symbol: 'circle',
        symbolSize: 0,
      },
      // {
      //   name: '去年',
      //   data: [80, 120, 100, 180, 150, 120, 60, 40],
      //   type: 'line',
      //   smooth: true,
      //   itemStyle: { color: '#ffb300' },
      //   lineStyle: { width: 3 },
      //   areaStyle: { color: 'rgba(255,179,0,0.15)' },
      //   symbol: 'circle',
      //   symbolSize: 0,
      // },
    ],
  };
  chart.setOption(option);
  envChartInstance = chart;
  addChartToResizeManager(chart);
};

// 组件挂载时初始化
onMounted(() => {
  getWarning()
  handleTodayMeetCount()
  fetchWater()
  fetchElectricity()
  fetchAccessControl()
  fetchCamera()

  updateTime();
  timer = setInterval(updateTime, 1000);
  initBarChart();
  initPowerChart();
  initEnvChart();
});

// 组件卸载时清理
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer);
  }
  // 从管理器中移除图表
  if (powerChartInstance) {
    removeChartFromResizeManager(powerChartInstance);
    powerChartInstance.dispose();
  }
  if (envChartInstance) {
    removeChartFromResizeManager(envChartInstance);
    envChartInstance.dispose();
  }
});
</script>

<style scoped>
.white-text-datepicker :deep(.ant-picker-input > input::placeholder) {
  color: #fff !important;
}
.white-text-datepicker :deep(.ant-picker-input > input) {
  color: white !important;
}
.white-text-datepicker :deep(.ant-picker-suffix > .anticon) {
  color: white !important;
}
@font-face {
  font-family: 'ShiShangZhongHeiJianTi';
  src: url('../../../assets/fonts/时尚中黑简体.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}
.mian {
  height: 100vh;
  background: url('../../../assets/property/bg.jpg');
  background-size: 100% 100%;
  background-color: #081b3a;
  display: flex;
  flex-direction: column;
}
.title {
  height: 5.375rem;
  align-items: center;
  display: flex;
  justify-content: space-between;
  .left {
    display: flex;
    width: 18.3125rem;
    .left-first {
      padding-left: 2.3125rem;
      font-size: 1.875rem;
      width: 10.5rem;
      color: #ffffff;
    }
    .left-second {
      width: 6.5rem;
      font-family: ShiShangZhongHeiJianTi;
      font-weight: 400;
      font-size: 1.25rem;
      color: #ffffff;
    }
  }
  .center {
    font-size: 1.9rem;
    color: #fff;
    text-align: center;
    font-weight: bold;
    letter-spacing: 0.1em;
    text-shadow:
      0 0 10px #1e90ff,
      0 0 20px #1e90ff;
  }
  .right {
    width: 17.3125rem;
    display: flex;
    font-family: ShiShangZhongHeiJianTi;
    font-weight: 400;
    font-size: 1.25rem;
    color: #ffffff;
    gap: 0.75rem;
    .logout {
      display: flex;
      cursor: pointer;
      align-items: center;
      gap: 0.2rem;
    }
  }
}
.header {
  margin-top: 1.125rem;
  margin-left: 4.625rem;
  margin-right: 4.25rem;
  height: 6rem;
  display: flex;
  justify-content: space-between;
  .header-item {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 1.5rem;
    border-radius: 0.5rem;
    box-shadow:
      0 0 10px #0ff2,
      0 0 20px #0ff2 inset;
  }
  .header-label {
    color: #fff;
    font-size: 1rem;
    margin-right: 0.5rem;
    letter-spacing: 0.05em;
  }
  .header-value {
    font-size: 1.5rem;
    font-weight: bold;
    margin: 0 0.2rem;
    font-family: ShiShangZhongHeiJianTi;
  }
  .header-value.orange {
    color: #ffb300;
  }
  .header-value.green {
    color: #00ffb0;
  }
  .header-value.blue {
    color: #3ec6ff;
  }
  .header-value.purple {
    color: #b388ff;
  }
  .header-unit {
    color: #fff;
    font-size: 1rem;
    margin-left: 0.2rem;
  }
}
.header div {
  width: 20.125rem;
}
.contents {
  flex: 1;
  .content {
    height: 100%;
    display: flex;
    justify-content: space-between;
    margin: 0 2.25rem 2.25rem 2.25rem;
    .content-left {
      width: 32.6875rem;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .first {
        height: 16.81rem;
        .bar-chart {
          margin-top: 35px;
        }
      }
      .second {
        height: 12rem;
        .power-chart {
          height: 100%;
        }
      }
      .third {
        height: 12.12rem;
        .env-chart {
          height: 12rem;
        }
      }
    }
    .content-center {
      width: 47.5rem;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .content-center-first {
        height: 30.9rem;
        .first-item {
          height: 100%;
          width: 100%;
          background: url('../../../assets/property/center-bg.png');
          background-size: 95% 95%;
          background-repeat: no-repeat;
          background-position: center;
        }
      }
      .content-center-second {
        height: 12.5rem;
        display: flex;
        justify-content: space-around;
        .offline,.online {
          display: flex;
          align-items: center;
          gap: 8px;
          color: #fff;
          font-size: 14px;
        }
        .offline::before,.online::before {
          content: "";
          width: 30px;
          height: 15px;
          border-radius: 3px;
          border: 1.5px solid #fff;
        }
        .offline::before{
          background-color: #5470C6;
        }
        .online::before {
          background-color: #9CDB7D;
        }
      }
    }
    .content-right {
      width: 32.68rem;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .first {
        height: 16.81rem;
      }
      .second {
        height: 11rem;
        margin-top: 2rem;
        margin-bottom: 2rem;
        .second-box {
          margin-left: 0.5rem;
          margin-top: 3.5rem;
          display: flex;
          justify-content: space-around;
          align-items: center;
          .box-content {
            height: 7rem;
            width: 7rem;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            .box-content-label {
              font-family: Microsoft YaHei;
              font-weight: 400;
              font-size: 0.8rem;
              color: #c4d6ff;
              line-height: 2rem;
            }
            .box-content-num {
              display: flex;
              justify-content: center;
              align-items: center;
              width: 6rem;
              height: 6rem;
              background: url('../../../assets/property/customer-circle.png');
              background-size: 100% 100%;
              font-family: Microsoft YaHei;
              font-weight: 400;
              font-size: 1.2rem;
              color: #ffffff;
            }
          }
        }
      }
      .third {
        padding: 5rem;
        height: 13.12rem;
        display: flex;
        justify-content: space-around;
        align-items: center;
        .third-item{
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          .third-title{
            font-family: Microsoft YaHei;
            font-weight: 400;
            font-size: 0.8rem;
            color: #c4d6ff;
            line-height: 2rem;
          }
          .third-num{
            display: flex;
            justify-content: center;
            align-items: center;
            width: 6rem;
            height: 4rem;
            background: url('../../../assets/monitor/device-alerts-bg2.png');
            background-size: 100% 100%;
            font-family: Microsoft YaHei;
            font-weight: 400;
            font-size: 1.2rem;
            color: #ffffff;
          }
        }
      }
    }
  }
}
</style>
