
<template>
<div class="ssyx-ems-dashboard-editor-container">
<!--  6个方块-->
  <real-time-base-info :display-data="runningDisplayData" :loading="runningHeadLoading" @field-click="handleHeadFieldClick"/>
  <!-- 时间选择 -->
  <date-range-select ref="dateRangeSelect" @updateDate="updateDate" style="margin-top:20px;"/>
<!--  echart图表-->
  <el-row :gutter="32" style="background:#fff;margin:30px 0;">
    <el-col :xs="24" :sm="12" :lg="12">
      <cnglqx-chart ref='cnglqx' :display-data="runningDisplayData"/>
    </el-col>
    <el-col :xs="24" :sm="12" :lg="12">
      <pocpjwd-chart ref='pocpjwd' :display-data="runningDisplayData"/>
    </el-col>
  </el-row>
  <el-row :gutter="32" style="margin:30px 0;">
    <el-col :xs="24" :sm="12" :lg="12">
      <dcpjsoc-chart ref="dcpjsoc" :display-data="runningDisplayData"/>
    </el-col>
    <el-col :xs="24" :sm="12" :lg="12">
      <dcpjwd-chart ref="dcpjwd" :display-data="runningDisplayData"/>
    </el-col>
  </el-row>

  <el-dialog
    :visible.sync="curveDialogVisible"
    :title="curveDialogTitle"
    width="1000px"
    append-to-body
    class="ems-dialog"
    :close-on-click-modal="false"
    destroy-on-close
    @opened="handleCurveDialogOpened"
    @closed="handleCurveDialogClosed"
  >
    <div class="curve-tools">
      <el-date-picker
        v-model="curveCustomRange"
        type="datetimerange"
        value-format="yyyy-MM-dd HH:mm:ss"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        style="width: 440px"
      />
      <el-button type="primary" size="mini" :loading="curveLoading" @click="loadCurveData">查询</el-button>
    </div>
    <div v-loading="curveLoading" ref="curveChartRef" style="height: 380px;"></div>
  </el-dialog>
</div>
</template>

