<template>
  <div class="p-2">
    <el-row :gutter="28">
      <el-col :span="4.3" :xs="24">
        <div class="head-container">
          <el-input
            v-model="workUnitName"
            placeholder="请输入计量设备名称"
            clearable

            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="monitorInfoOptions"
            :props="monitorProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="19" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
                 label-width="100px"
        >
          <!--          <el-form-item label="计量设备编号" prop="monitorCode">-->
          <!--            <el-input-->
          <!--              v-model="queryParams.monitorCode"-->
          <!--              placeholder="请输入计量设备编号"-->
          <!--              clearable-->
          <!--              @keyup.enter="handleQuery"-->
          <!--            />-->
          <!--          </el-form-item>-->
          <el-form-item label="采集时间">
            <el-date-picker
              v-model="daterangeCollectTime"
              style="width: 340px"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <Chart ref="chartCurrentRef" class="chart1" />
        <Chart ref="chartVoltageRef" class="chart2" />
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts" name="CurrentVoltageCurve">
import { ref, reactive, watch, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { dnbInstantList } from '@/api/ems/record/recordDnbInstant';
import { getMonitorInfoTree } from '@/api/ems/base/baseMonitorInfo';
import { parseTime } from '@/utils/ruoyi';
import Chart from '@/components/chart.vue';
import * as echarts from 'echarts';
import type { ElTree } from 'element-plus';
import type { EChartsOption } from 'echarts';

const route = useRoute();

const treeRef = ref<InstanceType<typeof ElTree>>();
const chartCurrentRef = ref<InstanceType<typeof Chart>>();
const chartVoltageRef = ref<InstanceType<typeof Chart>>();
const queryFormRef = ref();

const monitorInfoOptions = ref<any[]>([]);
const workUnitName = ref<string>('');
const daterangeCollectTime = ref<string[]>([]);
const selectMonitorName = ref<string>('');
const loading = ref(false);
const showSearch = ref(true);

const monitorProps = {
  children: 'children',
  label: 'label'
};

const queryParams = reactive<{ monitorCode?: string; params: Record<string, string> }>(
  {
    monitorCode: (route.query.monitorCode as string) || undefined,
    params: {}
  }
);

watch(workUnitName, (val) => {
  treeRef.value?.filter(val);
});

function handleQuery() {
  getList();
}

function resetQuery() {
  queryParams.monitorCode = undefined;
  daterangeCollectTime.value = [];
  queryParams.params = {};
  queryFormRef.value?.resetFields();
  handleQuery();
}

function getList() {
  loading.value = true;
  queryParams.params = {};
  if (daterangeCollectTime.value?.length === 2) {
    queryParams.params.beginCollectTime = daterangeCollectTime.value[0];
    queryParams.params.endCollectTime = daterangeCollectTime.value[1];
  }
  getChart().finally(() => {
    loading.value = false;
  });
}

function getTreeselect() {
  getMonitorInfoTree({ monitorType: 2 }).then((response) => {
    monitorInfoOptions.value = response.data;
  });
}

function filterNode(value: string, data: any) {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
}

function handleNodeClick(data: any) {
  queryParams.monitorCode = data.code;
  selectMonitorName.value = data.label;
  handleQuery();
}

async function getChart() {
  if (!queryParams.monitorCode) {
    chartCurrentRef.value?.setData({});
    chartVoltageRef.value?.setData({});
    return;
  }

  const query = {
    monitorCode: queryParams.monitorCode,
    params: { ...queryParams.params }
  };

  const { data } = await dnbInstantList(query);
  if (!Array.isArray(data) || data.length === 0) {
    chartCurrentRef.value?.setData({});
    chartVoltageRef.value?.setData({});
    return;
  }

  const collectTimes = data.map((item: any) => item.collectTime);

  const currentOption: EChartsOption = {
    title: { text: `${selectMonitorName.value} 电流曲线`, left: 'center' },
    grid: { top: 50, bottom: 70, left: 60, right: 40, containLabel: true },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross', label: { show: true } }
    },
    dataZoom: [
      { type: 'slider', height: 20, bottom: 8, start: 0, end: 100 },
      { type: 'inside', zoomOnMouseWheel: true, moveOnMouseMove: true }
    ],
    legend: { right: 0, top: 5 },
    xAxis: {
      type: 'category',
      data: collectTimes,
      axisLine: { lineStyle: { color: '#000' } },
      axisTick: { show: true, alignWithLabel: true },
      axisLabel: {
        color: '#000',
        rotate: collectTimes.length > 20 ? 45 : 0,
        interval: 'auto',
        formatter: (value: string) => value && value.length > 16 ? value.substring(11, 19) : value
      }
    },
    yAxis: [{
      type: 'value',
      name: '电流（A）',
      nameTextStyle: { color: '#000' },
      splitLine: { show: true, lineStyle: { type: 'dashed', color: '#e0e0e0' } },
      axisTick: { show: true },
      axisLine: { lineStyle: { color: '#000' } },
      axisLabel: {
        color: '#000',
        formatter: (value: number) => Math.abs(value) >= 1000 ? (value / 1000).toFixed(1) + 'k' : value.toFixed(1)
      },
      scale: true,
      splitNumber: 5
    }],
    series: [
      { name: 'A相电流', type: 'line', smooth: true, symbol: 'circle', symbolSize: 6, data: data.map((item: any) => item.ia) },
      { name: 'B相电流', type: 'line', smooth: true, symbol: 'circle', symbolSize: 6, data: data.map((item: any) => item.ib) },
      { name: 'C相电流', type: 'line', smooth: true, symbol: 'circle', symbolSize: 6, data: data.map((item: any) => item.ic) }
    ]
  };

  const voltageOption: EChartsOption = {
    title: { text: `${selectMonitorName.value} 电压曲线`, left: 'center' },
    grid: { top: 50, bottom: 70, left: 60, right: 40, containLabel: true },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross', label: { show: true } }
    },
    dataZoom: [
      { type: 'slider', height: 20, bottom: 8, start: 0, end: 100 },
      { type: 'inside', zoomOnMouseWheel: true, moveOnMouseMove: true }
    ],
    legend: { right: 0, top: 5 },
    xAxis: {
      type: 'category',
      data: collectTimes,
      axisLine: { lineStyle: { color: '#000' } },
      axisTick: { show: true, alignWithLabel: true },
      axisLabel: {
        color: '#000',
        rotate: collectTimes.length > 20 ? 45 : 0,
        interval: 'auto',
        formatter: (value: string) => value && value.length > 16 ? value.substring(11, 19) : value
      }
    },
    yAxis: [{
      type: 'value',
      name: '电压（V）',
      nameTextStyle: { color: '#000' },
      splitLine: { show: true, lineStyle: { type: 'dashed', color: '#e0e0e0' } },
      axisTick: { show: true },
      axisLine: { lineStyle: { color: '#000' } },
      axisLabel: {
        color: '#000',
        formatter: (value: number) => Math.abs(value) >= 1000 ? (value / 1000).toFixed(1) + 'k' : value.toFixed(1)
      },
      scale: true,
      splitNumber: 5
    }],
    series: [
      { name: 'A相电压', type: 'line', smooth: true, symbol: 'circle', symbolSize: 6, data: data.map((item: any) => item.va) },
      { name: 'B相电压', type: 'line', smooth: true, symbol: 'circle', symbolSize: 6, data: data.map((item: any) => item.vb) },
      { name: 'C相电压', type: 'line', smooth: true, symbol: 'circle', symbolSize: 6, data: data.map((item: any) => item.vc) }
    ]
  };

  chartCurrentRef.value?.setData(currentOption);
  chartVoltageRef.value?.setData(voltageOption);

  const chartCurrent = chartCurrentRef.value?.chart;
  const chartVoltage = chartVoltageRef.value?.chart;
  if (!chartCurrent || !chartVoltage) {
    return;
  }

  echarts.connect([chartCurrent, chartVoltage]);

  chartCurrent.on('datazoom', (event: any) => {
    if (Array.isArray(voltageOption.dataZoom) && voltageOption.dataZoom[0]) {
      voltageOption.dataZoom[0] = {
        ...(voltageOption.dataZoom[0] as Record<string, any>),
        start: event.start,
        end: event.end
      };
      chartVoltageRef.value?.setData(voltageOption);
    }
  });

  chartVoltage.on('datazoom', (event: any) => {
    if (Array.isArray(currentOption.dataZoom) && currentOption.dataZoom[0]) {
      currentOption.dataZoom[0] = {
        ...(currentOption.dataZoom[0] as Record<string, any>),
        start: event.start,
        end: event.end
      };
      chartCurrentRef.value?.setData(currentOption);
    }
  });
}

onMounted(() => {
  const nowDate = parseTime(new Date(), '{y}-{m}-{d}') as string;
  daterangeCollectTime.value = [`${nowDate} 00:00:00`, `${nowDate} 23:59:59`];
  getTreeselect();
  getList();
});
</script>
<style scoped>
.chart1,
.chart2 {
  width: 100%;
  height: calc(50vh - 80px);
  min-height: 280px;
  max-height: 400px;
}

@media screen and (max-width: 1200px) {
  .chart1,
  .chart2 {
    height: calc(45vh - 60px);
    min-height: 250px;
  }
}

@media screen and (max-width: 768px) {
  .chart1,
  .chart2 {
    height: 40vh;
    min-height: 220px;
  }
}
</style>