<style scoped lang="scss">
.curve-tools {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
<script>
import * as echarts from "echarts";
import DateRangeSelect from '@/components/Ems/DateRangeSelect/index.vue'
import RealTimeBaseInfo from "./../RealTimeBaseInfo.vue";
import CnglqxChart from './CnglqxChart.vue'
import PocpjwdChart from './PocpjwdChart.vue'
import DcpjwdChart from './DcpjwdChart.vue'
import DcpjsocChart from './DcpjsocChart.vue'
import getQuerySiteId from "@/mixins/ems/getQuerySiteId";
import {getProjectDisplayData} from '@/api/ems/dzjk'
import {getPointConfigCurve} from "@/api/ems/site";
import intervalUpdate from "@/mixins/ems/intervalUpdate";

export default {
  name:'DzjkSbjkSsyx',
  components:{RealTimeBaseInfo,CnglqxChart,PocpjwdChart,DcpjwdChart,DcpjsocChart,DateRangeSelect},
  mixins:[getQuerySiteId,intervalUpdate],
  data() {
    return {
      runningDisplayData: [], //单站监控项目配置展示数据
      timeRange:[],
      isInit:true,
      runningHeadLoading: false,
      curveDialogVisible: false,
      curveDialogTitle: "点位曲线",
      curveChart: null,
      curveLoading: false,
      curveCustomRange: [],
      curveQuery: {
        siteId: "",
        pointId: "",
        pointType: "data",
        rangeType: "custom",
        startTime: "",
        endTime: "",
      },
    }
  },
  beforeDestroy() {
    if (this.curveChart) {
      this.curveChart.dispose();
      this.curveChart = null;
    }
  },
  methods:{
    handleHeadFieldClick(item) {
      const pointId = String(item?.pointId || item?.raw?.dataPoint || "").trim();
      if (!pointId) {
        this.$message.warning("该字段未配置点位，无法查询曲线");
        return;
      }
      this.openCurveDialog({
        pointId,
        title: item?.title || item?.raw?.fieldName || pointId,
      });
    },
    openCurveDialog({pointId, title}) {
      const range = this.getDefaultCurveRange();
      this.curveCustomRange = range;
      this.curveDialogTitle = `点位曲线 - ${title || pointId}`;
      this.curveQuery = {
        siteId: this.siteId,
        pointId,
        pointType: "data",
        rangeType: "custom",
        startTime: range[0],
        endTime: range[1],
      };
      this.curveDialogVisible = true;
    },
    handleCurveDialogOpened() {
      if (!this.curveChart && this.$refs.curveChartRef) {
        this.curveChart = echarts.init(this.$refs.curveChartRef);
      }
      this.loadCurveData();
    },
    handleCurveDialogClosed() {
      if (this.curveChart) {
        this.curveChart.dispose();
        this.curveChart = null;
      }
      this.curveLoading = false;
    },
    getDefaultCurveRange() {
      const end = new Date();
      const start = new Date(end.getTime() - 24 * 60 * 60 * 1000);
      return [this.formatDateTime(start), this.formatDateTime(end)];
    },
    formatDateTime(date) {
      const d = new Date(date);
      const pad = (num) => String(num).padStart(2, "0");
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
    },
    formatCurveTime(value) {
      if (value === undefined || value === null || value === "") {
        return "";
      }
      const raw = String(value).trim();
      const normalized = raw
        .replace("T", " ")
        .replace(/\.\d+/, "")
        .replace(/Z$/, "")
        .replace(/([+-]\d{2}:?\d{2})$/, "")
        .trim();
      const matched = normalized.match(/^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})/);
      if (matched) {
        return `${matched[1]} ${matched[2]}`;
      }
      return normalized.slice(0, 16);
    },
    loadCurveData() {
      if (!this.curveQuery.siteId || !this.curveQuery.pointId) {
        this.$message.warning("点位信息不完整，无法查询曲线");
        return;
      }
      if (!this.curveCustomRange || this.curveCustomRange.length !== 2) {
        this.$message.warning("请选择查询时间范围");
        return;
      }
      this.curveQuery.startTime = this.curveCustomRange[0];
      this.curveQuery.endTime = this.curveCustomRange[1];
      const query = {
        siteId: this.curveQuery.siteId,
        pointId: this.curveQuery.pointId,
        pointType: "data",
        rangeType: "custom",
        startTime: this.curveQuery.startTime,
        endTime: this.curveQuery.endTime,
      };
      this.curveLoading = true;
      getPointConfigCurve(query).then((response) => {
        const rows = response?.data || [];
        this.renderCurveChart(rows);
      }).catch(() => {
        this.renderCurveChart([]);
      }).finally(() => {
        this.curveLoading = false;
      });
    },
    renderCurveChart(rows = []) {
      if (!this.curveChart) return;
      const xData = rows.map(item => this.formatCurveTime(item.dataTime));
      const yData = rows.map(item => item.pointValue);
      this.curveChart.clear();
      this.curveChart.setOption({
        legend: {},
        grid: {
          containLabel: true,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        textStyle: {
          color: "#333333",
        },
        xAxis: {
          type: "category",
          data: xData,
        },
        yAxis: {
          type: "value",
        },
        dataZoom: [
          {
            type: "inside",
            start: 0,
            end: 100,
          },
          {
            start: 0,
            end: 100,
          },
        ],
        series: [
          {
            name: this.curveDialogTitle,
            type: "line",
            data: yData,
            connectNulls: true,
          },
        ],
      });
      if (!rows.length) {
        this.$message.warning("当前时间范围暂无曲线数据");
      }
    },
    //6个方块数据
    getRunningHeadData(){
      this.runningHeadLoading = true
      return getProjectDisplayData(this.siteId).then((displayResponse) => {
        this.runningDisplayData = displayResponse?.data || []
      }).finally(() => {
        this.runningHeadLoading = false
      })
    },
    // 更新时间范围 重置图表
    updateDate(data){
      this.timeRange=data
      !this.isInit && this.updateChart()
      this.isInit = false
    },
    updateChart(){
      this.$refs.cnglqx.init(this.siteId,this.timeRange||[])
      this.$refs.pocpjwd.init(this.siteId,this.timeRange||[])
      this.$refs.dcpjsoc.init(this.siteId,this.timeRange||[])
      this.$refs.dcpjwd.init(this.siteId,this.timeRange||[])
      this.updateInterval(this.updateData)
    },
    updateData(){
      this.getRunningHeadData().finally(() => {
        this.updateChart()
      })
    },
    init(){
      this.$refs.dateRangeSelect.init(true)
      this.$nextTick(()=>{
        this.updateData()
      })
    }
  }

}
</script>
